
大模型 API 異步調用優化:高效并發與令牌池設計實踐
在上述代碼中,chat
函數用于向指定的模型發送請求,并獲取模型的響應。model
參數指定了要使用的模型,messages
參數是一個包含用戶消息的列表。運行上述代碼后,模型會返回相應的回答。
Ollama Python SDK 還支持流式響應,可以在發送請求時通過設置 stream=True
來啟用響應流式傳輸。這種方式特別適合處理長文本或實時交互的場景。例如:
Python復制
from ollama import chat
stream = chat(
model='deepseek-coder',
messages=[{'role': 'user', 'content': '你是誰?'}],
stream=True
)
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)
通過流式響應,模型的輸出會逐塊返回,每部分都可以即時處理,從而提高交互的實時性。
Ollama Python SDK 提供了強大的自定義功能,開發者可以通過創建自定義客戶端來進一步控制請求配置。例如,可以設置自定義的請求頭或指定本地服務的 URL:
Python復制
from ollama import Client
client = Client(
host='http://localhost:11434',
headers={'x-some-header': 'some-value'}
)
response = client.chat(
model='deepseek-coder',
messages=[
{'role': 'user', 'content': '你是誰?'}
]
)
print(response['message']['content'])
此外,Ollama Python SDK 還支持異步客戶端,適用于需要并發的場景。異步客戶端的使用方式與同步客戶端類似,但請求是異步執行的,可以提高性能。例如:
Python復制
import asyncio
from ollama import AsyncClient
async def chat():
message = {'role': 'user', 'content': '你是誰?'}
response = await AsyncClient().chat(
model='deepseek-coder',
messages=[message]
)
print(response['message']['content'])
asyncio.run(chat())
異步客戶端還支持流式響應。通過將 stream=True
設置為異步生成器,可以逐部分地異步返回響應,每部分都可以即時處理:
Python復制
import asyncio
from ollama import AsyncClient
async def chat():
message = {'role': 'user', 'content': '你是誰?'}
async for part in await AsyncClient().chat(
model='deepseek-coder',
messages=[message],
stream=True
):
print(part['message']['content'], end='', flush=True)
asyncio.run(chat())
Ollama Python SDK 提供了許多高級功能,用于操作和管理模型。以下是一些常用的 API 方法:
Python復制
ollama.chat(model='llama3.2', messages=[{'role': 'user', 'content': 'Why is the sky blue?'}])
Python復制
ollama.generate(model='llama3.2', prompt='Why is the sky blue?')
Python復制
ollama.list()
Python復制
ollama.show('llama3.2')
Python復制
ollama.create(model='example', from_='llama3.2', system="You are Mario from Super Mario Bros.")
Python復制
ollama.copy('llama3.2', 'user/llama3.2')
Python復制
ollama.delete('llama3.2')
Python復制
ollama.pull('llama3.2')
Python復制
ollama.push('user/llama3.2')
Python復制
ollama.embed(model='llama3.2', input='The sky is blue because of rayleigh scattering')
Python復制
ollama.ps()
這些方法為開發者提供了強大的工具,可以方便地管理和操作本地部署的 Ollama 模型。
除了直接使用 Ollama Python SDK 外,還可以通過 LangChain 庫來調用 Ollama 模型。LangChain 是一個流行的自然語言處理庫,提供了豐富的功能和工具。以下是使用 LangChain 調用 Ollama 的示例:
bash復制
pip install langchain
pip install langchain_community
Python復制
from langchain_community.llms import Ollama
host = "localhost"
port = "11434"
llm = Ollama(base_url=f"http://{host}:{port}", model="qwen2:1.5b", temperature=0)
res = llm.invoke("你是誰")
print(res)
在上述代碼中,Ollama
類用于創建一個與 Ollama 模型的連接,base_url
參數指定了 Ollama 服務的地址,model
參數指定了要使用的模型,temperature
參數用于調整生成結果的創造性程度。運行上述代碼后,模型會返回相應的回答。
在某些情況下,可能需要直接通過 HTTP 請求調用 Ollama 模型。這種方式更加靈活,可以方便地與其他系統集成。以下是使用 requests
庫調用 Ollama 的示例:
requests
庫:bash復制
pip install requests
Python復制
import requests
host = "localhost"
port = "11434"
url = f"http://{host}:{port}/api/chat"
model = "qwen2:1.5b"
headers = {"Content-Type": "application/json"}
data = {
"model": model,
"options": {
"temperature": 0
},
"stream": False,
"messages": [
{"role": "user", "content": "你是誰?"}
]
}
response = requests.post(url, json=data, headers=headers, timeout=60)
res = response.json()
print(res)
在上述代碼中,requests.post
方法用于發送 HTTP POST 請求,url
參數指定了 Ollama 服務的地址,data
參數包含了請求的正文內容,headers
參數指定了請求頭。運行上述代碼后,模型會返回相應的回答。
Ollama Python SDK 的最新版本(0.4)引入了許多改進,特別是對函數調用的支持。現在,開發者可以將 Python 函數作為工具傳遞給 Ollama 模型,并在模型響應中調用這些函數。這種方式為開發者提供了更大的靈活性,可以將自定義邏輯與模型生成的內容相結合。
以下是使用 Ollama Python SDK 0.4 版本的示例:
Python復制
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
Python復制
import ollama
response = ollama.chat(
'llama3.1',
messages=[{'role': 'user', 'content': 'What is 10 + 10?'}],
tools=[add_two_numbers]
)
Python復制
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)
此外,Ollama Python SDK 0.4 版本還支持從現有 Python 庫中傳遞函數作為工具。例如,可以將 requests
庫中的 request
函數作為工具傳遞給 Ollama:
Python復制
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:
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)
Ollama Python SDK 0.4 版本通過 Pydantic 和 docstring 解析生成 JSON Schema,從而簡化了工具的定義和傳遞過程。例如,對于 add_two_numbers
函數,生成的 JSON Schema 如下:
JSON復制
{
"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 SDK,方便開發者在 Python 環境中調用本地部署的大模型。通過 Ollama Python SDK,開發者可以輕松地實現文本生成、對話生成、模型管理等功能。此外,Ollama Python SDK 的最新版本引入了許多改進,特別是對函數調用的支持,為開發者提供了更大的靈活性。通過本文的介紹,希望讀者能夠更好地理解和使用 Ollama Python SDK,從而在自然語言處理項目中發揮其強大的功能。