Skip to content

API 参考

Ollama 提供了强大的 REST API,让您可以轻松地将大语言模型集成到您的应用程序中。

基础信息

  • 基础 URL: http://localhost:11434
  • 内容类型: application/json
  • 认证: 无需认证(本地运行)

核心端点

生成文本

生成模型响应的主要端点。

http
POST /api/generate

请求体:

json
{
  "model": "gemma3",
  "prompt": "解释量子计算的基本原理",
  "stream": false,
  "options": {
    "temperature": 0.7,
    "top_p": 0.9,
    "max_tokens": 1000
  }
}

响应:

json
{
  "model": "gemma3",
  "created_at": "2024-01-15T10:30:00Z",
  "response": "量子计算是一种利用量子力学原理进行信息处理的计算方式...",
  "done": true,
  "total_duration": 2500000000,
  "load_duration": 500000000,
  "prompt_eval_count": 15,
  "prompt_eval_duration": 300000000,
  "eval_count": 150,
  "eval_duration": 1700000000
}

对话聊天

支持多轮对话的聊天端点。

http
POST /api/chat

请求体:

json
{
  "model": "llama3.2",
  "messages": [
    {
      "role": "user",
      "content": "你好,请介绍一下自己"
    },
    {
      "role": "assistant", 
      "content": "你好!我是一个AI助手,可以帮助您回答问题和完成各种任务。"
    },
    {
      "role": "user",
      "content": "你能帮我写代码吗?"
    }
  ],
  "stream": false
}

模型管理

列出模型

http
GET /api/tags

响应:

json
{
  "models": [
    {
      "name": "llama3.2:latest",
      "modified_at": "2024-01-15T10:00:00Z",
      "size": 4661224448,
      "digest": "sha256:abc123...",
      "details": {
        "format": "gguf",
        "family": "llama",
        "families": ["llama"],
        "parameter_size": "8B",
        "quantization_level": "Q4_0"
      }
    }
  ]
}

拉取模型

http
POST /api/pull

请求体:

json
{
  "name": "llama3.2"
}

删除模型

http
DELETE /api/delete

请求体:

json
{
  "name": "llama3.2"
}

参数说明

生成参数

参数类型默认值说明
temperaturefloat0.8控制输出的随机性,0-2之间
top_pfloat0.9核采样参数,0-1之间
top_kint40限制候选词数量
max_tokensint-最大生成token数
stoparray-停止生成的字符串
repeat_penaltyfloat1.1重复惩罚因子

流式响应

设置 "stream": true 可以获得流式响应:

bash
curl http://localhost:11434/api/generate \
   -H "Content-Type: application/json" \
   -d '{
     "model": "llama3.2",
     "prompt": "写一首关于春天的诗",
     "stream": true
   }'

流式响应格式:

json
{"model":"llama3.2","created_at":"2024-01-15T10:30:00Z","response":"春","done":false}
{"model":"llama3.2","created_at":"2024-01-15T10:30:01Z","response":"风","done":false}
{"model":"llama3.2","created_at":"2024-01-15T10:30:02Z","response":"轻","done":false}
...
{"model":"llama3.2","created_at":"2024-01-15T10:30:10Z","response":"","done":true}

错误处理

API 使用标准的 HTTP 状态码:

状态码说明
200请求成功
400请求参数错误
404模型未找到
500服务器内部错误

错误响应格式:

json
{
  "error": "model 'nonexistent-model' not found"
}

官方客户端库

Python 库

安装:

bash
pip install ollama

使用示例:

python
import ollama

# 生成文本
response = ollama.generate(
    model='llama3.2',
    prompt='解释机器学习的基本概念'
)
print(response['response'])

# 聊天对话
messages = [
    {'role': 'user', 'content': '你好!'},
    {'role': 'assistant', 'content': '你好!有什么可以帮助您的吗?'},
    {'role': 'user', 'content': '请解释一下深度学习'}
]

response = ollama.chat(
    model='gemma3',
    messages=messages
)
print(response['message']['content'])

# 流式生成
for chunk in ollama.generate(model='gemma3', prompt='写一个故事', stream=True):
    print(chunk['response'], end='', flush=True)

JavaScript 库

安装:

bash
npm install ollama

使用示例:

javascript
import { Ollama } from 'ollama'

const ollama = new Ollama({ host: 'http://localhost:11434' })

// 生成文本
const response = await ollama.generate({
  model: 'gemma3',
  prompt: '解释人工智能的发展历程'
})
console.log(response.response)

// 聊天对话
const chatResponse = await ollama.chat({
  model: 'gemma3',
  messages: [
    { role: 'user', content: '你好!' },
    { role: 'assistant', content: '你好!有什么可以帮助您的吗?' },
    { role: 'user', content: '请推荐一些学习编程的资源' }
  ]
})
console.log(chatResponse.message.content)

// 流式生成
const stream = await ollama.generate({
  model: 'llama3.2',
  prompt: '写一首诗',
  stream: true
})

for await (const chunk of stream) {
  process.stdout.write(chunk.response)
}

最佳实践

1. 错误重试

python
import time
import ollama

def generate_with_retry(model, prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            return ollama.generate(model=model, prompt=prompt)
        except Exception as e:
            if attempt == max_retries - 1:
                raise e
            time.sleep(2 ** attempt)  # 指数退避

2. 批量处理

python
def batch_generate(model, prompts, batch_size=5):
    results = []
    for i in range(0, len(prompts), batch_size):
        batch = prompts[i:i + batch_size]
        for prompt in batch:
            result = ollama.generate(model=model, prompt=prompt)
            results.append(result)
    return results

3. 温度控制

python
# 创意写作 - 高温度
creative_response = ollama.generate(
    model='llama3.2',
    prompt='写一个科幻故事',
    options={'temperature': 1.2}
)

# 事实性回答 - 低温度
factual_response = ollama.generate(
    model='llama3.2',
    prompt='什么是光合作用?',
    options={'temperature': 0.3}
)

下一步

让大语言模型触手可及 - Get up and running with large language models