【AI大模型学习路线】第三阶段之RAG与LangChain——第十三章(理解Function Calling)Function Calling(函数调用)详解,附代码?
欢迎宝子们点赞、关注、收藏!欢迎宝子们批评指正!
祝所有的硕博生都能遇到好的导师!好的审稿人!好的同门!顺利毕业!
大多数高校硕博生毕业要求需要参加学术会议,发表EI或者SCI检索的学术论文会议论文。详细信息可关注VX “
学术会议小灵通
”或参考学术信息专栏:https://fighting.blog.csdn.net/article/details/146994798
随着GPT-4、Claude、Gemini等大模型的涌现,单靠模型记忆生成答案的方式已经难以满足需求。于是:
这种能力支持了大模型更深入的应用于问答系统、自动办公、智能决策等场景。
OpenAI API
和 LangChain
框架来演示Function Calling。pip install openai langchain
functions = [
{
"name": "get_weather",
"description": "Get the weather of a given city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "Name of the city, like Beijing or New York"
}
},
"required": ["city"]
}
}
]
def get_weather(city):
return f"The weather in {city} is sunny and 25°C."
from openai import OpenAI
client = OpenAI()
user_query = "What's the weather like in Shanghai?"
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": user_query}],
functions=functions,
function_call="auto" # 让模型自动判断是否调用函数
)
# 判断是否调用函数
message = response.choices[0].message
if message.function_call:
# 提取参数
import json
func_name = message.function_call.name
arguments = json.loads(message.function_call.arguments)
# 调用函数
if func_name == "get_weather":
result = get_weather(arguments["city"])
print("Function result:", result)
else:
print("Model response:", message.content)
from langchain.agents import initialize_agent, Tool
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(model="gpt-4")
# 定义一个工具
def get_weather_tool(city):
return f"{city} is rainy today."
tools = [
Tool(
name="get_weather",
func=get_weather_tool,
description="Use this tool to get the current weather of a city"
)
]
agent = initialize_agent(tools, llm, agent="chat-zero-shot-react-description", verbose=True)
agent.run("What's the weather like in Paris?")
Function Calling 不仅让大模型能“说话”,还能动手干活,是实现以下技术路线的基础:
项目 | 内容 |
---|---|
本质 | 让大模型调用结构化函数响应用户意图 |
应用 | API调用、信息检索、数据处理等 |
框架 | OpenAI API / LangChain / LlamaIndex 等 |
优势 | 实现模型“生成+行动”,是AI代理的基础 |