2026/4/17 0:45:40
网站建设
项目流程
wordpress企业网站模板下载,cms系统都有哪些,宣传h5是什么意思,太原哪里做网站你是否遇到过这样的场景#xff1f;
想把 ChatGPT 接入自己的应用#xff0c;却被模型限制、价格波动、接口差异搞得一头雾水#xff1b;
刚写好的代码#xff0c;换一个模型就要重构一遍#xff1b;
好不容易跑通了#xff0c;又发现前端、后端、流式输出全都要重新适配…你是否遇到过这样的场景想把 ChatGPT 接入自己的应用却被模型限制、价格波动、接口差异搞得一头雾水刚写好的代码换一个模型就要重构一遍好不容易跑通了又发现前端、后端、流式输出全都要重新适配。现在这些问题可以用一个“中转 API”一次性解决。本教程将手把手带你使用神马中转API兼容 OpenAI Chat Completions 的中转 API通过 Python 快速部署一个可切换多模型的 ChatGPT 应用。无论你使用的是 OpenAI、Claude、Gemini、DeepSeek还是其他对话模型只需要 一个统一接口、一套请求格式就能完成调用。这套中转API是什么这套神马中转API接口兼容OpenAI 的 Chat Completions 格式你只需要在请求体里改 model就可以切换 OpenAI / Claude / Gemini / DeepSeek / Grok / Qwen 等模型。你给的接口是Chat(聊天)方法POST路径/v1/chat/completions准备工作Base URL 与 API Key文档说明BaseURL通常是神马中转API域名也可以在工作台页面查看API key在令牌页面获取你可以把它们放到环境变量里推荐export GPT_BEST_BASE_URL你的BaseURL例如https://api.whatai.cc export GPT_BEST_API_KEY你的API_KEY按文档拼请求Header BodyHeader文档示例里用的是Accept: application/jsonAuthorization: Bearer {{YOUR_API_KEY}}Content-Type: application/jsonBody请求体application/json文档示例包含这些字段model、messages、temperature、top_p、n、stream、stop、max_tokens、presence_penalty、frequency_penalty、logit_bias、user、response_format、seen、tools、tool_choice。最小可用通常是 model messages其他按需加。Python同步请求示例requestsimport os import requests BASE_URL os.getenv(GPT_BEST_BASE_URL) # 你的 BaseURLhttps://api.whatai.cc) API_KEY os.getenv(GPT_BEST_API_KEY) if not BASE_URL or not API_KEY: raise RuntimeError(请先设置 GPT_BEST_BASE_URL 和 GPT_BEST_API_KEY 环境变量) url f{BASE_URL.rstrip(/)}/v1/chat/completions # 接口路径 headers { Accept: application/json, Authorization: fBearer {API_KEY}, # Bearer 方式 Content-Type: application/json, } payload { model: gpt-4o-mini, # 按需替换成你要用的模型名 messages: [ {role: system, content: 你是一个严谨的编程助手。}, {role: user, content: 用Python写一个快速排序并解释时间复杂度。}, ], temperature: 0.7, top_p: 1, n: 1, stream: False, # 非流式 max_tokens: 800, } resp requests.post(url, headersheaders, jsonpayload, timeout60) resp.raise_for_status() data resp.json() # 返回格式示例choices[0].message.content print(data[choices][0][message][content]) print(usage:, data.get(usage))Python流式输出示例streamtrue文档请求体里有 stream: true 字段示例。流式一般是服务端不断返回分片常见是 SSEdata: ...。import os import json import requests BASE_URL os.getenv(GPT_BEST_BASE_URL) API_KEY os.getenv(GPT_BEST_API_KEY) url f{BASE_URL.rstrip(/)}/v1/chat/completions headers { Accept: application/json, Authorization: fBearer {API_KEY}, Content-Type: application/json, } payload { model: gpt-4o-mini, messages: [ {role: user, content: 请用三句话解释什么是递归并给一个Python例子。} ], stream: True, # 流式 temperature: 0.6, } with requests.post(url, headersheaders, jsonpayload, streamTrue, timeout60) as r: r.raise_for_status() for line in r.iter_lines(decode_unicodeTrue): if not line: continue # 常见 SSE 行data: {...} 或 data: [DONE] if line.startswith(data:): line line[len(data:):].strip() if line [DONE]: break try: chunk json.loads(line) except json.JSONDecodeError: # 如果服务端不是 SSE 格式而是纯JSON片段可在这里按需兼容 continue # OpenAI 风格流式choices[0].delta.content delta chunk.get(choices, [{}])[0].get(delta, {}) content delta.get(content) if content: print(content, end, flushTrue) print() # 换行“部署一个 ChatGPT 应用”的最小后端FastAPI转发可选这个小服务做两件事接收你自己的前端请求转发到中转 API 的 /v1/chat/completions仍然保持文档要求的 Header/Body 结构import os import requests from fastapi import FastAPI, HTTPException from pydantic import BaseModel BASE_URL os.getenv(GPT_BEST_BASE_URL) API_KEY os.getenv(GPT_BEST_API_KEY) app FastAPI() class ChatReq(BaseModel): model: str messages: list temperature: float | None None top_p: float | None None n: int | None None stream: bool | None None stop: str | None None max_tokens: int | None None presence_penalty: float | None None frequency_penalty: float | None None logit_bias: dict | None None user: str | None None response_format: dict | None None seen: int | None None tools: list | None None tool_choice: dict | None None app.post(/chat) def chat(req: ChatReq): if not BASE_URL or not API_KEY: raise HTTPException(status_code500, detailMissing GPT_BEST_BASE_URL / GPT_BEST_API_KEY) url f{BASE_URL.rstrip(/)}/v1/chat/completions # headers { Accept: application/json, Authorization: fBearer {API_KEY}, # Content-Type: application/json, } resp requests.post(url, headersheaders, jsonreq.model_dump(exclude_noneTrue), timeout60) if resp.status_code ! 200: raise HTTPException(status_coderesp.status_code, detailresp.text) return resp.json()启动示例uvicorn your_file_name:app --host 0.0.0.0 --port 8000返回结果怎么看文档给的返回示例结构是choices: 数组choices[0].message.role/contentusage.prompt_tokens / completion_tokens / total_tokens你在 Python 里通常取data[choices][0][message][content]