LangChain-17 FunctionCalling 利用大模型对函数进行回调 扩展大模型的额外的能力 比如实现加减乘除等功能 原创
背景介绍
引用:
Function Calling是一种允许用户在使用大型语言模型(如GPT系列)处理特定问题时,定制并调用外部函数的功能。这些外部函数可以是专门为处理特定任务(如数据分析、图像处理等)而设计的代码块。通过Function Calling,大模型可以调用这些外部函数获取信息,然后根据这些信息生成相应的输出,从而实现更加复杂和专业化的任务处理能力。
安装依赖
pip install -qU langchain-core langchain-openai
编写代码
这里封装了一些类:加、减、乘、除
通过: llm_with_tools = llm.bind_tools([Add, Multiply, Subtract])
将它们组合起来,接着交给大模型。
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
class Multiply(BaseModel):
"""Multiply two integers together."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
class Add(BaseModel):
"""Add two integers together."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
class Subtract(BaseModel):
"""Subtract two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
llm_with_tools = llm.bind_tools([Add, Multiply, Subtract])
message1 = llm_with_tools.invoke("what's 3 * 12")
print(f"message1: {message1}")
message2 = llm_with_tools.invoke("what's 3 + 12'")
print(f"message2: {message2}")
message3 = llm_with_tools.invoke("what's 3 - 12'")
print(f"message3: {message3}")
运行结果
➜ python3 test17.py
message1: content='3 * 12 is equal to 36.' response_metadata={'finish_reason': 'stop', 'logprobs': None}
message2: content='The result of 3 + 12 is 15.' response_metadata={'finish_reason': 'stop', 'logprobs': None}
message3: content='' additional_kwargs={'tool_calls': [{'id': 'call_aXV9LQfp4COEzB5b93nazfkv', 'function': {'arguments': '// Using the Subtract function from the functions namespace\nfunctions.Subtract({a: 3, b: 12});', 'name': 'python'}, 'type': 'function'}]} response_metadata={'finish_reason': 'tool_calls', 'logprobs': None}
转换函数
我们可以通过工具,将函数转换为JSON
的形式
import json
from langchain_core.utils.function_calling import convert_to_openai_tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers together.
Args:
a: First integer
b: Second integer
"""
return a * b
print(json.dumps(convert_to_openai_tool(multiply), indent=2))
输出结果
➜ python3 test17.py
{
"type": "function",
"function": {
"name": "multiply",
"description": "Multiply two integers together.",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "integer",
"description": "First integer"
},
"b": {
"type": "integer",
"description": "Second integer"
}
},
"required": [
"a",
"b"
]
}
}
}
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)