Function calling

Afarensis 助手API:实现函数调用

Afarensis 助手API支持函数调用,类似于聊天完成API,这一功能允许您向助手描述函数,并智能地返回需要调用的函数及其参数。当助手在运行过程中调用函数时,执行将暂停,直到您提供函数调用的结果,从而继续运行的执行。

定义函数 在创建助手时,首先定义您想要助手调用的函数:

assistant = client.beta.assistants.create( instructions="You are a weather bot. Use the provided functions to answer questions.", model="gpt-4-turbo-preview", tools=[{ "type": "function", "function": { "name": "getCurrentWeather", "description": "获取指定地点的天气", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "城市和州,例如 San Francisco, CA"}, "unit": {"type": "string", "enum": ["c", "f"]} }, "required": ["location"] } } }, { "type": "function", "function": { "name": "getNickname", "description": "获取城市的昵称", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "城市和州,例如 San Francisco, CA"}, }, "required": ["location"] } } }] ) 触发和读取函数调用 当用户消息触发函数调用时,运行将进入“pending”状态,并在处理后进入“requires_action”状态。您可以通过检索运行状态来验证此状态,并查看需要调用的函数及其参数。

提交函数输出 完成函数调用后,您需要提交函数的输出,以便继续运行的执行:

run = client.beta.threads.runs.submit_tool_outputs( thread_id=thread.id, run_id=run.id, tool_outputs=[ { "tool_call_id": call_ids[0], "output": "22C", }, { "tool_call_id": call_ids[1], "output": "LA", }, ] ) 在提交了函数输出后,运行将进入“queued”状态,并继续执行直至完成。

最后更新于