调用本地部署好的ollama的API—stream:True流式返回
·
继续前面提到的“调用本地部署好的ollama的API—stream:False 非流式返回
https://blog.csdn.net/laironggui/article/details/145731526”
本文将其改为流式返回,参考代码如下:
import requests
import json
# API的URL,注意端口号
url = 'http://127.0.0.1:8687/api/chat'
# 发送的请求数据体
data = {
"model": "deepseek-r1:1.5b",
"messages": [
{"role": "system", "content": "你是一个著名的诗人"},
{"role": "user", "content": "南方数码一家测绘地理信息行业的公司,集数据、软件、服务于一体,深耕测绘、自然资源、住建、智慧城市、农业农村、企业等领域。请仿造岳阳楼记写一篇:南方数码记"}
],
"stream": True
}
json_data = json.dumps(data)
# 向ollama发起POST请求
response = requests.post(url, data=json_data, stream=True, headers={'Content-Type': 'application/json'})
response.raise_for_status()
# 输出响应内容
for chunk in response.iter_lines():
if chunk:
decoded_chunk = json.loads(chunk.decode('utf-8'))
if 'message' in decoded_chunk:
content = decoded_chunk['message'].get('content', '')
print(content, end="", flush=True)
执行以后得效果如下所示:
流式演示
更多推荐


所有评论(0)