You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Prompt-Engineering-Guide/pages/applications/function_calling.zh.mdx

108 lines
4.6 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 在LLM中调用函数
## 调用函数
函数调用是指可靠地连接LLM与外部工具的能力。让用户能够使用高效的外部工具、与外部API进行交互。
GPT-4和GPT-3.5是经过微调的LLM能够检测函数是否被调用随后输出包含调用函数参数的JSON。通过这一过程被调用的函数能够作为工具添加到您的AI应用中并且您可以在单个请求中定义多个函数。
函数调用是一项重要能力。它对于构建LLM驱动的聊天机器人或代理至关重要。这些聊天机器人或代理需要为LLM检索上下文。它们还与外部工具交互。这种交互是通过将自然语言转换为API调用来完成的。
函数调用使开发者能够创建:
- 能够高效使用外部工具回答问题的对话代理。例如,查询“伯利兹的天气如何?”将被转换为类似`get_current_weather(location: string, unit: 'celsius' | 'fahrenheit')`的函数调用
- 用于提取和标记数据的LLM驱动解决方案例如从维基百科文章中提取人名
- 可以帮助将自然语言转换为API调用或有效数据库查询的应用程序
- 能够与知识库交互的对话式知识检索引擎
在这份指南中我们展示了如何针对GPT-4和其他开源模型给出提示以执行不同的函数调用。
## 使用GPT-4进行函数调用
作为一个基本示例,假设我们要求模型检查特定地点的天气。
LLM本身无法响应此请求。因为它所使用的训练数据集截止至之前的某个日期。解决这个问题的方法是将LLM与外部工具结合起来。您可以利用模型的函数调用能力来确定要调用的外部函数及其参数然后让它返回最终回复结果。以下是一个简单的示例展示了如何使用OpenAI API实现这一点。
假设一个用户向模型提出以下问题:
```
伦敦的天气如何?
```
要使用函数调用处理此请求第一步是定义一个或一组天气函数。您将作为OpenAI API请求的一部分传递这些函数
```python
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]
```
`get_current_weather`函数能够返回指定位置的天气情况。当您将这个函数定义作为请求的一部分传递时它实际上并不执行函数只是返回一个包含调用函数所需参数的JSON对象。以下是一些如何实现这一点的代码片段。
您可以如下定义一个完整的函数:
```python
def get_completion(messages, model="gpt-3.5-turbo-1106", temperature=0, max_tokens=300, tools=None):
response = openai.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
tools=tools
)
return response.choices[0].message
```
您可以像这样构造用户提问:
```python
messages = [
{
"role": "user",
"content": "伦敦的天气如何?"
}
]
```
最后,您可以调用`get_completion`函数,将结果传递给`response`中的`messages`和`tools`
```python
response = get_completion(messages, tools=tools)
```
`response`的构造如下所示:
```python
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='...', function=Function(arguments='{"location":"London","unit":"celsius"}', name='get_current_weather'), type='function')])
```
特别地,`arguments` 对象包含了模型提取的重要参数,这些参数将被用于完成请求。
然后您可以调用一个外部天气API来获取实际的天气信息。一旦您有了天气信息就可以将其传回模型随后根据原始用户问题总结出最终回应。
这里有一个[python notebook](https://github.com/dair-ai/Prompt-Engineering-Guide/blob/main/notebooks/pe-function-calling.ipynb)它提供了一个简单示例展示了如何使用OpenAI API进行函数调用。
## 使用开源LLM进行函数调用
更多使用开源LLM进行函数调用的说明即将推出...
## 函数调用用例
更多函数调用用例即将推出...