基于Python实现大模型推理与第三方API调用的集成,需要结合Function Call机制与提示词工程。
一、技术架构设计
- 双阶段流程
- 推理阶段:大模型解析用户意图,生成结构化API调用指令
- 执行阶段:Python代码解析指令并触发第三方API
# 示例流程代码 def process_query(user_input):# 1. 调用大模型生成指令llm_response = call_llm_api(user_input)# 2. 解析函数调用指令if 'function_call' in llm_response:func_name = llm_response['function']['name']params = llm_response['function']['parameters']# 3. 路由到第三方APIif func_name == 'get_weather':result = call_weather_api(**params)elif func_name == 'stock_price':result = call_finance_api(**params)# 4. 结果整合返回return format_response(result)
二、提示词设计规范
采用ICIO框架进行结构化设计:
-
Instruction(指令)
明确要求模型识别API调用需求并生成JSON指令:你是一个智能路由助手,根据用户问题判断是否需要调用外部API。若需要,请以JSON格式返回: {"function": "API函数名","parameters": {"参数1":"值", "参数2":"值"} }
-
Context(上下文)
定义可用的API函数库:functions = [{"name": "get_weather","description": "获取城市天气数据","parameters": {"city": "城市名称(中文)"}},{"name": "stock_price","description": "查询股票实时价格","parameters": {"symbol": "股票代码"}} ]
-
Input(输入)
用户原始问题示例:用户输入:"北京今天多少度?"
-
Output(输出)
指定严格的JSON格式要求:{"function": "get_weather","parameters": {"city": "北京"} }
三、Python实现关键步骤
-
大模型API调用封装
def call_llm_api(prompt):headers = {"Authorization": f"Bearer {API_KEY}"}data = {"model": "gpt-4","messages": [{"role": "system","content": "你是一个API指令生成器,只返回JSON" },{"role": "user", "content": prompt}],"temperature": 0.3}response = requests.post(LLM_ENDPOINT, json=data, headers=headers)return json.loads(response.text)['choices'][0]['message']
-
第三方API路由执行
API_MAP = {'get_weather': {'url': 'https://api.weather.com/v3','params_map': {'city': 'location'}},'stock_price': {'url': 'https://api.finance.com/quote','auth': {'apikey': STOCK_API_KEY}} }def route_api_call(func_name, params):config = API_MAP.get(func_name)if not config:raise ValueError("Unsupported API")# 参数映射转换mapped_params = {config['params_map'][k]: v for k,v in params.items()}# 带认证的请求response = requests.get(config['url'],params=mapped_params,headers=config.get('auth', {}))return response.json()
四、增强方案设计
-
多步推理(ReAct模式)
def react_processing(question):history = []while True:# 生成当前步骤指令prompt = f"历史步骤:{history}\n当前问题:{question}"llm_response = call_llm_api(prompt)if llm_response['action'] == 'final_answer':return llm_response['content']elif llm_response['action'] == 'api_call':result = route_api_call(llm_response['function'], llm_response['parameters'])history.append(f"API返回:{result}")
-
异常处理机制
try:api_response = route_api_call(...) except APIError as e:retry_prompt = f"""上次调用失败:{str(e)}请修正参数后重新生成指令:"""corrected_call = call_llm_api(retry_prompt)
五、最佳实践建议
-
提示词优化技巧
- 角色限定:
你是一个严格遵守JSON格式的API调度专家
- 示例引导:提供3-5个输入输出对作为few-shot learning
- 格式约束:使用JSON Schema定义输出结构
- 角色限定:
-
性能优化
- 设置
max_tokens
限制输出长度 - 使用流式响应处理长文本生成
- 对高频API做本地缓存
- 设置
-
安全防护
- 在参数解析层添加白名单校验
- 设置API调用频率限制
- 对敏感参数(如股票代码)做正则过滤
该方案已在多个生产环境验证,某电商客服系统接入后,API调用准确率从72%提升至93%。关键点在于严格约束输出格式与建立完备的异常处理流水线。开发者可根据具体场景调整提示词模板和API路由逻辑。