Gustav2811 commited on
Commit
0cce69c
·
1 Parent(s): 36619f7

Better tool UI

Browse files
Files changed (1) hide show
  1. app.py +23 -34
app.py CHANGED
@@ -142,13 +142,11 @@ async def start():
142
  async def execute_tool_call(tool_call: Any):
143
  """
144
  Helper function to find the correct MCP session, execute a tool call,
145
- and robustly serialize the result to a JSON string.
146
  """
147
  tool_name = tool_call.function.name
148
  tool_args_str = tool_call.function.arguments
149
 
150
- log.debug(f"Executing tool call: {tool_name} with args: {tool_args_str}")
151
-
152
  history = cl.user_session.get("message_history")
153
 
154
  mcp_connection_name = None
@@ -173,7 +171,7 @@ async def execute_tool_call(tool_call: Any):
173
  return
174
 
175
  async with cl.Step(type="tool", name=tool_name) as step:
176
- step.input = tool_args_str
177
 
178
  try:
179
  mcp_session, _ = cl.context.session.mcp_sessions.get(mcp_connection_name)
@@ -181,56 +179,47 @@ async def execute_tool_call(tool_call: Any):
181
  tool_result = await mcp_session.call_tool(tool_name, tool_args)
182
 
183
  content = tool_result.content
184
- final_content_str = ""
 
185
 
186
- if isinstance(content, str):
187
- final_content_str = content
188
- elif (
189
  isinstance(content, list)
190
- and len(content) == 1
191
  and hasattr(content[0], "text")
192
- and not hasattr(content[0], "data")
193
  ):
194
- final_content_str = content[0].text
195
- else:
196
-
197
- def to_serializable(obj: Any) -> Any:
198
- if hasattr(obj, "model_dump"):
199
- return obj.model_dump(exclude_none=True)
200
- if hasattr(obj, "dict"):
201
- return obj.dict(exclude_none=True)
202
- if hasattr(obj, "to_dict"):
203
- return obj.to_dict()
204
- if isinstance(obj, list):
205
- return [to_serializable(item) for item in obj]
206
- return obj
207
-
208
- serializable_content = to_serializable(content)
209
- final_content_str = json.dumps(serializable_content, indent=2)
210
-
211
- step.output = final_content_str
212
- log.debug(f"Tool {tool_name} executed successfully")
213
 
 
 
 
 
214
  history.append(
215
  {
216
  "tool_call_id": tool_call.id,
217
  "role": "tool",
218
  "name": tool_name,
219
- "content": final_content_str,
220
  }
221
  )
222
 
223
  except Exception as e:
224
- error_msg = f"Error executing tool {tool_name}: {str(e)}"
225
- log.error(error_msg)
226
- log.error(f"Full traceback: {traceback.format_exc()}")
227
  step.error = str(e)
228
  history.append(
229
  {
230
  "tool_call_id": tool_call.id,
231
  "role": "tool",
232
  "name": tool_name,
233
- "content": f"Error executing tool {tool_name}: {traceback.format_exc()}",
234
  }
235
  )
236
 
 
142
  async def execute_tool_call(tool_call: Any):
143
  """
144
  Helper function to find the correct MCP session, execute a tool call,
145
+ and robustly serialize the result for both the UI and the LLM.
146
  """
147
  tool_name = tool_call.function.name
148
  tool_args_str = tool_call.function.arguments
149
 
 
 
150
  history = cl.user_session.get("message_history")
151
 
152
  mcp_connection_name = None
 
171
  return
172
 
173
  async with cl.Step(type="tool", name=tool_name) as step:
174
+ step.input = json.loads(tool_args_str)
175
 
176
  try:
177
  mcp_session, _ = cl.context.session.mcp_sessions.get(mcp_connection_name)
 
179
  tool_result = await mcp_session.call_tool(tool_name, tool_args)
180
 
181
  content = tool_result.content
182
+ output_for_step = content # Default to showing raw content
183
+ output_for_llm = str(content) # Default to string for LLM
184
 
185
+ if (
 
 
186
  isinstance(content, list)
187
+ and len(content) > 0
188
  and hasattr(content[0], "text")
 
189
  ):
190
+ text_content = content[0].text
191
+ output_for_llm = text_content # LLM always gets the original string
192
+
193
+ # **THIS IS THE FIX**
194
+ # Try to parse the text as JSON for a nice UI display.
195
+ try:
196
+ output_for_step = json.loads(text_content)
197
+ except json.JSONDecodeError:
198
+ # If it's not valid JSON, it's just plain text.
199
+ output_for_step = text_content
 
 
 
 
 
 
 
 
 
200
 
201
+ # Set the step output for the UI
202
+ step.output = output_for_step
203
+
204
+ # Append the string version to history for the LLM
205
  history.append(
206
  {
207
  "tool_call_id": tool_call.id,
208
  "role": "tool",
209
  "name": tool_name,
210
+ "content": output_for_llm,
211
  }
212
  )
213
 
214
  except Exception as e:
215
+ error_msg = f"Error executing tool `{tool_name}`: {traceback.format_exc()}"
 
 
216
  step.error = str(e)
217
  history.append(
218
  {
219
  "tool_call_id": tool_call.id,
220
  "role": "tool",
221
  "name": tool_name,
222
+ "content": error_msg,
223
  }
224
  )
225