共计 2288 个字符,预计需要花费 6 分钟才能阅读完成。
ChatGPT 插件让 AI 能力突破对话边界,通过扩展工具集实现场景定制,同时为开发者开辟了商业变现新路径。本文将手把手带你完成一个天气查询插件的开发全流程。

一、插件架构核心原理
-
通信机制图解
graph LR User-->ChatGPT ChatGPT-->Plugin[插件服务端] Plugin-->ExternalAPI[第三方天气 API]用户请求经过 ChatGPT 主模型解析后,通过 OpenAPI 规范调用插件服务,最终获取外部数据源返回结果。
-
OpenAPI 映射关键点
- 接口路径对应
paths.weather.get - 参数描述转换为自然语言:” 城市名参数需要完整的行政区划名称 ”
-
响应示例必须包含结构化数据字段说明
-
CORS 必配头部示例
@app.middleware("http") async def add_cors_headers(request, call_next): response = await call_next(request) response.headers.update({ "Access-Control-Allow-Origin": "https://chat.openai.com", "Access-Control-Allow-Methods": "GET,POST", "Access-Control-Allow-Headers": "Authorization" }) return response
二、实战开发步骤
-
OAuth2.0 鉴权实现
from fastapi import Depends, HTTPException from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/weather") async def get_weather( city: str, token: str = Depends(oauth2_scheme) ): try: # 添加重试逻辑 for attempt in range(3): try: data = await fetch_weather_api(city, token) return {"temperature": data["temp"], "unit": "Celsius"} except TimeoutError: if attempt == 2: raise await asyncio.sleep(1) except InvalidTokenError: raise HTTPException(status_code=401, detail="Invalid API key") -
插件清单关键配置
{ "schema_version": "v1", "name_for_human": "天气小助手", "description_for_model": "当用户询问天气或气候信息时,你需要调用此插件。输入参数必须包含明确的城市名称,输出包含温度(单位:摄氏度)和天气状况。", "auth": { "type": "oauth", "client_url": "https://yourdomain.com/oauth" }, "api": { "type": "openapi", "url": "https://yourdomain.com/openapi.json" } } description_for_model需明确触发条件和参数要求- 认证配置需要与后端实现严格匹配
三、性能优化方案
-
异步任务处理对比
-
Webhook 模式:
@app.post("/long-task") async def create_task(): task_id = start_async_processing() return {"status": "pending", "callback_url": f"/results/{task_id}"} - Polling 模式:
@app.get("/task-status/{task_id}") async def check_status(task_id: str): return {"status": get_progress(task_id)} -
选择建议:短任务用 Polling,超过 30 秒任务推荐 Webhook
-
上下文节省技巧
- 使用
summary字段替代完整历史记录 - 对长文本响应启用
truncate_middle选项 - 设置合理的
max_tokens限制
四、问题排查指南
-
认证失效三大场景
-
检查
ai-plugin.json中的auth.client_url是否包含 HTTPS - 验证 OAuth2.0 的
redirect_uri与 ChatGPT 控制台配置完全一致 -
确认 Access Token 未过期(标准有效期 2 小时)
-
Postman 调试技巧
-
创建新 Collection 时添加 Header:
Authorization: Bearer [测试 Token] Origin: https://chat.openai.com - 使用 Tests 脚本自动验证响应格式
- 开启 Console Log 查看原始请求头
五、开发经验总结
在实际开发过程中,有三个关键点需要注意:首先是 description_for_model 的编写要尽可能具体,这直接影响 ChatGPT 调用插件的准确性;其次是错误处理要包含重试机制,特别是对第三方 API 的调用;最后建议在本地先通过 Postman 完整测试所有接口,再部署到生产环境。
下一步可以尝试为插件添加多语言支持,或结合用户历史查询数据提供个性化天气建议。完整的示例代码已上传到 GitHub 仓库(虚构链接),欢迎开发者们一起交流改进。
正文完
