@@ -201,43 +201,80 @@ def to_stream_response_simple(stream_event):
201201 r ['Cache-Control' ] = 'no-cache'
202202 return r
203203
204- tool_message_template = """
204+ tool_message_json_template = """
205+ ```json
206+ %s
207+ ```
208+ """
209+
210+ tool_message_complete_template = """
205211<details>
206212 <summary>
207213 <strong>Called MCP Tool: <em>%s</em></strong>
208214 </summary>
209215
216+ **Input:**
217+ %s
218+
219+ **Output:**
210220%s
211221
212222</details>
213223
214224"""
215225
216- tool_message_json_template = """
217- ```json
218- %s
219- ```
220- """
221226
222227
223- def generate_tool_message_template (name , context ):
224- if '```' in context :
225- return tool_message_template % (name , context )
228+ def generate_tool_message_complete (name , input_content , output_content ):
229+ """生成包含输入和输出的工具消息模版"""
230+ # 格式化输入
231+ if '```' not in input_content :
232+ input_formatted = tool_message_json_template % input_content
233+ else :
234+ input_formatted = input_content
235+
236+ # 格式化输出
237+ if '```' not in output_content :
238+ output_formatted = tool_message_json_template % output_content
226239 else :
227- return tool_message_template % (name , tool_message_json_template % (context ))
240+ output_formatted = output_content
241+
242+ return tool_message_complete_template % (name , input_formatted , output_formatted )
228243
229244
230245async def _yield_mcp_response (chat_model , message_list , mcp_servers , mcp_output_enable = True ):
231246 client = MultiServerMCPClient (json .loads (mcp_servers ))
232247 tools = await client .get_tools ()
233248 agent = create_react_agent (chat_model , tools )
234249 response = agent .astream ({"messages" : message_list }, stream_mode = 'messages' )
250+
251+ # 用于存储工具调用信息
252+ tool_calls_info = {}
253+
235254 async for chunk in response :
236- if mcp_output_enable and isinstance (chunk [0 ], ToolMessage ):
237- content = generate_tool_message_template (chunk [0 ].name , chunk [0 ].content )
238- chunk [0 ].content = content
239- yield chunk [0 ]
240255 if isinstance (chunk [0 ], AIMessageChunk ):
256+ tool_calls = chunk [0 ].additional_kwargs .get ('tool_calls' , [])
257+ for tool_call in tool_calls :
258+ tool_id = tool_call .get ('id' , '' )
259+ if tool_id :
260+ # 保存工具调用的输入
261+ tool_calls_info [tool_id ] = {
262+ 'name' : tool_call .get ('function' , {}).get ('name' , '' ),
263+ 'input' : tool_call .get ('function' , {}).get ('arguments' , '' )
264+ }
265+ yield chunk [0 ]
266+
267+ if mcp_output_enable and isinstance (chunk [0 ], ToolMessage ):
268+ tool_id = chunk [0 ].tool_call_id
269+ if tool_id in tool_calls_info :
270+ # 合并输入和输出
271+ tool_info = tool_calls_info [tool_id ]
272+ content = generate_tool_message_complete (
273+ tool_info ['name' ],
274+ tool_info ['input' ],
275+ chunk [0 ].content
276+ )
277+ chunk [0 ].content = content
241278 yield chunk [0 ]
242279
243280
0 commit comments