后端技术杂谈

后端技术杂谈

马上订阅 后端技术杂谈 RSS 更新: https://rowkey.cn/atom.xml

Langchain代理和OpenAI函数调用的区别

2023年11月30日 19:29

最近在实现LLM调用外部工具的时候,突然意识到貌似OpenAI的Function Calling和LangChain的Agent都能达到相同的结果,只是实现方式不同。因此这里来对比一下。

OpenAI Functions Calling

OpenAI函数允许更好地控制AI调用的函数,因为我们必须解析AI的响应,找出AI想要调用的函数,并将参数传递给该函数。我们可以在每个阶段干预并修改被调用函数或其参数。

假设我们想让AI使用一个REST API,而不指定它可以执行的操作。我们提供一个通用的REST API客户端,让AI决定使用哪种HTTP方法和哪些参数。

定义一个函数

首先,我们必须准备一个可用Function的描述。

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
functions = [
{
    "type": "function",
    "function": {
        "name": "call_rest_api",
        "description": "Sends a request to the REST API",
        "parameters": {
            "type": "object",
            "properties": {
                "method": {
                    "type": "string",
                    "description": "The HTTP method to be used",
                    "enum": ["GET", "POST", "PUT", "DELETE"],
                },
                "url": {
                    "type": "string",
                    "description": "The URL of the endpoint. Value placeholders must be replaced with actual values.",
                },
                "body": {
                    "type": "string",
                    "description": "A string representation of the JSON that should be sent as the request body.",
                },

            },
            "required": ["method", "url"],
        },
    }
}
]

除了描述之外,还需要一个函数的实现。毕竟,当我们收到一个表示AI想要调用函数的响应时,我们将负责调用该函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def call_rest_api(self, arguments):
    arguments = json.loads(arguments)
    # reques.in is a hosted, fake REST API that we can use for testing
    url = 'https://reqres.in' + arguments['url']
    body = arguments.get('body', {})
    response = None
    if arguments['method'] ==...

剩余内容已隐藏

查看完整文章以阅读更多