假设机器已经安装ollama工具,并且已经下载好了ollama模型。

这里我们使用qwen3:8b模型。

1 pip安装ollama库

pip install ollama  -i https://pypi.tuna.tsinghua.edu.cn/simple

2 运行ollama示例程序

1)阻塞式调用

from ollama import chat
from ollama import ChatResponse
response: ChatResponse = chat(model='qwen3:8b', messages=[
  {
    'role': 'user',
    'content': '新疆的美食有哪些?,请将输出控制在100个字以内。',
  },
])
print(response['message']['content'])
print(response.message.content)

2)流式调用

from ollama import chat
from ollama import ChatResponse

stream = chat(
    model='qwen3:8b',
    messages=[{'role': 'user', 'content': '新疆的美食有哪些?,请将输出控制在100个字以内。'}],
    stream=True,
)

for chunk in stream:
  print(chunk['message']['content'], end='', flush=True)

reference

----

ollama qwen3

https://ollama.com/library/qwen3

ollama-python

https://github.com/ollama/ollama-python

Logo

免费领 200 小时云算力,进群参与显卡、AI PC 幸运抽奖

更多推荐