Ollama Python 函式庫 0.4 版本,具備函式呼叫功能改進

2024年11月25日

Ollama playing with tools

在最新版本的 Ollama Python 函式庫 中,現在可以將函式作為工具提供。此函式庫現在也具備完整的型別支援,並且新增了 新的範例

開始使用

首先安裝或升級 Ollama Python 函式庫

pip install -U ollama

將 Python 函式作為工具傳遞

定義一個 Python 函式

首先定義一個常規的 Python 函式。為了獲得更好的結果,請標註參數和回傳值類型,並可選擇性地新增 Google 風格的 docstring

def add_two_numbers(a: int, b: int) -> int:
  """
  Add two numbers

  Args:
    a: The first integer number
    b: The second integer number

  Returns:
    int: The sum of the two numbers
  """
  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], # Actual function reference
)

從模型回應中呼叫函式

使用模型回傳的工具呼叫和引數來呼叫相應的函式

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': 'get the ollama.com webpage?',
  }],
  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:
    # Make an HTTP request to the URL specified in the tool call
    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 和 docstring 解析來產生 JSON schema。例如,對於本文開頭宣告的 add_two_nubmers 函式,會產生以下 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 上更新。
  • 整個函式庫的完整型別支援,以支援直接物件存取,同時維持現有功能。