python测试ollama的API接口是否可用

python测试ollama的API接口是否可用

测试代码ollama_API_test.py

# ollama serve
# nohup ollama serve > ollama.log 2>&1 &
# ollama list
# ollama run llama3
# Use Ctrl + d or /bye to exit.

import ollama

modele_name = "llama3"
message = """
Why is the sky blue?
"""
response = ollama.chat(
    model=modele_name,
    messages=[{"role": "user", "content": message}],
    stream=False,  # 是否流式输出
)
print(
    "\n"
    + "-" * 30
    + "\n"
    + str(response["message"]["content"].strip("\n").strip())
    + "\n"
    + "-" * 30
    + "\n"
)
<think> 我们在之前的对话中已经讨论过使用Python调用Ollama模型的两种方式:1)使用ollama官方库(目前功能有限)进行阻塞和流式调用;2)使用requests库通过REST API调用。 根据用户当前需求“使用Python调用Ollama模型开发问答接口”,我们可以结合引用[2]和引用[3]的内容,提供两种实现方法:一种是使用ollama库(如果用户安装的是较新版本,可能已经支持),另一种是直接调用REST API(更通用)。 注意:用户要求开发的是“问答接口”,因此我们需要构建一个能够接收问题并返回答案的接口。我们可以分别展示两种方式,并说明如何封装成问答函数。 方法1:使用ollama库(需要先安装ollamaollama python包) 方法2:使用requests库调用API 我们将分别提供两种方法的代码示例,并解释其使用。 注意:在开始之前,请确保已经安装ollama并启动了服务(在终端运行`ollama serve`),同时下载了所需的模型(如`ollama pull qwen:7b`)。 由于用户问题中提到了“开发问答接口”,我们假设用户需要构建一个函数,输入问题,输出回答。 根据引用[2],使用ollama库进行流式和非流式调用的示例已经给出。我们可以将其封装成问答函数。 根据引用[3],使用requests调用API的方式也给出了非流式的示例,我们可以稍作修改使其更健壮。 下面我们分别实现: </think> ### Python调用Ollama模型开发问答接口的实现方法 开发问答接口主要可通过两种方式实现,下面详细介绍具体实现步骤: #### 方法1:使用官方Python库(推荐) ```python from ollama import chat # 需安装ollama库:pip install ollama def qa_interface(question: str, model: str = "llama3"): """ 问答接口函数 :param question: 用户问题 :param model: 使用的模型名称 :return: 完整的回答文本 """ response = chat( model=model, messages=[{'role': 'user', 'content': question}], stream=False # 非流式获取完整响应 ) return response['message']['content'] # 使用示例 answer = qa_interface("量子计算的基本原理是什么?") print(answer) ``` #### 方法2:通过REST API调用 ```python import requests def ollama_qa_api(question: str, model: str = "mistral", base_url: str = "http://localhost:11434"): """ REST API问答接口 :param question: 用户问题 :param model: 模型名称(默认mistral) :param base_url: Ollama服务地址 :return: 生成的回答 """ url = f"{base_url}/api/generate" payload = { "model": model, "prompt": question, "stream": False # 关闭流式传输 } try: response = requests.post(url, json=payload, timeout=120) response.raise_for_status() return response.json().get("response", "").strip() except Exception as e: return f"请求出错: {str(e)}" # 使用示例 response = ollama_qa_api("解释Transformer架构的核心思想") print(response) ``` #### 关键实现要点: 1. **模型选择**: - 常用模型:`llama3`, `mistral`, `qwen2`, `deepseek-r1`等 - 可通过`ollama list`查看本地可用模型 2. **参数配置**: - `temperature`:控制生成随机性(0.1-1.0) - `max_tokens`:限制响应长度 - `system`:添加系统级指令 3. **流式响应实现**(实时逐字输出): ```python # 流式问答接口 def streaming_qa(question): stream = chat( model="llama3", messages=[{'role': 'user', 'content': question}], stream=True ) for chunk in stream: print(chunk['message']['content'], end='', flush=True) ``` 4. **部署建议**: - 封装为FastAPI接口: ```python from fastapi import FastAPI app = FastAPI() @app.post("/ask") async def ask(question: str): return {"answer": qa_interface(question)} ``` - 使用uvicorn运行:`uvicorn main:app --reload --port 8000` #### 最佳实践建议: 1. 添加异常处理应对模型超时 2. 对长文本问题自动分段处理 3. 实现对话历史管理(传入`messages`列表) 4. 设置速率限制防止滥用接口 5. 使用`langchain-ollama`集成高级功能[^1][^2] > 注意:运行前需确保Ollama服务已启动(终端执行`ollama serve`),模型已下载(`ollama pull llama3`)[^1][^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值