FastAPI + Ollama AI 角色参数设定指南
环境准备
pip install fastapi ollama httpx
确保 Ollama 服务已启动并运行在 http://localhost:11434
。
基础集成
基本 FastAPI 应用
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.get("/query")
async def query_ollama(model: str, prompt: str):
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:11434/api/generate",
json={
"model": model,
"prompt": prompt
}
)
return {"result": response.json()["response"]}
带系统提示词的聊天接口
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.post("/chat")
async def chat_endpoint(request: dict):
model = request.get("model", "deepseek-chat")
messages = request.get("messages", [])
system_prompt = request.get("system_prompt", "你是一个专业的AI助手")
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:11434/api/chat",
json={
"model": model,
"system": system_prompt,
"messages": messages
}
)
return {"result": response.json()}
多轮对话示例
# 第一次对话
response = await client.post(
"http://localhost:11434/api/chat",
json={
"model": "deepseek-chat",
"system": "你是一个专业的AI助手",
"messages": [
{"role": "user", "content": "你好,请帮我回答一个问题"}
]
}
)
first_response = response.json()["response"]
# 第二次对话(包含历史)
response = await client.post(
"http://localhost:11434/api/chat",
json={
"model": "deepseek-chat",
"system": "你是一个专业的AI助手",
"messages": [
{"role": "user", "content": "你好,请帮我回答一个问题"},
{"role": "assistant", "content": first_response},
{"role": "user", "content": "请告诉我2024年的诺贝尔物理学奖获得者是谁"}
]
}
)
final_response = response.json()["response"]
角色参数示例
1. 专业 AI 助手
system_prompt = """
你是一个专业的AI助手,擅长使用互联网和工具来解决用户的问题。
你必须严格按照以下规则进行:
1. 先分析用户请求,确定是否需要使用工具
2. 如果需要使用工具,调用相应的工具
3. 如果不需要使用工具,直接回答用户的问题
4. 如果不确定如何回答,可以向用户请求更多信息
"""
2. 专业翻译员
system_prompt = """
你是一个专业的翻译员,擅长将英文翻译成指定的语言。
你需要按照以下步骤工作:
1. 首先确认用户需要将英文翻译成哪种语言
2. 然后将英文翻译成指定的语言
3. 如果翻译过程中遇到困难,可以向用户请求帮助
4. 最终提供翻译结果和原始英文文本
"""
3. 专业程序员
system_prompt = """
你是一个专业的程序员,擅长使用代码解决用户的问题。
你需要按照以下步骤工作:
1. 首先确认用户需要解决的问题
2. 然后提供解决该问题的代码
3. 如果代码中有错误,可以向用户解释并请求反馈
4. 最终提供完整的解决方案和解释
"""
使用模板引擎
基础模板示例
from string import Template
# 定义系统提示词模板
system_prompt_template = """
你是一个专业的{specialty},擅长{skills}。
你需要按照以下步骤工作:
1. {step1}
2. {step2}
3. {step3}
"""
# 渲染模板
system_prompt = Template(system_prompt_template).substitute(
specialty="AI助手",
skills="回答各种问题",
step1="分析用户请求",
step2="使用可用工具解决问题",
step3="提供清晰简洁的回答"
)
# 使用渲染后的提示词
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:11434/api/chat",
json={
"model": "deepseek-chat",
"system": system_prompt,
"messages": [{"role": "user", "content": "请帮我解决一个问题"}]
}
)
动态角色模板
from fastapi import FastAPI
from string import Template
app = FastAPI()
# 角色模板配置
ROLE_TEMPLATES = {
"programmer": {
"specialty": "程序员",
"skills": "编写和调试代码",
"step1": "理解需求",
"step2": "编写代码",
"step3": "测试和优化"
},
"translator": {
"specialty": "翻译员",
"skills": "中英文互译",
"step1": "理解原文",
"step2": "准确翻译",
"step3": "润色和校对"
},
"teacher": {
"specialty": "教师",
"skills": "知识讲解",
"step1": "分析问题",
"step2": "深入浅出讲解",
"step3": "总结和复习"
}
}
@app.post("/dynamic-role")
async def dynamic_role_chat(role: str, user_prompt: str):
if role not in ROLE_TEMPLATES:
raise HTTPException(status_code=400, detail="不支持的角色类型")
# 使用模板生成系统提示词
system_prompt = Template(system_prompt_template).substitute(
**ROLE_TEMPLATES[role]
)
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:11434/api/chat",
json={
"model": "deepseek-chat",
"system": system_prompt,
"messages": [{"role": "user", "content": user_prompt}]
}
)
return response.json()
使用示例
# 使用程序员角色
response = await client.post(
"/dynamic-role",
json={
"role": "programmer",
"user_prompt": "请帮我写一个冒泡排序算法"
}
)
# 使用翻译员角色
response = await client.post(
"/dynamic-role",
json={
"role": "translator",
"user_prompt": "请将这段代码注释翻译成中文"
}
)
# 使用教师角色
response = await client.post(
"/dynamic-role",
json={
"role": "teacher",
"user_prompt": "请解释什么是递归"
}
)
完整应用示例
from fastapi import FastAPI, HTTPException
import httpx
from typing import Dict, List, Optional
from pydantic import BaseModel
app = FastAPI()
class Message(BaseModel):
role: str # "user" 或 "assistant"
content: str
class ChatRequest(BaseModel):
model: str = "deepseek-chat"
system_prompt: str = "你是一个专业的AI助手"
user_prompt: str = "你好,请帮我回答一个问题"
messages: Optional[List[Message]] = None
@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
try:
ollama_messages = request.messages or []
ollama_messages.append({"role": "user", "content": request.user_prompt})
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:11434/api/chat",
json={
"model": request.model,
"system": request.system_prompt,
"messages": ollama_messages
}
)
if response.status_code != 200:
raise HTTPException(
status_code=response.status_code,
detail=f"Ollama API调用失败: {response.text}"
)
return response.json()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
API 使用说明
基本查询
- 端点:
GET /query
- 参数:
model
: 模型名称prompt
: 提示词
聊天接口
- 端点:
POST /chat
- 请求体:
{ "model": "deepseek-chat", "system_prompt": "你是一个专业的AI助手", "user_prompt": "用户输入的问题", "messages": [ {"role": "user", "content": "历史消息1"}, {"role": "assistant", "content": "历史回复1"} ] }