Ollama将Python函数作为参数传递,增强函数调用功能

253 阅读2分钟

Ollama将Python函数作为参数传递,增强函数调用功能

工具调用

在最新版本的Ollama Python库中,现在可以将函数作为工具提供。该库现在也全面支持类型提示,并添加了新的例子。

开始使用

首先安装或升级Ollama Python库:

pip install -U ollama

将Python函数作为工具传递

定义一个Python函数

首先定义一个常规的Python函数。为了获得更好的结果,请注解参数和返回值的类型,并可选地添加一个Google风格的文档字符串:

def add_two_numbers(a: int, b: int) -> int:
  """
  将两个数字相加
​
  参数:
    a: 第一个整数
    b: 第二个整数
​
  返回:
    int: 两个数字的和
  """
  return a + b

将函数作为工具传递给Ollama

接下来,使用tools字段将函数作为工具传递给Ollama:

import ollama
​
response = ollama.chat(
  'llama3.1',
  messages=[{'role': 'user', 'content': 'What is 10 + 10?'}],
  tools=[add_two_numbers], # 实际函数引用
)

从模型响应中调用函数

使用模型返回的工具调用和参数来调用相应的函数:

available_functions = {
  'add_two_numbers': add_two_numbers,
}
​
for tool in response.message.tool_calls or []:
  function_to_call = available_functions.get(tool.function.name)
  if function_to_call:
    print('Function output:', function_to_call(**tool.function.arguments))
  else:
    print('Function not found:', tool.function.name)

将现有函数作为工具传递

现在也可以将来自现有Python库、SDK和其他地方的函数作为工具提供。例如,以下代码将requests库中的request函数作为工具传递,以获取Ollama网站的网页内容:

import ollama
import requests
​
available_functions = {
  'request': requests.request,
}
​
response = ollama.chat(
  'llama3.1',
  messages=[{
    'role': 'user',
    'content': '获取ollama.com网页内容?',
  }],
  tools=[requests.request],
)
​
for tool in response.message.tool_calls or []:
  function_to_call = available_functions.get(tool.function.name)
  if function_to_call == requests.request:
    # 根据工具调用中指定的URL发起HTTP请求
    resp = function_to_call(
      method=tool.function.arguments.get('method'),
      url=tool.function.arguments.get('url'),
    )
    print(resp.text)
  else:
    print('Function not found:', tool.function.name)

工作原理:从函数生成JSON Schema

Ollama Python库使用Pydantic和文档字符串解析来生成JSON Schema。例如,对于本文开头声明的add_two_numbers函数,生成了以下JSON Schema(之前需要手动作为工具提供):

{
    "type": "function",
    "function": {
        "name": "add_two_numbers",
        "description": "Add two numbers",
        "parameters": {
            "type": "object",
            "required": [
                "a",
                "b"
            ],
            "properties": {
                "a": {
                    "type": "integer",
                    "description": "The first integer number"
                },
                "b": {
                    "type": "integer",
                    "description": "The second integer number"
                }
            }
        }
    }
}

Ollama Python库的其他改进

Ollama Python库的0.4版本还包括其他改进:

  • Ollama Python GitHub上的例子已更新。
  • 整个库都支持完整的类型提示,以支持直接对象访问,同时保持现有功能。