Skip to content

LV010-API-Reference

一、简介

1. 基础 URL

我们安装完 Ollama 并运行后,它默认在下面的地址提供服务:

md
http://localhost:11434/api

对于 Ollama 提供的一些云上可调用的模型(cloud models),可以使用相同的 api,基础 URL 如下:

md
https://ollama.com/api

2. curl 请求实例

2.1 local model

我们在本地运行了下面的模型:

shell
  /workspace git:(master) ollama list
NAME               ID              SIZE      MODIFIED       
qwen3:0.6b         7df6b6e09427    522 MB    11 minutes ago    
qwen3:14b          bdbd181c33f2    9.3 GB    11 minutes ago    
qwen3:32b          030ee887880f    20 GB     11 minutes ago    
qwen3:1.7b         8f68893c685c    1.4 GB    11 minutes ago    
qwen3:1.7b-q8_0    29b6a7a420a4    2.2 GB    11 minutes ago    
qwen3:30b          ad815644918f    18 GB     11 minutes ago    
qwen3:4b           359d7dd4bcda    2.5 GB    11 minutes ago    
qwen3:8b           500a1f067a9f    5.2 GB    11 minutes ago    
qwen3-coder:30b    06c1097efce0    18 GB     11 minutes ago

在 Ollama 运行后,API 是自动可用的,我们不需要做其他的操作。而且通过 http://localhost:11434 在本地访问 Ollama 的 API 时,无需进行身份验证。我们通过 curl 访问:

shell
curl http://localhost:11434/api/generate -d '{
  "model": "qwen3:0.6b",
  "prompt": "为什么天空是蓝色的?"
}'

# powershell 中可以这样写
Invoke-RestMethod -Uri "http://localhost:11434/api/generate" `
    -Method Post `
    -Headers @{"Content-Type"="application/json"} `
    -Body '{
        "model": "qwen3:0.6b",
        "prompt": "为什么天空是蓝色的?"
    }'

【例】

shell
  /workspace git:(master) curl http://localhost:11434/api/generate -d '{
  "model": "qwen3:0.6b",
  "prompt": "为什么天空是蓝色的?"
}'
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.193065735Z","response":"","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.195269699Z","response":"","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.197507653Z","response":"","thinking":"嗯","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.199661628Z","response":"","thinking":",","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.201919511Z","response":"","thinking":"用户","done":false}
#...
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.226201678Z","response":"","thinking":"需要","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.228365013Z","response":"","thinking":"回忆","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.230538958Z","response":"","thinking":"相关的","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-10T23:53:15.232741753Z","response":"","thinking":"科学","done":false}

2.2 cloud model

Cloud - Ollama

Ollama 的云模型是 Ollama 中一种新型模型,无需强大的 GPU 即可运行,因为它运行在云端,我们通过 api 即可请求服务,这里需要注意,我们通过 ollama.com 运行云模型的时候需要进行身份认证(Authentication)。

我们需要登录 Ollama,然后在这里【 Ollama keys · Settings】生成自己的 API KEY。

Tips:

(1)API 密钥目前不会过期,只会在申请时可见一次,后续就看不到了,注意保存。

(2)云模型的调用是 免费 的,但是是 有限制 的,但是我们可以在 【Plan & Billing · Settings】这里看到。

然后我们通过下面的命令来调用看一下:

shell
export OLLAMA_LLM_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxx
curl https://ollama.com/api/generate \
  -H "Authorization: Bearer $OLLAMA_LLM_KEY" \
  -d '{
    "model": "gpt-oss:120b",
    "prompt": "为什么天空是蓝色的?",
    "stream": false
  }'

【例】

shell
  /workspace git:(master) curl https://ollama.com/api/generate \
  -H "Authorization: Bearer $OLLAMA_LLM_KEY" \
  -d '{
    "model": "gpt-oss:120b",
    "prompt": "为什么天空是蓝色的?",
    "stream": false
  }'

{"model":"gpt-oss:120b","created_at":"2025-12-11T00:02:39.444057303Z","response":"**简要答案**  \n天空呈蓝色是因为大气层中的气体分子把太阳光散射了,而蓝光比其他颜色的光更容易被散射。我们的眼睛看到的正是这部分被散射出来的蓝光。\n\n---\n\n## 1. 太阳光的组成  \n\n- 太阳光是白光,实际上是由不同波长(颜色)的光组成的。  \n- 可见光的波长范围大约是 **380 nm(紫)到 750 nm(红)**。  \n- 其中蓝光的波长约在 **450–495 nm**,比红光(≈620–750 nm)短。\n\n## 2. 大气中的光散射——瑞利散射(Rayleigh scattering)\n\n### 什么是瑞利散射?\n\n- 当光波经过尺寸远小于其波长的粒子(如氮气、氧气分子)时,会发生弹性散射,这种散射称为 **瑞利散射**。  \n- 瑞利散射的散射强度 **I** 与波长 **λ** 的四次方成反比:\n\n\\[\nI \\propto \\frac{1}{\\lambda^{4}}\n\\]\n\n- 这意味着 **波长越短(颜色越偏蓝),散射得越强**。\n\n### 在大气中的表现\n\n- 大气中主要的散射粒子是气体分子(直径约 0.1 nm),远小于可见光波长。  \n- 由于 **\\(1/λ^{4}\\)** 的关系,蓝光(λ≈470 nm)比红光(λ≈650 nm)散射强约 **(650/470)^4 ≈ 10 倍**。  \n- 因此,当阳光穿过大气层时,蓝光被大量向四面八方散射,而大部分红光仍沿直线路径继续前进。\n\n## 3. 我们为什么看到蓝天?\n\n1. **光线进入大气层**:太阳光从宇宙空间进入地球大气。  \n2. **蓝光被散射**:蓝光在大气中被气体分子强烈散射,向四面八方扩散。  \n3. **眼睛接收散射光**:我们在任何方向(除了直接看向太阳的方向)看到的主要是这些被散射的蓝光。  \n4. **白天的视觉感受**:由于散射光占主导,天空呈现蓝色。如果在非常清晰、无尘的高海拔地区,天空会显得更深的蔚蓝,因为散射的路径更长,蓝光被更充分地散射。\n\n## 4. 为什么日落时呈红色?\n\n- 当太阳接近地平线时,光线需要穿过更厚的大气层(路径更长)。  \n- 大气对蓝光的散射在长路径上几乎把所有蓝光都“拿走”,剩下的主要是波长更长、散射更弱的红光和橙光。  \n- 于是我们看到的日出、日落呈红橙色。\n\n## 5. 影响因素与例外情况\n\n| 因素 | 对天空颜色的影响 |\n|------|-------------------|\n| **大气颗粒(如尘埃、雾、烟)** | 粒子尺寸在可见光范围内会产生 **米散射**(Mie scattering),对所有波长的散射相对均匀,使天空偏白或灰。 |\n| **水汽含量** | 高湿度时,微小水滴也会产生米散射,天空会显得更淡甚至呈现淡蓝或淡灰。 |\n| **极光** | 高层大气中带电粒子与气体碰撞产生发光,呈绿色、红色或紫色,和瑞利散射无关。 |\n| **日食** | 月亮遮挡太阳光后,天空短时间变暗,颜色逐渐转向深蓝或黑色,随后恢复。 |\n\n## 6. 小结\n\n- **蓝天的根本原因**:**瑞利散射**——大气分子对短波长(蓝光)散射更强。  \n- **感知**:我们的眼睛捕捉到大量向各方向散射的蓝光,于是把整个天穹看成蓝色。  \n- **其它现象**(如日落红色、雾天灰白)都是由散射机制的不同尺度或光路长度导致的。\n\n 希望这段解释能帮助你理解为什么天空是蓝色的!如果还有其他关于大气光学或相关现象的问题,随时提问。"," thinking ":" The user asks in Chinese: \" Why is the sky blue?\" Need to explain Rayleigh scattering, wavelength dependence, etc., in Chinese. Should be clear, maybe include some details about atmosphere, scattering, human eye perception. Also could mention why sunsets are red. Provide concise yet thorough answer."," done ": true," done_reason ":" stop "," total_duration ": 6851231576," prompt_eval_count ": 74," eval_count ": 1126}

3. HTTPX

3.1 HTTPX 简介

HTTPX 是一个功能全面的 Python 3 HTTP 客户端,提供同步和异步 API,并支持 HTTP/1.1 和 HTTP/2。

HTTPX - 中文文档

HTTPX

使用 pip 安装 HTTPX:

shell
pip install httpx

在后面的大模型调用中常用的就是 post 和 get 请求,我们可以安装好库看一下,其实 httpx 都是封了好几层,大概的调用关系是这样的:

md
httpx.post --> request("POST", ...)
httpx.get  --> request("GET", ...)

更深入的其实还有,但是这里就简单了解到这里吧。

httpx.posthttpx.get 内部调用的是 httpx.request , 在 request 这里有参数的详细说明。这里就不赘述了,后面看源码注释就可以了,这里还要关注返回值,返回值是一个 Response 对象,主要后面会接触到下面几个属性:

参考文档:Developer Interface - response 或者 开发者接口 - response

3.2 post 请求示例

我们可以使用 httpx 的 post 请求来实现上面对大模型 api 的请求。

3.2.1 local model
python
import httpx

response = httpx.post(
    "http://localhost:11434/api/generate",
    json={
        "model": "qwen3:0.6b",
        "prompt": "AI是什么,回答不要超过10个字",
        "stream": False,
    },
)

print(response.json())

我们运行的话,会得到以下输出信息:

shell
{'model': 'qwen3:0.6b', 'created_at': '2025-12-11T15:16:30.3675775Z', 'response': '人工智能', 'thinking': '好的,用户问AI 是什么,我需要回答不超过10个字。首先,AI是人工智能,是计算机科学的分支。要简洁,所以直接写“人工智能”就可以了。确保字数刚好,没有多余内容。\n', 'done': True, 'done_reason': 'stop', 'context': [151644, 872, 198, 15469, 102021, 3837, 102104, 100148, 100381, 16, 15, 18947, 18600, 608, 26865, 151645, 198, 151644, 77091, 198, 151667, 198, 99692, 3837, 20002, 56007, 15469, 102021, 3837, 35946, 85106, 102104, 106070, 16, 15, 18947, 18600, 1773, 101140, 3837, 15469, 20412, 104455, 3837, 20412, 104564, 99891, 9370, 103799, 1773, 30534, 110485, 3837, 99999, 101041, 61443, 2073, 104455, 854, 108466, 1773, 103944, 18600, 8863, 109586, 3837, 80443, 115916, 43815, 8997, 151668, 271, 104455], 'total_duration': 369561700, 'load_duration': 85598600, 'prompt_eval_count': 20, 'prompt_eval_duration': 36399500, 'eval_count': 54, 'eval_duration': 234524100}
3.2.2 cloud model
python
import httpx
import os

url = "https://ollama.com/api/generate"
api_key = os.getenv("OLLAMA_LLM_KEY")
if not api_key:
    print("警告: OLLAMA_LLM_KEY 环境变量未设置,将不使用认证头")
    headers = {}
else:
    headers = {"Authorization": f"Bearer {api_key}"}

response = httpx.post(
    url,
    headers=headers,
    json={
        "model": "gpt-oss:120b",
        "prompt": "AI 是什么,需要回答不超过10个字.",
        "stream": False
    },
)

print(response.json())

运行会得到以下输出:

shell
{'model': 'gpt-oss:120b', 'created_at': '2025-12-11T15:22:11.779070751Z', 'response': '人工智能', 'thinking': 'The user asks in Chinese: "AI 是什么,需要回答不超过10个字." They want a definition of AI, answer no more than 10 characters (Chinese characters). Must be <=10 characters. Provide concise definition. Something like "人工智能". That\'s 4 characters. Or "机器学习". 4 characters. Probably "人工智能". That\'s 4 characters. It\'s within limit. Provide just that.', 'done': True, 'done_reason': 'stop', 'total_duration': 670799356, 'prompt_eval_count': 78, 'eval_count': 96}

3.3 get 请求

Get version - Ollama

我门还可以使用 get 请求,例如查看 ollama 版本。

3.3.1 local model
python
import httpx

response = httpx.get("http://localhost:11434/api/version")
print(response.text)

运行可能会看到如下输出:

shell
{"version":"0.13.2"}
3.3.2 cloud model
python
import httpx
import os

url = "https://ollama.com/api/version"
api_key = os.getenv("OLLAMA_LLM_KEY")
if not api_key:
    print("警告: OLLAMA_LLM_KEY 环境变量未设置,将不使用认证头")
    headers = {}
else:
    headers = {"Authorization": f"Bearer {api_key}"}

response = httpx.get(url, headers=headers)

print(response.text)

运行可能会得到如下内容:

shell
{"version":"0.0.0"}

二、流式传输

1. 流式传输示例

某些 API 端点默认会流式传输响应,例如 /api/generate。这些响应以换行分隔的 JSON 格式(即 application/x-ndjson 内容类型)提供。例如:

shell
curl http://localhost:11434/api/generate -d '{
  "model": "qwen3:0.6b",
  "prompt": "介绍一下AI,不要超过10个字"
}'

会得到下面的输出:

shell
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.675043089Z","response":"人工智能","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.677173914Z","response":"(","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.679426426Z","response":"AI","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.681735548Z","response":")","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.68405562Z","response":"是指","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.686398301Z","response":"模拟","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.688748432Z","response":"人类","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.69124742Z","response":"智能","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.693636341Z","response":"的","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.696060011Z","response":"系统","done":false}
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:47:46.69849513Z","response":"。","done":false}

2. 禁用流式输出

对于任何支持流式传输的端点,可以通过在请求体中提供 {"stream": false} 来禁用流式传输。这样的话响应会以 application/json 格式返回。

shell
curl http://localhost:11434/api/generate -d '{
  "model": "qwen3:0.6b",
  "prompt": "介绍一下AI,不要超过10个字",
  "stream": false
}'

然后会看到以下输出:

shell
{"model":"qwen3:0.6b","created_at":"2025-12-11T14:50:28.396618291Z","response":"人工智能(AI)是通过算法和数据学习并优化的系统。","thinking":"好的,用户让我介绍一下AI,不超过10个字。首先,我需要确保内容简洁,同时涵盖关键点。AI是人工智能的缩写,所以直接用“人工智能”开头。接下来,可能需要提到它的定义,比如“通过算法和数据学习”之类的。然后要强调其应用,比如“自动化、预测和优化”。还要提到它的发展历史,比如“从1950年代到今天”。最后加上应用场景,比如“医疗、金融和自动驾驶”。这样总字数控制在10个字以内,同时信息完整。检查一下有没有超过字数,确保符合要求。\n","done":true,"done_reason":"stop","context":[151644,872,198,109432,15469,3837,100148,100381,16,15,18947,18600,608,26865,151645,198,151644,77091,198,151667,198,99692,3837,20002,104029,109432,15469,3837,106070,16,15,18947,18600,1773,101140,3837,35946,85106,103944,43815,110485,3837,91572,102994,99936,27442,1773,15469,20412,104455,9370,99872,61443,3837,99999,101041,11622,2073,104455,854,111749,1773,104326,3837,87267,85106,104496,104121,91282,3837,101912,2073,67338,107018,33108,20074,100134,854,106896,1773,101889,30534,104046,41146,99892,3837,101912,2073,105550,5373,104538,33108,103983,55807,104019,104496,99652,103949,100022,3837,101912,2073,45181,16,24,20,15,104227,26939,100644,55807,100161,102189,116541,3837,101912,2073,100182,5373,100015,33108,109044,55807,99654,59743,18600,8863,100359,18493,16,15,18947,18600,108341,3837,91572,27369,100873,1773,101071,100158,104710,100381,18600,8863,3837,103944,101137,101882,8997,151668,271,104455,9909,15469,7552,20412,67338,107018,33108,20074,100134,62926,103983,9370,72448,1773],"total_duration":416016938,"load_duration":77151500,"prompt_eval_count":19,"prompt_eval_duration":2507258,"eval_count":149,"eval_duration":290408588}#

3. 怎么选择?

Streaming 流式传输(默认)(1)实时响应生成;
(2)更低的感知延迟;
(3)更适合长生成内容。
Non-streaming 非流式传输 (1)处理更简单;
(2)更适合简短回复或结构化输出;
(3)在某些应用中更易于处理。