FastAPI/Python 接入通义千问 Function Calling(工具调用) FastAPI/Python 接入通义千问 Function Calling工具调用实战 Day3关键词FastAPI、通义千问、Function Calling、工具调用、Agent、Python这是大模型接入实战的 Day3。Day1 跑通单轮非流式 / SSE 流式Day2 用 Redis 做了多轮会话 上下文压缩。Day3 往前再走一步——让模型能「调用工具」模型自己决定要不要查天气、查学历程序员负责把工具跑完把结果喂回去模型再生成最终回答。这是做 AI Agent 的基础能力。一、Function Calling 是什么大模型本身只会「说话」不会查实时数据、不会调业务接口。Function Calling工具调用的机制是你先告诉模型「你有哪些工具可用」tools列表每个工具含名称 / 描述 / 参数 JSON Schema用户提问后模型判断是否需要调用工具、调用哪个、参数是什么模型不直接回答而是返回一个tool_calls指明函数名 参数程序员执行对应工具拿到结果把工具结果以roletool的形式塞回messages再调一次模型模型这次基于工具结果生成最终的自然语言回答一句话模型出「调用指令」你出「执行 回填」最后模型「总结」。二、单工具天气查询llm/case5.py2.1 定义工具importjsonimportosimportrandomfromopenaiimportOpenAIdefget_current_weather(arguments):weather_conditions[晴天,阴天,雨天,雪天]random_weatherrandom.choice(weather_conditions)locationarguments[location]returnf{location}今天是{random_weather}tools[{type:function,function:{name:get_current_weather,description:当你想查询指定城市的天气时非常有用,parameters:{type:object,properties:{location:{type:string,description:城市或县区比如北京市、杭州市、余杭区等,}},required:[location],},},}]工具定义就是一段JSON Schemaname是函数名description告诉模型「什么时候该用它」parameters描述入参。模型靠description来决策所以描述要写清楚。2.2 客户端与带 tools 的调用clientOpenAI(api_keyos.environ[DASHSCOPE_API_KEY],base_urlhttps://ws-ulkao56twirebft4.cn-beijing.maas.aliyuncs.com/compatible-mode/v1,)messages[]defget_ai_response(messages):completionclient.chat.completions.create(modelqwen-plus,messagesmessages,temperature0.75,toolstools,# 把工具列表传进去)returncompletion关键点toolstools必须带上否则模型不知道有工具可用。2.3 判断是否需要调用工具 执行 回填user_message{role:user,content:北京今天的天气?}messages.append(user_message)completionget_ai_response(messages)messages.append(completion.choices[0].message)# 判断第一次返回是否需要调用工具ifcompletion.choices[0].message.tool_callsisNone:print(不需要调用工具)print(completion.choices[0].message.content)else:print(需要调用工具)tool_callscompletion.choices[0].message.tool_callsfortool_callintool_calls:tool_idtool_call.idfunc_nametool_call.function.name func_argumentstool_call.function.arguments function_mapping{get_current_weather:get_current_weather}tool_resultfunction_mapping[func_name](json.loads(func_arguments))tool_message{role:tool,content:tool_result,tool_call_id:tool_id,}messages.append(tool_message)completionget_ai_response(messages)# 再调一次拿到最终回答print(f最终的结果是:{completion.choices[0].message.content})流程要点tool_calls is None→ 模型直接回答了不用调工具否则遍历tool_calls模型可能一次让你调多个工具tool_call.function.arguments是JSON 字符串要json.loads成 dict 再传给函数用function_mapping字典映射函数名 → 函数对象不要用eval安全风险回填的消息roletool且必须带tool_call_id与模型下发的 id 对应再调一次get_ai_response模型才能基于工具结果生成自然语言回答三、多工具天气 学历验证llm/case6.py在单工具基础上加第二个工具学历验证。它要调外部 HTTP 接口并用 Redis 缓存结果。3.1 学历验证工具外部 API Redis 缓存importredisimportrequests redis_clientredis.Redis(hostlocalhost,port6379,db7,decode_responsesTrue,protocol2,)defacademic_credential_verification(arguments):vcodearguments[vcode]keyfboss:llm:academic_credential_verification:{vcode}redis_verification_dataredis_client.get(key)ifredis_verification_dataisNone:BASE_URLhttps://www.apimy.cn/api/xxw/bgcxpayload{key:os.getenv(MY_XXW_BGCX_API_KEY),vcode:arguments[vcode]}headers{Content-Type:application/json}responserequests.post(BASE_URL,jsonpayload,headersheaders,timeout30)response.raise_for_status()dataresponse.json()redis_client.set(key,json.dumps(data,ensure_asciiFalse))returnjson.dumps(data,ensure_asciiFalse)else:returnredis_verification_data要点先查 Redis 缓存同一vcode不重复打外部接口省额度也更快外部调用加raise_for_status()timeoutHTTP 异常和超时都要兜底否则会卡死工具调用API Key 走环境变量MY_XXW_BGCX_API_KEY不硬编码3.2 注册两个工具 映射tools[{type:function,function:{name:get_current_weather,description:当你想查询指定城市的天气时非常有用,parameters:{type:object,properties:{location:{type:string,description:城市或县区}},required:[location],},},},{type:function,function:{name:academic_credential_verification,description:当你想查询学历或学历验证时非常有用,parameters:{type:object,properties:{vcode:{type:string,description:学历验证码}},required:[vcode],},},},]function_mapping{get_current_weather:get_current_weather,academic_credential_verification:academic_credential_verification,}调用逻辑和单工具完全一致——遍历tool_calls按function.name从function_mapping取函数执行。模型会根据用户问题自动选工具问天气调天气、问学历验证码调学历。注意case5.py/case6.py目前是原生脚本直接python跑还没封装成 FastAPI 接口。脚本用来验证链路下一步可像 Day1/Day2 那样包成POST /llm-day03/...路由对外提供。四、踩坑清单重点tools的parameters必须是合法 JSON Schematype/properties/required缺一不可required里列的字段模型才会保证给。description决定模型会不会调描述模糊模型容易「该调不调」或「乱调」。把触发场景写清楚。arguments是字符串不是 dicttool_call.function.arguments是 JSON 字符串必须json.loads才能当参数用。回填消息必须roletooltool_call_id少一个模型会报错或忽略结果tool_call_id要和模型下发的tool_call.id一一对应。必须再调一次模型调完工具把结果塞回messages后要再create一次模型才会生成「基于工具结果的自然语言回答」——很多新手只执行工具就结束了以为没输出。一次可能调多个工具tool_calls是列表记得for遍历别只取[0]。用字典映射代替evalfunction_mapping[name](args)安全千万别eval(name)执行模型下发的字符串。外部工具要加失败兜底raise_for_status()timeout并考虑接口超时 / 限流时给模型一个友好错误信息作为 tool 结果回填。外部结果加缓存像 case6 这样用 Redis 按业务 key 缓存避免重复调用、省钱省时。API Key 走环境变量os.environ[DASHSCOPE_API_KEY]缺省会抛KeyError强制校验生产建议os.getenv 显式判空返回友好错误。温度建议调低Function Calling 更看重参数格式正确temperature偏高如 0.75可能影响 JSON 参数稳定性关键业务场景可调到 0.1~0.3。五、小结Day3 把「模型调用工具」跑通了单工具天气查询验证 Function Calling 全流程多工具天气 学历验证后者接外部 API 并加 Redis 缓存核心套路固定定义 tools → 带 tools 调模型 → 判断 tool_calls → 执行工具 → roletool 回填 → 再调一次拿最终回答这是迈向AI Agent的第一步——模型从「只会聊天」变成「能动手查数据 / 调接口」。后续可继续做把 Function Calling 封装成 FastAPI 流式接口SSE 工具执行进度多轮对话 工具调用结合Day2 的 Redis 会话 今天工具工具执行异步化外部 API 慢用httpx.AsyncClient 异步工具结果做结构化校验Pydantic 校验arguments注本文代码片段均来自当天真实提交的后端练习文件llm/case5.py、llm/case6.py仅做脱敏API Key 走环境变量。case3.py/case4.py仍为全注释的多轮对话草稿未纳入本篇。