Ollama API 交互详解Ollama 提供了一套完整的 REST API允许开发者通过 HTTP 请求与本地运行的模型进行交互。默认服务地址为http://localhost:11434。1. 核心 API 端点1.1 对话补全 (POST /api/chat)最常用的端点支持多轮对话符合 ChatML 格式。请求体结构:{model:llama3,// 模型名称messages:[// 消息列表{role:system,content:你是一个助手},{role:user,content:你好},{role:assistant,content:你好}],stream:false,// 是否流式输出options:{// 可选参数temperature:0.7,num_predict:500,top_p:0.9},keep_alive:5m// 模型保持加载时间}响应示例 (非流式):{model:llama3,created_at:2023-10-27T10:00:00.000Z,message:{role:assistant,content:你好有什么可以帮你的吗},done:true,total_duration:1500000000,load_duration:100000000,prompt_eval_count:15,eval_count:20,eval_duration:1400000000}流式响应示例:{model:llama3,created_at:...,message:{role:assistant,content:你},done:false}{model:llama3,created_at:...,message:{role:assistant,content:好},done:false}{model:llama3,created_at:...,done:true,total_duration:...}1.2 文本补全 (POST /api/generate)适用于单轮任务如续写、摘要不维护对话历史。请求体:{model:llama3,prompt:Once upon a time,stream:false,options:{temperature:0.7}}响应:{model:llama3,created_at:...,response:... there was a brave knight...,done:true,context:[123,456,...],// Token ID 序列可选total_duration:...,prompt_eval_count:5,eval_count:10}1.3 嵌入向量 (POST /api/embeddings)生成文本的向量表示用于 RAG、语义搜索等。请求体:{model:nomic-embed-text,prompt:这里是一段关于机器学习的文本。}响应:{embedding:[0.123,-0.456,0.789,...]// 向量数组}1.4 模型管理 API端点方法功能/api/tagsGET列出所有已下载模型/api/pullPOST下载模型/api/createPOST创建自定义模型/api/deleteDELETE删除模型/api/copyPOST复制模型/api/showPOST显示模型信息/api/psGET查看当前运行的模型2. 代码实现示例2.1 Python 实现使用requests库 (原生 HTTP):importrequestsimportjsondefchat_ollama(prompt,modelllama3,streamFalse):urlhttp://localhost:11434/api/chatpayload{model:model,messages:[{role:user,content:prompt}],stream:stream}ifstream:responserequests.post(url,jsonpayload,streamTrue)forlineinresponse.iter_lines():ifline:datajson.loads(line)ifmessageindataandcontentindata[message]:print(data[message][content],end,flushTrue)ifdata.get(done):print(\n生成完成)else:responserequests.post(url,jsonpayload)dataresponse.json()returndata[message][content]# 使用print(chat_ollama(用一句话介绍自己))使用ollama官方库:importollama# 简单对话responseollama.chat(modelllama3,messages[{role:user,content:Hello}])print(response[message][content])# 流式对话streamollama.chat(modelllama3,messages[{role:user,content:写一首诗}],streamTrue)forchunkinstream:print(chunk[message][content],end,flushTrue)2.2 JavaScript / Node.js 实现使用fetch(原生):asyncfunctionchatOllama(prompt){constresponseawaitfetch(http://localhost:11434/api/chat,{method:POST,headers:{Content-Type:application/json},body:JSON.stringify({model:llama3,messages:[{role:user,content:prompt}],stream:true})});constreaderresponse.body.getReader();constdecodernewTextDecoder();while(true){const{done,value}awaitreader.read();if(done)break;constchunkdecoder.decode(value);constlineschunk.split(\n);for(constlineoflines){if(line){constdataJSON.parse(line);if(data.message?.content){process.stdout.write(data.message.content);}}}}}chatOllama(Hello);使用ollama官方库:importollamafromollama;constresponseawaitollama.chat({model:llama3,messages:[{role:user,content:Hello}]});console.log(response.message.content);// 流式conststreamawaitollama.chat({model:llama3,messages:[{role:user,content:写故事}],stream:true});forawait(constpartofstream){process.stdout.write(part.message.content);}2.3 cURL 命令行非流式对话:curlhttp://localhost:11434/api/chat-d{ model: llama3, messages: [ {role: system, content: 你是一个助手}, {role: user, content: Hello} ], stream: false }流式对话:curlhttp://localhost:11434/api/chat-d{ model: llama3, messages: [{role: user, content: 写故事}], stream: true }下载模型:curlhttp://localhost:11434/api/pull-d{name: llama3}列出模型:curlhttp://localhost:11434/api/tags3. 高级用法3.1 多轮对话状态管理API 本身是无状态的需要客户端维护messages数组。importollama messages[{role:system,content:你是一个 Python 专家},{role:user,content:什么是列表推导式},]# 第一轮responseollama.chat(modelllama3,messagesmessages)replyresponse[message][content]print(fAI:{reply})# 将回复加入历史messages.append({role:assistant,content:reply})# 第二轮messages.append({role:user,content:能举个例子吗})responseollama.chat(modelllama3,messagesmessages)print(fAI:{response[message][content]})3.2 保持模型加载 (Keep Alive)默认情况下模型在 5 分钟无操作后会被卸载。可以通过keep_alive参数延长。importrequests responserequests.post(http://localhost:11434/api/chat,json{model:llama3,messages:[{role:user,content:Hello}],keep_alive:30m# 保持 30 分钟})3.3 自定义参数通过options字段调整模型行为。importollama responseollama.chat(modelllama3,messages[{role:user,content:写代码}],options{temperature:0.2,# 低随机性num_predict:500,# 限制长度top_p:0.9,repeat_penalty:1.2# 减少重复})3.4 多模态交互 (图像输入)支持llava等视觉模型。importollama responseollama.chat(modelllava,messages[{role:user,content:这张图片里有什么,images:[path/to/image.jpg]# 本地路径或 Base64}])print(response[message][content])3.5 使用 OpenAI SDK 兼容模式Ollama 的/v1端点兼容 OpenAI API 格式。fromopenaiimportOpenAI clientOpenAI(base_urlhttp://localhost:11434/v1,api_keyollama# 任意值)completionclient.chat.completions.create(modelllama3,messages[{role:user,content:Hello}],streamTrue)forchunkincompletion:ifchunk.choices[0].delta.content:print(chunk.choices[0].delta.content,end)4. 错误处理常见错误错误原因解决方案Connection refused服务未启动运行ollama serveModel not found模型未下载运行ollama pull model404 Not Found端点错误检查 URL 和 API 路径500 Internal Server Error模型加载失败检查显存/内存是否充足错误处理示例 (Python)importrequestsfromrequests.exceptionsimportConnectionError,HTTPErrortry:responserequests.post(http://localhost:11434/api/chat,json{model:llama3,messages:[{role:user,content:Hello}]})response.raise_for_status()print(response.json()[message][content])exceptConnectionError:print(错误Ollama 服务未启动)exceptHTTPErrorase:print(fHTTP 错误{e})exceptExceptionase:print(f未知错误{e})5. 性能优化建议流式输出: 设置stream: true提升用户体验。保持会话: 频繁调用时设置keep_alive避免重复加载模型。批量处理: 对于大量文本考虑使用num_predict限制单次输出长度。模型选择: 根据任务复杂度选择合适的模型如llama3:8b用于通用llama3:70b用于复杂推理。量化版本: 使用量化模型如q4_0减少内存占用。通过 Ollama API你可以轻松将本地大模型集成到 Web 应用、移动应用、自动化脚本等各种场景中。