使用 Function Calling 的提示词模板与 OpenAI 示例详解
一、Function Calling 简介
Function Calling 是指大模型在理解用户意图后,自动调用一个或多个预定义的函数,并传入合适的参数。这使得模型不再是“只输出文本”,而是能与外部系统联动,执行真实操作。
例如:
- 用户问:“北京明天天气怎么样?”
- 模型识别出需要调用
get_weather 函数,并传入 city="北京" 和 date="明天"
二、提示词模板的作用
提示词模板是 Function Calling 的基础配置文件。
它告诉模型:
- 它扮演的角色(Role)
- 可用的工具(Tools)
- 调用规则(Calling Rules)
- 输出格式(Response Format)
✅ 作用总结:
| 角色 |
说明 |
| Role |
明确职责边界(如“你是一个天气助手”) |
| Tools |
告知可用函数及其参数 |
| Rules |
控制何时调用函数 |
| Output Format |
控制返回结果形式 |
三、使用 OpenAI 实现 Function Calling 的 Python 示例
以下是一个完整的示例,展示如何构造提示词模板 + 定义函数 schema + 调用 OpenAI API 并处理响应。
📦 步骤概览:
- 构造完整的 Prompt(含角色、工具、调用规则)
- 定义
get_weather 函数的 Schema
- 发起请求并解析是否调用了函数
- 如果调用成功,模拟执行函数并返回结果
💻 完整代码示例(Python + OpenAI)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import openai
openai.api_key = "YOUR_OPENAI_API_KEY"
def get_weather(city: str, date: str = "明天") -> str: weather_data = { "北京": {"今天": "22℃,多云", "明天": "23℃,晴"}, "上海": {"今天": "28℃,小雨", "明天": "29℃,阴"} } return f"{city}{date}天气:{weather_data.get(city, {}).get(date, '无数据')}"
def build_prompt(user_query): template = """ # 角色 你是天气助手,仅回答与天气相关的问题。
# 可用工具 - **get_weather**: - 描述: 查询城市天气预报。 - 参数: - `city` (字符串,必需): 用户指定的城市,如“上海”。 - `date` (字符串,可选): 日期(格式:今天/明天/YYYY-MM-DD),默认明天。
# 调用规则 1. 仅当用户明确询问天气时调用工具。 2. 若用户未说明城市,回复:“请问您想查询哪个城市?” 3. 工具返回结果后,整理为自然语言回复(如“上海明天25℃,晴”)
【用户输入】 """ return template.strip() + "\n" + user_query.strip()
tool_schema = { "type": "function", "function": { "name": "get_weather", "description": "查询城市天气预报。", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "要查询的城市名称"}, "date": {"type": "string", "description": "查询日期,默认明天"} }, "required": ["city"] } } }
def call_openai_with_function(prompt): response = openai.ChatCompletion.create( model="gpt-3.5-turbo-1106", messages=[{"role": "user", "content": prompt}], functions=[tool_schema], function_call="auto" )
message = response.choices[0].message
if hasattr(message, 'function_call'): func_name = message.function_call.name args = eval(message.function_call.arguments) print("调用函数:", func_name) print("参数:", args)
result = get_weather(**args) return result else: return message.content
if __name__ == "__main__": user_input = "北京天气怎么样?" prompt = build_prompt(user_input) response = call_openai_with_function(prompt) print("最终回复:", response)
|
四、运行结果示例
假设用户输入为:
深色版本
程序输出可能如下:
深色版本
1 2 3
| 调用函数: get_weather 参数: {'city': '北京', 'date': '明天'} 最终回复: 北京明天天气:23℃,晴
|
五、总结
| 内容 |
说明 |
| ✅ 提示词模板 |
是 Function Calling 的核心,决定了模型的行为逻辑 |
| ✅ Function Calling 流程 |
包括构建 prompt、定义 schema、调用 API、解析 tool_call |
| ✅ OpenAI 支持 |
通过 functions 和 function_call 字段实现 |
| ✅ 本地调试函数 |
可模拟真实接口行为,便于开发测试 |
竭力的进入安息。喜欢赞美和敬拜,喜欢在经文中看到主耶稣,有志同道合的朋友可以加微信私聊:xingxiliang。