Ollama Anthropic 兼容

2026-10-29 19:01 更新

Ollama 实现了 Anthropic Messages API 的子集,让 Claude Code 这类按 Anthropic 协议说话的工具能直接接本地模型。

版本基线 v0.40.12,官方 docs.ollama.com/api/anthropic-compatibility。

一、Base URL

目标 地址
本地 http://localhost:11434
直连云端 https://ollama.com

注意不带 /v1——Anthropic 客户端会自己在后面拼 /v1/messages。这是与 OpenAI 兼容层最容易搞混的一点。

二、云端直连

export OLLAMA_API_KEY="your_api_key"

curl https://ollama.com/v1/messages \
  -H "Authorization: Bearer $OLLAMA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "gemma4:31b",
    "max_tokens": 1024,
    "messages": [
      { "role": "user", "content": "Say hello in one sentence." }
    ]
  }'

文本在 content 里取。

两个关键约束:

  • 云端端点只认 Authorization: Bearer,不接受单独用 x-api-key
  • anthropic-version 不能低于 2023-06-01,更低的值会被拒绝

三、本地接入

环境变量(给 Claude Code 这类工具)

export ANTHROPIC_AUTH_TOKEN=ollama   # 必填但被忽略
export ANTHROPIC_BASE_URL=http://localhost:11434

Python 客户端

import anthropic

client = anthropic.Anthropic(
    base_url='http://localhost:11434',
    api_key='ollama',  # required but ignored
)

message = client.messages.create(
    model='qwen3-coder',
    max_tokens=1024,
    messages=[{'role': 'user', 'content': 'Hello, how are you?'}]
)
print(message.content[0].text)

流式

with client.messages.stream(
    model='qwen3-coder',
    max_tokens=1024,
    messages=[{'role': 'user', 'content': 'Count from 1 to 10'}]
) as stream:
    for text in stream.text_stream:
        print(text, end='', flush=True)

工具调用

message = client.messages.create(
    model='qwen3-coder',
    max_tokens=1024,
    tools=[{
        'name': 'get_weather',
        'description': 'Get the current weather in a location',
        'input_schema': {
            'type': 'object',
            'properties': {
                'location': {'type': 'string', 'description': 'The city and state'}
            },
            'required': ['location']
        }
    }],
    messages=[{'role': 'user', 'content': "What's the weather in San Francisco?"}]
)

for block in message.content:
    if block.type == 'tool_use':
        print(f'Tool: {block.name}')
        print(f'Input: {block.input}')

四、/v1/messages 支持范围

支持的特性:Messages、流式、系统提示词、多轮对话、视觉(图片)、工具(函数调用)、工具结果、思考/扩展思考。

支持的请求字段:model、max_tokens、messages(文本/图片 base64/内容块数组/tool_use/tool_result/thinking 块)、system、stream、temperature、top_p、top_k、stop_sequences、tools、thinking、output_config.effort、tool_choice、metadata。

支持的响应字段:id、type、role、model、content(text / tool_use / thinking 块)、stop_reason(end_turn / max_tokens / tool_use)、usage(input_tokens / output_tokens)。

流式事件:message_start、content_block_start、content_block_delta(text_delta / input_json_delta / thinking_delta)、content_block_stop、message_delta、message_stop、ping、error。

五、明确不支持的

这是选型前必须看的一张表:

特性 说明
/v1/messages/count_tokens 没有 token 计数端点
tool_choice 不能强制指定工具,也不能禁用工具
metadata 请求元数据(user_id)
Prompt caching 不支持 cache_control 前缀缓存
Batches API 无异步批处理
Citations 无引用内容块
PDF 支持 不支持 document 内容块
服务端错误事件 流式中的 error 事件不走 SSE,错误直接返回 HTTP 状态

部分支持:

特性 状态
图片内容 支持 base64,不支持 URL 图片
扩展思考 基础支持,budget_tokens 接受但不强制

tool_choice 缺失这一条影响比较大——如果你的业务依赖「强制模型必须调用某个工具」,这里做不到。

六、行为差异(相比官方 Anthropic API)

  • 本地服务不校验 API Key
  • 云端端点拒绝低于 2023-06-01 的 anthropic-version
  • token 计数是近似值,基于底层模型自己的 tokenizer,和 Claude 的计数不一致

第三条意味着:如果你按 usage.input_tokens 做精准计费,数字只能当参考。

七、兼容默认模型名

有些工具写死了 claude-3-5-sonnet 这类名字,用 ollama cp 复制一份:

ollama cp qwen3-coder claude-3-5-sonnet

然后正常调用:

curl http://localhost:11434/v1/messages \
    -H "Content-Type: application/json" \
    -d '{
        "model": "claude-3-5-sonnet",
        "max_tokens": 1024,
        "messages": [{"role": "user", "content": "Hello!"}]
    }'

动手试

## ① 本地 /v1/messages 是否就绪
curl http://localhost:11434/v1/messages \
  -H "Content-Type: application/json" \
  -d '{"model":"qwen3-coder","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}'

## ② 配合 Claude Code(详见 12.5)
export ANTHROPIC_AUTH_TOKEN=ollama
export ANTHROPIC_API_KEY=""
export ANTHROPIC_BASE_URL=http://localhost:11434
claude --model qwen3-coder

Claude Code 的完整接入见 12.5 Ollama Claude Code。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号