Agent 智能体
一个基于大模型的 AI Agent 系统可以拆分为大模型(LLM)、规划(planning skills)、记忆(memeory)与工具使用(tool use)四个组件部分。
这里主要讲解一下怎么利用LLM进行tool use即function calling函数调用。 PS:如果已经可以调用大模型,直接跳转Stpe 2
Function Calling
Step1:调用大模型
首先我们需要知道怎么调用一个大模型,这里我们用到了火山引擎中DeepSeek R1大模型。
1、进入火山方舟https://www.volcengine.com/product/ark 选择DeepSeek-R1模型,选择其他也可以。
2、选择API调用指南
3、按照提示导入相关代码
获取API Key以及开通相应的大模型。
我们继续根据提示,快速接入测试。
下载相关库。
pip install --upgrade "openai>=1.0"
至此,我们就通过Open AI 的SDK的方式接入了大模型API。如何使用Open AI 的SDK方式
Step2:Function Calling的DEMO
Open AI的Function Calling 参考文档:https://platform.openai.com/docs/guides/function-calling?api-mode=responses&example=get-weather
火山引擎Function Calling参考文档:https://www.volcengine.com/docs/82379/1262342#多轮精调
b站Function Calling参考视频:【MCP 与 Function Calling 到底什么关系,以及为什么我认为大部分人的观点都是错误的】 https://www.bilibili.com/video/BV15YJTzkENC/?share_source=copy_web&vd_source=fd2c09c047a87bd10e3ac840b20d98fa
具体来说Function Calling是干什么的?
用户可以用自然语言向模型描述一组 Function 的功能和定义; 在对话过程中,当大模型觉得需要使用某函数时会智能地选择该 Function,并返回调用所需参数,来满足用户的特定需求; 其他情况,大模型不会返回 Function,而是继续对话。大模型不会直接调用 Function,而是返回其对应的入参,您可自行调用该函数/API接口。
代码如下:
import os
from openai import OpenAI
import json
# 请替换为你申请的api key!!
client = OpenAI(
#从配置文件中读取api key
api_key = os.environ.get("ARK_API_KEY"),
#显式的用字符串直接读取
#api_key = "xxxxxxxxxxxxxxxx"
base_url = "https://ark.cn-beijing.volces.com/api/v3",
)
# LLM大模型 可用的工具(函数)
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获得当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "当前城市和地区,例如 北京市,朝阳区"
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位,摄氏度或华氏度,根据用户地区判断"
}
},
"required": ["location", "format"]
}
}
}
]
messages = []
# 具体实现工具(函数)
def get_current_weather(location, format):
return f"当前{location}的天气是晴天,温度是25度,单位是{format}。"
if __name__ == "__main__":
print("----- standard request -----")
# 创建消息列表
messages .append({"role":"system","content":"不要将错误的内容插入到函数中,缺少参数提示用户输入"})
messages .append({"role":"user","content":"我在邢台市,信都区,你能告诉我当前的天气吗?"})
# 调用LLM
response = client.chat.completions.create(
model="deepseek-r1-250120",
messages=messages,
tools=tools,
function_call={"name": "get_current_weather"},
)
print("Response:", response)
# 根据LLM的响应判断是否需要调用工具(函数)
if response.choices[0].finish_reason == "tool_calls":
function_response = response.choices[0].message
# 将函数调用的响应加入消息历史
messages.append(function_response.model_dump())
# 所需要调用的工具名function name
function_name = function_response.tool_calls[0].function.name
# 所需要调用的工具的参数 arguments
print(f"Function Name: {function_name}")
print(f"Function Arguments: {function_args}")
# 调用LLM指定的工具(函数)
if function_name == "get_current_weather":
json_args = json.loads(function_args)
print(f"Function Arguments: {json_args}")
weather_info = get_current_weather(json_args["location"], json_args["format"])
print("今天的天气:"+weather_info)
# 将函数结果加入消息历史,并重新请求模型生成回复
tool_call = response.choices[0].message.tool_calls[0]
messages.append({
"role": "tool",
"content": weather_info, # 直接使用自然语言字符串
"tool_call_id": tool_call.id # 确保 tool_call_id 是字符串
})
print(json.dumps(messages, indent=2, ensure_ascii=False)) # 检查是否可序列化
second_response = client.chat.completions.create(
model="deepseek-r1-250120",
messages=messages
)
print("\n----- 最终回复 -----")
print(second_response.choices[0].message.content)
else:
# 处理非工具(函数)调用的响应
print("Response:")