ohmygpt-logoOhMyGPT Cookbook

工具调用

在你的提示中使用工具

工具调用(也称为函数调用)使 LLM 能够访问外部工具。LLM 并不直接调用工具,而是建议要调用的工具。用户随后单独调用该工具,并将结果提供给 LLM。最后,LLM 将响应格式化为对用户原始问题的答案。

OhMyGPT 在模型和提供者之间标准化了工具调用接口。

有关工具调用在 OpenAI SDK 中如何工作的入门,请参阅本文,或者如果您更喜欢从完整的端到端示例中学习,请继续阅读。

工具调用示例

这里是 Python 代码,它使 LLMs 能够调用外部 API——在这种情况下是古腾堡计划,以搜索书籍。

import json, requests
from openai import OpenAI
 
OMG_API_KEY = f"<OMG_API_KEY>"
 
# You can use any model that supports tool calling
MODEL = "gemini-2.0-flash-001"
 
openai_client = OpenAI(
  base_url="https://api.ohmygpt.com/v1",
  api_key=OMG_API_KEY,
)
 
task = "What are the titles of some James Joyce books?"
 
messages = [
  {
    "role": "system",
    "content": "You are a helpful assistant."
  },
  {
    "role": "user",
    "content": task,
  }
]

定义工具

接下来,我们定义要调用的工具。请记住,该工具将由 LLM 请求,但我们在这里编写的代码最终负责执行调用并将结果返回给 LLM。

def search_gutenberg_books(search_terms):
    search_query = " ".join(search_terms)
    url = "https://gutendex.com/books"
    response = requests.get(url, params={"search": search_query})
 
    simplified_results = []
    for book in response.json().get("results", []):
        simplified_results.append({
            "id": book.get("id"),
            "title": book.get("title"),
            "authors": book.get("authors")
        })
 
    return simplified_results
 
tools = [
  {
    "type": "function",
    "function": {
      "name": "search_gutenberg_books",
      "description": "Search for books in the Project Gutenberg library based on specified search terms",
      "parameters": {
        "type": "object",
        "properties": {
          "search_terms": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "List of search terms to find books in the Gutenberg library (e.g. ['dickens', 'great'] to search for books by Dickens with 'great' in the title)"
          }
        },
        "required": ["search_terms"]
      }
    }
  }
]
 
TOOL_MAPPING = {
    "search_gutenberg_books": search_gutenberg_books
}
 

请注意,“tool”只是一个普通的函数。然后我们编写一个与 OpenAI 函数调用参数兼容的 JSON “规范”。我们将把该规范传递给 LLM,以便它知道这个工具是可用的以及如何使用它。它将在需要时请求该工具,以及任何参数。然后我们将在本地处理工具调用,进行函数调用,并将结果返回给 LLM。

工具使用和工具结果

让我们向模型发出第一个调用:

request_1 = {
    "model": gemini-2.0-flash-001,
    "tools": tools,
    "messages": messages
}
 
response_1 = openai_client.chat.completions.create(**request_1).message

LLM 以 tool_calls 的完成原因和一个 tool_calls 数组进行响应。在通用的 LLM 响应处理程序中,您会想在处理工具调用之前检查完成原因,但在这里我们将假设情况是这样的。让我们继续,处理工具调用:

# 附加对消息数组的响应,以便LLM具有完整的上下文
# 很容易忘记此步骤!
messages.append(response_1)
 
# 现在我们处理请求的工具调用,并使用我们的书籍查找工具
for tool_call in response_1.tool_calls:
    '''
    In this case we only provided one tool, so we know what function to call.
    When providing multiple tools, you can inspect `tool_call.function.name`
    to figure out what function you need to call locally.
    '''
    tool_name = tool_call.function.name
    tool_args = json.loads(tool_call.function.arguments)
    tool_response = TOOL_MAPPING[tool_name](**tool_args)
    messages.append({
      "role": "tool",
      "tool_call_id": tool_call.id,
      "name": tool_name,
      "content": json.dumps(tool_response),
    })

消息数组现在包含:

  1. 我们的原始请求
  2. LLM 的响应(包含工具调用请求)
  3. 工具调用的结果(从古腾堡项目 API 返回的 json 对象)

现在,我们可以进行第二次调用,并希望获得我们的结果!

request_2 = {
  "model": MODEL,
  "messages": messages,
  "tools": tools
}
 
response_2 = openai_client.chat.completions.create(**request_2)
 
print(response_2.choices[0].message.content)

输出将类似于:

Here are some books by James Joyce:

*   *Ulysses*
*   *Dubliners*
*   *A Portrait of the Artist as a Young Man*
*   *Chamber Music*
*   *Exiles: A Play in Three Acts*

我们做到了!我们成功地在提示中使用了一个工具。

目录