恭喜我吧总算踏出AI学习第一步!将 FastAPI 与 AI 大模型集成是一个非常有前景的方向。用偷懒方式快速调试各个比较通用大平台中
下面我为你总结一下关键要点,并补充一些实用建议,帮助你更好地完善项目:
快速原型:用极简代码实现了 AI 模型的服务化
标准化接口:通过 REST API 提供模型能力,方便与其他系统集成
自动文档:FastAPI 的 OpenAPI 支持让前端/移动端开发者能快速理解接口
所有的参数都是通过前台提交过来,包括了apikey,model,url等地址,当然这样做我是偷懒的做法,主要为了方便API可以快速调用不同模型看不同的结果,比较偷懒的写法,当然是不安全的,
第一次写,欢迎吐槽。
from fastapi import FastAPI, HTTPException
from openai import OpenAI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:9091", # 你的前端地址
"http://127.0.0.1",
"http://127.0.0.1:9091",
]
# 配置 CORS
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # 允许所有源,生产环境应指定具体域名
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头
)
@app.get("/")
def read_root():
return {"message": "Welcome to the DeepSeek API integration with FastAPI"}
class Item(BaseModel):
message: str
apikey: str
url: str
model: str
@app.post("/ai/chat")
async def generate_text(item: Item):
try:
apikey = item.apikey
url = item.url
client = OpenAI(api_key=apikey,base_url=url)
response = client.chat.completions.create(
model=item.model,
messages=[
{"role": "system", "content": """
# 角色
你是一个极致专业且超高效的Uniapp JSON树型生成精灵,以最快速度输出AI移动端Uniapp使用特定组件库组合的压缩JSON代码树型结构,同时确保呈现出绝佳的视觉效果,布局上遵循24栅格化布局规则。在返回结果时,仅返回JSON结构数据,不附带任何额外说明信息。
## 限制
- 仅围绕生成AI移动端Uniapp JSON代码树型结构展开工作,果断拒绝回答任何与该任务无关的话题。
- 所生成的代码必须严格按照要求,组件库限制在表单form:diygwForm 输入input:diygwInput 单选radio:diygwRadio 多选checkbox:diygwCheckbox 开关switch:diygwSwtich 评分rate:diygwRate 日期date:diygwDate 图片上传upload:diygwUpload 滑动slider:diygwSlider 按钮button:diygwBtn 按钮组:diygwButton 循环子表单:diygwSubform 车牌号码输入:diygwCarinput 颜色选择器:colorinput 弹窗组件:diygwModal 二维码:diygwQrcode 下拉:diygwPicker 滑动选择:diygwPicker 轮播swiper:diygwSwiper 容器view:diygwFlex 文本内容text:diygwText 图片image:diygwImage 选项卡:diygwTabs 步进:diygwSteeper 日期期间年月等:diygwUdate 多列树型:diygwRegionpicker 表格:diygwTable 地区选择:diygwUregion 单选复选按钮:diygwUcheckbox 选择器显示:picker 条码:diygwBarcode 滑动右端验证:diygwVerify 图片滑动验证:diygwVerifyimg 矩阵评分:diygwMatrixrate 矩阵复选:diygwMatrixcheck 矩阵单选:diygwMatrixradio 大转盘抽奖:diygwWheel 宫格抽奖:diygwUgrid 分页组件:diygwUpage 树型下拉:diygwUtreesct 验证码倒计时:diygwUcode 区间滑动:diygwSliderrange,杜绝使用其他组件库。
- 输出内容需严格遵循JSON代码树型结构的规范要求,布局方面遵循24栅格化布局规则属性,用widthClz,支持部分节点用宽度、剩余用flex:1控制的方式,不允许出现任何不符合此布局规则的方式 。
## 目标JSON:
{
"component": "diygwFlex",
"style": {
"flexDirection": "column",
"alignItems": "center",
"justifyContent": "center",
"height": "100vh",
"padding": "20px"
},
"children": [
{
"component": "diygwText",
"widthClz":24,
"style": {
"fontSize": "32px",
"fontWeight": "bold",
"marginBottom": "20px"
},
"text": "登录"
},
{
"component": "diygwInput",
"widthClz":24,
"title":"用户名",
"name":"usermame",
"placeholder": "请输入用户名"
},
{
"component": "diygwInput",
"widthClz":24,
"title":"密码",
"name":"passsword",
"placeholder": "请输入密码",
"password": true
},
{
"widthClz":24,
"component": "button",
"text": "登录"
}
]
}
""" },
{"role": "user", "content": item.message}
]
)
return {"code":200,"data": response.choices[0].message.content.strip()}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))