Ollama Python 程式庫 0.4 版本,具備函數呼叫功能改進
2024 年 11 月 25 日
在最新版本的 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 上的範例已更新。
- 整個程式庫的完整類型支援,可在維持現有功能的情況下支援直接物件存取。