将结果返回给模型
将工具输出格式化为工具角色消息,以便模型读取并继续对话。
将结果返回给模型 是 CoddyKit 上的免费 AI Agents 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
工具结果消息
运行工具后,您需要通过工具消息告知模型执行结果:
messages.append({
'role': 'tool',
'tool_call_id': tool_call.id, # MUST match the assistant's tool_call.id
'content': json.dumps(result)
})内容应为字符串
OpenAI 要求 content 为字符串。请使用 json.dumps 序列化对象:
# Bad — will error
messages.append({'role': 'tool', 'tool_call_id': id, 'content': {'temp': 18}})
# Good
messages.append({'role': 'tool', 'tool_call_id': id, 'content': '{"temp": 18}'})Anthropic 格式
Anthropic 在用户消息中使用内容区块:
messages.append({
'role': 'user',
'content': [{
'type': 'tool_result',
'tool_use_id': 'toolu_abc',
'content': json.dumps(result)
}]
})返回错误
如果工具执行失败,请返回错误,不要假装执行成功。模型可以自行恢复:
try:
result = run_tool(...)
content = json.dumps({'ok': True, 'data': result})
except Exception as e:
content = json.dumps({'ok': False, 'error': str(e)})
messages.append({'role': 'tool', 'tool_call_id': id, 'content': content})多结果模式
对于并行工具调用,请使用匹配的 ID 追加每个结果:
for tc in message.tool_calls:
result = dispatch(tc)
messages.append({
'role': 'tool',
'tool_call_id': tc.id,
'content': json.dumps(result)
})大型输出:进行摘要
如果工具返回 100KB 的 HTML,将其全部发送给模型会浪费令牌并分散注意力。请先进行摘要或截断:
def truncate(text, max_chars=4000):
if len(text) <= max_chars:
return text
return text[:max_chars] + f'\n...[truncated, {len(text)-max_chars} more chars]'
sample = "x" * 4500
result = truncate(sample, max_chars=50)
print(result)
始终保持相同的模式
即使结果有所不同(成功 / 错误 / 未找到),也要保持输出模式稳定。形状一致时,模型的可靠性更高:
from typing import TypedDict, Literal, Optional, Any
class ToolResult(TypedDict):
status: Literal['ok', 'not_found', 'error']
data: Optional[Any]
error: Optional[str]
def make_result(status, data=None, error=None) -> ToolResult:
return {'status': status, 'data': data, 'error': error}
print(make_result('ok', data={'temp': 72}))
print(make_result('not_found', error='city not found'))包含元数据提示
在内容中加入提示,帮助模型解释结果:
content = json.dumps({
'data': rows,
'note': 'Returned 50 rows (most recent first). There may be more matches.'
})二进制数据
不要将大型二进制数据块编码为 base64 后放入工具消息。请改为将其保存到存储中,并返回 URL 或 ID:
result = {
'image_path': '/tmp/chart-abc.png',
'thumbnail_url': 'https://...',
'caption': 'Sales by quarter, 2024'
}
for k, v in result.items():
print(f"{k}: {v}")
再次运行模型循环
追加所有工具结果后,再次调用模型——它要么生成最终答案,要么调用更多工具:
class Msg:
def __init__(self, tool_calls=None, content=None):
self.tool_calls = tool_calls or []
self.content = content
class ToolCall:
def __init__(self, name, args):
self.name = name
self.args = args
def call_model(messages, tools):
if len(messages) < 4:
return Msg(tool_calls=[ToolCall('get_weather', {'city': 'Paris'})])
return Msg(content='It is sunny in Paris.')
messages = [{'role': 'user', 'content': 'Weather in Paris?'}]
tools = ['get_weather']
message = call_model(messages, tools)
while message.tool_calls:
for tc in message.tool_calls:
result = f'Result of {tc.name}({tc.args})'
messages.append({'role': 'tool', 'name': tc.name, 'content': result})
print('Tool call:', tc.name, '->', result)
message = call_model(messages, tools)
print('Final answer:', message.content)
审计工具输出
记录每个(工具调用 ID、参数、结果)以便调试。当智能体的行为异常时,工具结果日志是首先应该查看的地方。
工具结果格式
工具消息中的 tool_call_id 指的是什么?
回顾
现在您已经掌握了完整的工具调用往返流程。下一门课程是记忆,这是智能体的第三大支柱。
常见问题解答
「将结果返回给模型」课时是免费的吗?
是的 — 「将结果返回给模型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「将结果返回给模型」这节课中我会学到什么?
将工具输出格式化为工具角色消息,以便模型读取并继续对话。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「将结果返回给模型」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。