本地部署的Ollama模型API访问方式详解
在本地部署的Ollama模型中,开发者可以通过两种不同的API方式进行访问。这两种方式各有特点,适用于不同的应用场景。本文将详细介绍这两种API访问方式,并提供相应的代码示例。
1. 通过OLLAMA API访问
OLLAMA API是一种无需API Key的访问方式,适合在本地环境中直接与Ollama模型进行交互。开发者可以通过简单的HTTP请求来测试模型的可用性,并获取模型的响应。
以下是一个使用Python的requests库与OLLAMA API进行交互的示例代码:
import requests
def test_ollama_chat(base_url="http://localhost:11434"):
headers = {
"Content-Type": "application/json"
}
data = {
"model": "deepseek-r1:32b", # 替换为你的 Ollama 模型名称
"messages": [
{
"role": "user",
"content": "Why is the sky blue?"
}
]
}
try:
response = requests.post(f"{base_url}/v1/chat/completions", headers=headers, json=data)
if response.status_code == 200:
result = response.json()
if "choices" in result and len(result["choices"]) > 0:
print("Ollama 模型 chat 可用,回复内容:")
print(result["choices"][0]["message"]["content"])
return True
else:
print("Ollama 模型 chat 测试失败,未返回有效回复")
return False
else:
print(f"Ollama 模型 chat 测试失败,状态码:{response.status_code}")
return False
except requests.exceptions.RequestException as e:
print(f"Ollama 模型 chat 测试请求失败:{e}")
return False
在该示例中,我们通过POST请求向OLLAMA API发送一个包含模型名称和用户消息的JSON数据包。如果请求成功,模型将返回一个包含回复内容的JSON响应。
2. 通过Open WebUI的API访问
Open WebUI的API访问方式需要通过API Key进行身份验证,适合在需要控制访问权限的场景中使用。这种方式通过Open WebUI分发API Key,确保只有授权的用户能够访问模型。
以下是一个使用Python的requests库与Open WebUI API进行交互的示例代码:
import requests
import json
def test_ollama_chat(apikey, base_url="http://localhost:3000"):
headers = {
"Authorization": f"Bearer {apikey}",
"Content-Type": "application/json"
}
data = {
"model": "deepseek-r1:32b", # 替换为你的 Ollama 模型名称
"messages": [
{
"role": "user",
"content": "Why is the sky blue?"
}
]
}
try:
response = requests.post(f"{base_url}/api/chat/completions", headers=headers, data=json.dumps(data))
if response.status_code == 200:
result = response.json()
if "choices" in result and len(result["choices"]) > 0:
print("Ollama 模型 chat 可用,回复内容:")
print(result["choices"][0]["message"]["content"])
return True
else:
print("Ollama 模型 chat 测试失败,未返回有效回复")
return False
else:
print(f"Ollama 模型 chat 测试失败,状态码:{response.status_code}")
return False
except requests.exceptions.RequestException as e:
print(f"Ollama 模型 chat 测试请求失败:{e}")
return False
if __name__ == "__main__":
apikey = "sk-xxxxxxx" # 替换为你的 OpenWebUI APIKey
test_ollama_chat(apikey)
在该示例中,我们通过POST请求向Open WebUI的API发送一个包含模型名称和用户消息的JSON数据包,并在请求头中添加了API Key进行身份验证。如果请求成功,模型将返回一个包含回复内容的JSON响应。