Javier-Jimenez99 commited on
Commit
ba4c5ab
·
1 Parent(s): 7d1fb1e

Actualizar mensajes y etiquetas en inglés en la interfaz de usuario y el historial de ejecución para mejorar la claridad y la consistencia.

Browse files
Files changed (2) hide show
  1. app.py +30 -33
  2. prompt.txt +10 -7
app.py CHANGED
@@ -47,7 +47,7 @@ def add_to_execution_history(step_type: str, data: Any, tab_id: str = None):
47
  def format_execution_history():
48
  """Format the execution history for display"""
49
  if not execution_history:
50
- return "No hay historial de ejecución aún."
51
 
52
  formatted_history = []
53
  for entry in execution_history:
@@ -56,14 +56,14 @@ def format_execution_history():
56
  tab_id = entry.get("tab_id", "N/A")
57
 
58
  if step_type == "user_input":
59
- formatted_history.append(f"**[{timestamp}] 👤 Usuario (Tab: {tab_id})**\n\n{entry['data']}\n\n")
60
  elif step_type == "agent_response":
61
- formatted_history.append(f"**[{timestamp}] 🤖 Agente**\n\n{entry['data']}\n\n")
62
  elif step_type == "tool_call":
63
  tool_data = entry['data']
64
- formatted_history.append(f"**[{timestamp}] 🔧 Llamada a Herramienta**\n\n**Herramienta**: {tool_data['name']}\n\n**Argumentos**: \n\n```json\n{json.dumps(tool_data.get('args', {}), indent=2)}\n```\n\n")
65
  elif step_type == "tool_result":
66
- formatted_history.append(f"**[{timestamp}] ✅ Resultado de Herramienta**\n\n```\n{entry['data']}\n```\n\n")
67
  elif step_type == "error":
68
  formatted_history.append(f"**[{timestamp}] ❌ Error**\n\n{entry['data']}\n\n")
69
 
@@ -146,8 +146,7 @@ async def chat(history: list, tab_id: str=None, anthropic_api_key: str=None):
146
  "name": tool_call.get("name", "unknown"),
147
  "args": tool_call.get("args", {})
148
  }, tab_id)
149
-
150
- # Check if it's a tool message (result of tool execution)
151
  if hasattr(msg, 'name') and msg.name:
152
  add_to_execution_history("tool_result", msg.content, tab_id)
153
 
@@ -158,7 +157,7 @@ async def chat(history: list, tab_id: str=None, anthropic_api_key: str=None):
158
  return cleaned
159
 
160
  except Exception as e:
161
- error_msg = f"Error durante la ejecución: {str(e)}"
162
  add_to_execution_history("error", error_msg, tab_id)
163
  return error_msg
164
 
@@ -215,8 +214,7 @@ async def chat_with_history_tracking(message: str, history: List, tab_id: str =
215
  # Check if it's a tool message (result of tool execution)
216
  if hasattr(msg, 'name') and msg.name:
217
  add_to_execution_history("tool_result", msg.content, tab_id)
218
-
219
- # Get the final output
220
  output = all_messages[-1].content
221
  cleaned = re.sub(r'<think>.*?</think>', '', output, flags=re.DOTALL).strip()
222
 
@@ -226,7 +224,7 @@ async def chat_with_history_tracking(message: str, history: List, tab_id: str =
226
  return history, format_execution_history()
227
 
228
  except Exception as e:
229
- error_msg = f"Error durante la ejecución: {str(e)}"
230
  add_to_execution_history("error", error_msg, tab_id)
231
  history.append([message, error_msg])
232
  return history, format_execution_history()
@@ -235,19 +233,19 @@ def clear_history():
235
  """Clear the execution history"""
236
  global execution_history
237
  execution_history = []
238
- return [], "Historial de ejecución limpiado."
239
 
240
  # Create the enhanced Gradio interface
241
- with gr.Blocks(title="OwlBear Agent - Historial Completo", theme=gr.themes.Default()) as demo:
242
- gr.Markdown("# 🦉 OwlBear Agent - Vista Completa de Ejecución")
243
- gr.Markdown("Esta interfaz muestra todo el proceso de ejecución del agente, incluyendo llamadas a herramientas y pasos intermedios.")
244
- gr.Markdown("**Nota:** Todos los mensajes enviados a la API original también aparecen aquí automáticamente.")
245
 
246
  with gr.Row():
247
  with gr.Column(scale=1):
248
  gr.Markdown("## 💬 Chat")
249
  chatbot = gr.Chatbot(
250
- label="Conversación",
251
  height=400,
252
  show_label=True,
253
  container=True,
@@ -255,41 +253,41 @@ with gr.Blocks(title="OwlBear Agent - Historial Completo", theme=gr.themes.Defau
255
 
256
  with gr.Row():
257
  msg = gr.Textbox(
258
- label="Mensaje",
259
- placeholder="Escribe tu mensaje aquí...",
260
  lines=2,
261
  scale=4
262
  )
263
- send_btn = gr.Button("Enviar", variant="primary", scale=1)
264
 
265
  with gr.Row():
266
  tab_id = gr.Textbox(
267
  label="Tab ID",
268
- placeholder="ID de pestaña (opcional)",
269
  value="main",
270
  scale=1
271
  )
272
  anthropic_key = gr.Textbox(
273
  label="Anthropic API Key",
274
- placeholder="Clave API de Anthropic (opcional)",
275
  type="password",
276
  scale=2
277
  )
278
 
279
- clear_btn = gr.Button("Limpiar Chat", variant="secondary")
280
 
281
  with gr.Column(scale=1):
282
- gr.Markdown("## 📊 Historial de Ejecución Detallado")
283
- gr.Markdown("*Se actualiza automáticamente cada 2 segundos*")
284
  execution_display = gr.Markdown(
285
- value="No hay historial de ejecución aún.",
286
- label="Historial Completo",
287
  height=600,
288
  container=True,
289
  )
290
 
291
- refresh_btn = gr.Button("Actualizar Historial", variant="secondary")
292
- clear_history_btn = gr.Button("Limpiar Historial", variant="secondary")
293
 
294
  # Auto-refresh timer for execution history
295
  timer = gr.Timer(value=2) # Refresh every 2 seconds
@@ -352,15 +350,14 @@ api_demo = gr.Interface(
352
  gr.Textbox(label="tab_id"),
353
  gr.Textbox(label="anthropic_api_key"),
354
  ],
355
- outputs="text",
356
- title="OwlBear Agent - API Original"
357
  )
358
 
359
  # Combined interface with tabs
360
  combined_demo = gr.TabbedInterface(
361
  [demo, api_demo],
362
- ["Vista Completa con Historial", "API Original"],
363
- title="🦉 OwlBear Agent - Interfaz Completa"
364
  )
365
 
366
  if __name__ == "__main__":
 
47
  def format_execution_history():
48
  """Format the execution history for display"""
49
  if not execution_history:
50
+ return "No execution history yet."
51
 
52
  formatted_history = []
53
  for entry in execution_history:
 
56
  tab_id = entry.get("tab_id", "N/A")
57
 
58
  if step_type == "user_input":
59
+ formatted_history.append(f"**[{timestamp}] 👤 User (Tab: {tab_id})**\n\n{entry['data']}\n\n")
60
  elif step_type == "agent_response":
61
+ formatted_history.append(f"**[{timestamp}] 🤖 Agent**\n\n{entry['data']}\n\n")
62
  elif step_type == "tool_call":
63
  tool_data = entry['data']
64
+ formatted_history.append(f"**[{timestamp}] 🔧 Tool Call**\n\n**Tool**: {tool_data['name']}\n\n**Arguments**: \n\n```json\n{json.dumps(tool_data.get('args', {}), indent=2)}\n```\n\n")
65
  elif step_type == "tool_result":
66
+ formatted_history.append(f"**[{timestamp}] ✅ Tool Result**\n\n```\n{entry['data']}\n```\n\n")
67
  elif step_type == "error":
68
  formatted_history.append(f"**[{timestamp}] ❌ Error**\n\n{entry['data']}\n\n")
69
 
 
146
  "name": tool_call.get("name", "unknown"),
147
  "args": tool_call.get("args", {})
148
  }, tab_id)
149
+ # Check if it's a tool message (result of tool execution)
 
150
  if hasattr(msg, 'name') and msg.name:
151
  add_to_execution_history("tool_result", msg.content, tab_id)
152
 
 
157
  return cleaned
158
 
159
  except Exception as e:
160
+ error_msg = f"Error during execution: {str(e)}"
161
  add_to_execution_history("error", error_msg, tab_id)
162
  return error_msg
163
 
 
214
  # Check if it's a tool message (result of tool execution)
215
  if hasattr(msg, 'name') and msg.name:
216
  add_to_execution_history("tool_result", msg.content, tab_id)
217
+ # Get the final output
 
218
  output = all_messages[-1].content
219
  cleaned = re.sub(r'<think>.*?</think>', '', output, flags=re.DOTALL).strip()
220
 
 
224
  return history, format_execution_history()
225
 
226
  except Exception as e:
227
+ error_msg = f"Error during execution: {str(e)}"
228
  add_to_execution_history("error", error_msg, tab_id)
229
  history.append([message, error_msg])
230
  return history, format_execution_history()
 
233
  """Clear the execution history"""
234
  global execution_history
235
  execution_history = []
236
+ return [], "Execution history cleared."
237
 
238
  # Create the enhanced Gradio interface
239
+ with gr.Blocks(title="OwlBear Agent - Complete History", theme=gr.themes.Default()) as demo:
240
+ gr.Markdown("# 🦉 OwlBear Agent - Complete Execution View")
241
+ gr.Markdown("This interface shows the complete agent execution process, including tool calls and intermediate steps.")
242
+ gr.Markdown("**Note:** All messages sent to the original API also appear here automatically.")
243
 
244
  with gr.Row():
245
  with gr.Column(scale=1):
246
  gr.Markdown("## 💬 Chat")
247
  chatbot = gr.Chatbot(
248
+ label="Conversation",
249
  height=400,
250
  show_label=True,
251
  container=True,
 
253
 
254
  with gr.Row():
255
  msg = gr.Textbox(
256
+ label="Message",
257
+ placeholder="Type your message here...",
258
  lines=2,
259
  scale=4
260
  )
261
+ send_btn = gr.Button("Send", variant="primary", scale=1)
262
 
263
  with gr.Row():
264
  tab_id = gr.Textbox(
265
  label="Tab ID",
266
+ placeholder="Tab ID (optional)",
267
  value="main",
268
  scale=1
269
  )
270
  anthropic_key = gr.Textbox(
271
  label="Anthropic API Key",
272
+ placeholder="Anthropic API Key (optional)",
273
  type="password",
274
  scale=2
275
  )
276
 
277
+ clear_btn = gr.Button("Clear Chat", variant="secondary")
278
 
279
  with gr.Column(scale=1):
280
+ gr.Markdown("## 📊 Detailed Execution History")
281
+ gr.Markdown("*Updates automatically every 2 seconds*")
282
  execution_display = gr.Markdown(
283
+ value="No execution history yet.",
284
+ label="Complete History",
285
  height=600,
286
  container=True,
287
  )
288
 
289
+ refresh_btn = gr.Button("Refresh History", variant="secondary")
290
+ clear_history_btn = gr.Button("Clear History", variant="secondary")
291
 
292
  # Auto-refresh timer for execution history
293
  timer = gr.Timer(value=2) # Refresh every 2 seconds
 
350
  gr.Textbox(label="tab_id"),
351
  gr.Textbox(label="anthropic_api_key"),
352
  ],
353
+ outputs="text", title="OwlBear Agent - Original API"
 
354
  )
355
 
356
  # Combined interface with tabs
357
  combined_demo = gr.TabbedInterface(
358
  [demo, api_demo],
359
+ ["Complete View with History", "Original API"],
360
+ title="🦉 OwlBear Agent - Complete Interface"
361
  )
362
 
363
  if __name__ == "__main__":
prompt.txt CHANGED
@@ -1,12 +1,13 @@
1
- You are a professional Game Master specialized in running single-player medieval fantasy D&D sessions. You create personalized, proactive, and dynamic adventures that focus entirely on one player's character as the hero of their own epic story. You must maintain your persona at all times.
2
 
3
  YOUR ROLE
4
- Storyteller: Create immersive medieval fantasy adventures. You must "show, not tell," bringing the world of Aethermoor to life through powerful narration. Focus on sensory details not visible on the map.
5
  Companion: Provide helpful NPCs when needed, but keep the player as the main hero of the story.
6
  Guide: Adapt difficulty and story to the individual player's choices and preferences. Make failures into interesting story complications, not dead ends.
7
- World: Bring the medieval realm of Aethermoor to life. You must be proactive. After the player introduces their character, immediately create the starting map, place the player's token, and describe the opening scene to begin the adventure.
8
 
9
  CORE PRINCIPLES
 
10
  Player-Centered: Everything revolves around the player's character. Actively weave their provided backstory, goals, and choices into the narrative to create personal stakes.
11
  "Yes, and...": Build on player ideas creatively and incorporate them into the unfolding story.
12
  No Multiple-Choice Questions: Never present the player with a numbered or bulleted list of actions (e.g., "Do you 1, 2, or 3?"). Instead, describe the situation and ask an open-ended question like, "What do you do?" to give the player full agency.
@@ -21,8 +22,8 @@ Rich Narrative: Use vivid detail for atmosphere, character interactions, and wor
21
 
22
  ADVENTURE STRUCTURE
23
  Oneshot Format: Design adventures as complete, self-contained stories that can be finished in one session.
24
- Focused Scope: Keep the main quest simple and achievable within approximately 1 hour of play.
25
- Immediate Start: After the player introduces their character, ask for one key backstory detail (a goal, a rival, a lost item). Then, immediately create the map, place the token, and launch into the opening scene. Do not wait to be asked.
26
  Clear Goals: Each adventure should have a specific, attainable objective that is introduced early.
27
 
28
  DURING PLAY
@@ -37,9 +38,11 @@ Remember: You're crafting personal oneshot adventures where the player is the st
37
 
38
  TOOL MANAGEMENT:
39
  Game State: It represents perfectly the current state of the game, including items, map and fog.
40
- War Fog: If it is enabled, the player will not see anything unless it has a light source attached to it.
41
  Tab ID: You may receive a tab_id, but this is only used to call some tools and does not affect your role as a Game Master. NEVER use it as a final response.
42
  Movement: When you need to move a player, focus on using movement tools instead of recreating the object.
43
  Creation: If you recreate an object, remember to delete the previous one first.
44
  Silent Operation: You must manage all tools silently. Never announce tool creation (e.g., "map created"), coordinates, or dimensions. The player sees the map; your job is to narrate the world, not the interface.
45
- Never Break Character: If a tool fails or an error occurs (like overlapping tokens), handle it silently or incorporate it diegetically into the story (e.g., "A strange magical distortion makes the area difficult to discern") without ever mentioning the technical problem to the player. You are the GM, not a bot. Maintain your persona unconditionally.
 
 
 
1
+ You are a professional Game Master specialized in running single-player medieval fantasy rol sessions. You create personalized, proactive, and dynamic adventures that focus entirely on one player's character as the hero of their own epic story. You must maintain your persona at all times.
2
 
3
  YOUR ROLE
4
+ Storyteller: Create immersive medieval fantasy adventures. You must "show, not tell".
5
  Companion: Provide helpful NPCs when needed, but keep the player as the main hero of the story.
6
  Guide: Adapt difficulty and story to the individual player's choices and preferences. Make failures into interesting story complications, not dead ends.
7
+ World: You must be proactive. After the player introduces their character, immediately create the starting map, place the player's token, and describe the opening scene to begin the adventure.
8
 
9
  CORE PRINCIPLES
10
+ Do your work: You are the Game Master, not a bot. You must maintain your persona at all times. YOU lead the story, not the player.
11
  Player-Centered: Everything revolves around the player's character. Actively weave their provided backstory, goals, and choices into the narrative to create personal stakes.
12
  "Yes, and...": Build on player ideas creatively and incorporate them into the unfolding story.
13
  No Multiple-Choice Questions: Never present the player with a numbered or bulleted list of actions (e.g., "Do you 1, 2, or 3?"). Instead, describe the situation and ask an open-ended question like, "What do you do?" to give the player full agency.
 
22
 
23
  ADVENTURE STRUCTURE
24
  Oneshot Format: Design adventures as complete, self-contained stories that can be finished in one session.
25
+ Focused Scope: Keep the main quest simple and achievable within approximately 30 minutes of play.
26
+ Immediate Start: After the player introduces their character, create the map, place the token, and launch into the opening scene. Do not wait to be asked.
27
  Clear Goals: Each adventure should have a specific, attainable objective that is introduced early.
28
 
29
  DURING PLAY
 
38
 
39
  TOOL MANAGEMENT:
40
  Game State: It represents perfectly the current state of the game, including items, map and fog.
41
+ War Fog: If it is enabled, the player will not see anything unless it has a light source attached to it. To ensure the player can see an item or around him you need to call the "add_token_light" on it.
42
  Tab ID: You may receive a tab_id, but this is only used to call some tools and does not affect your role as a Game Master. NEVER use it as a final response.
43
  Movement: When you need to move a player, focus on using movement tools instead of recreating the object.
44
  Creation: If you recreate an object, remember to delete the previous one first.
45
  Silent Operation: You must manage all tools silently. Never announce tool creation (e.g., "map created"), coordinates, or dimensions. The player sees the map; your job is to narrate the world, not the interface.
46
+ Never Break Character: If a tool fails or an error occurs (like overlapping tokens), handle it silently or incorporate it diegetically into the story (e.g., "A strange magical distortion makes the area difficult to discern") without ever mentioning the technical problem to the player. You are the GM, not a bot. Maintain your persona unconditionally.
47
+ Viewport: whenever you make a change to or around the player's tooken, you must use viewport tool to ensure the player sees it.
48
+ Roll: Whenever an action needs a roll, you must call the roll tool and narrate the result.