LLM 工具调用框架:GPT Plugin

一、GPT Plugin

GPT Plugin(OpenAI 插件) 是目前最成熟的“LLM 工具调用”框架之一,由 OpenAI 官方于 2023 年推出,在 GPT-4 模型中广泛应用,目标是让 LLM 不再只是“聊天”,而是能主动调用工具、读取数据、执行任务

GPT Plugin 是什么?

GPT Plugin 是一种插件机制,它让 ChatGPT 模型可以通过 自然语言 调用外部服务或工具。
核心原理是通过描述性 API 接口规范,让模型理解如何调用你的服务。

核心工作机制(技术流程)

GPT Plugin 的工作流程如下:

+-------------+         +-----------------+          +--------------------+
| 用户提问     | --->    | GPT-4 模型(理解+规划)| --->   | 插件 API Server(你写的服务) |
+-------------+         +-----------------+          +--------------------+
                               ↑                                     |
                    插件 Manifest + OpenAPI Spec           返回 JSON 结果

关键组件:

组件说明
plugin manifest (ai-plugin.json)描述插件的名称、用途、图标、身份认证方式等
OpenAPI 规范 (openapi.yaml)精确描述你的 API 接口,让模型能“看懂怎么调用”
API 服务端提供你想暴露给模型的功能接口,如查天气、查数据库、发微信等
ChatGPT 插件系统在对话中识别用户需求 → 选择插件 → 自动调用 → 回复用户

开发流程概览

1.准备 API 服务

  • 比如你写一个 /weather?city=Tokyo 的接口返回天气数据

2.写 openapi.yaml 文件

  • 描述 /weather 接口、参数类型、返回值结构

3.写 ai-plugin.json 文件

  • 告诉 ChatGPT 你这个插件叫什么、干什么、logo、认证方式

4.部署并托管你的插件

  • 需要 HTTPS,推荐用 vercel、railway、cloudflare、ngrok 或自建 nginx

5.在 GPT 中注册

  • 用户进入 ChatGPT(GPT Plus),打开插件模式,点击“插件商店” → “开发者插件” → 输入你的域名注册

插件 Manifest 示例(ai-plugin.json)

{
  "schema_version": "v1",
  "name_for_human": "Weather Plugin",
  "name_for_model": "weather",
  "description_for_model": "Get current weather for any city",
  "auth": {
    "type": "none"
  },
  "api": {
    "type": "openapi",
    "url": "https://yourdomain.com/openapi.yaml"
  },
  "logo_url": "https://yourdomain.com/logo.png",
  "contact_email": "you@example.com",
  "legal_info_url": "https://yourdomain.com/legal"
}

优势

优点说明
与 GPT 原生深度集成模型可自动理解并调用,无需手动填参数
支持自然语言调用用户只需“说人话”,模型负责调用插件
标准化接口规范使用 OpenAPI 描述,易于对接现有系统
支持多种认证方式无认证、API Key、OAuth2 皆可支持
可访问外部 Web、数据库、代码执行等能力类似小程序,扩展 ChatGPT 的能力边界

局限与前提

限制说明
GPT Plugin 仅支持 ChatGPT Plus 用户(GPT-4 模式)使用
目前只能在浏览器端注册和使用插件(不适用于 API 调用)
插件调用频率有限(OpenAI 有节流策略)
安全责任完全由开发者承担(你的 API 被模型调用)

实战场景

场景示例
企业插件查库存、查订单、创建流程、审批请求等
教育插件课程推荐、试题查询、题库调用
数据查询财务系统查询、表格分析、数据透视等
个人工具记账、日历提醒、聊天记录整理

是否适合你?

情况建议
你面向 ChatGPT Plus 用户非常推荐,插件是最官方、最原生的 LLM 接入方式
你做私有化部署或自有模型建议选 LangChain、OpenMCP、Open Interpreter 等方案
你不确定需求可先用 mock server 测试 GPT Plugin 的交互感受

延伸资料

二、GPT Plugin 模板

# GPT Plugin Template Project (Python FastAPI)

from fastapi import FastAPI, Query
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware

app = FastAPI(title="BAW Plugin", version="0.1.0")

# Enable CORS for GPT plugin host
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/baw/process-status")
def get_process_status(process_id: str = Query(..., description="BAW process instance ID")):
    # Stub logic: replace with real API call to BAW
    return {
        "process_id": process_id,
        "status": "In Progress",
        "last_updated": "2025-06-24T10:00:00Z"
    }

@app.get("/.well-known/ai-plugin.json")
def serve_manifest():
    return JSONResponse({
        "schema_version": "v1",
        "name_for_human": "BAW Plugin",
        "name_for_model": "baw",
        "description_for_model": "Plugin to query BAW workflow process status by process ID.",
        "auth": {"type": "none"},
        "api": {
            "type": "openapi",
            "url": "https://yourdomain.com/openapi.json"
        },
        "logo_url": "https://yourdomain.com/logo.png",
        "contact_email": "you@example.com",
        "legal_info_url": "https://yourdomain.com/legal"
    })

@app.get("/openapi.json")
def custom_openapi():
    return JSONResponse(get_openapi(
        title=app.title,
        version=app.version,
        routes=app.routes
    ))

下面是一个基础的 GPT Plugin 模板项目(使用 Python + FastAPI),功能是根据传入的 process_id 查询一个 IBM BAW 流程的状态(目前是模拟数据,下一步我们将替换为真实接口调用):

项目结构

 

📦 gpt-baw-plugin/
 ┣ 📄 main.py                ← 主程序文件
 ┣ 📄 openapi.json           ← OpenAPI schema(自动生成)
 ┣ 📄 .well-known/
 ┃   ┗ 📄 ai-plugin.json     ← 插件 manifest 描述

当前功能

  • /baw/process-status:GET 接口,接收 process_id 参数,返回流程状态(模拟数据)

  • /.well-known/ai-plugin.json:GPT 插件所需的 Manifest 文件

  • /openapi.json:提供 OpenAPI 描述,让模型能理解接口怎么调用

三、GPT Plugin扩展

将当前的 GPT Plugin 模板项目扩展为一个支持 OAuth 并调用真实 BAW 流程状态接口的插件。

目标功能:

GPT 插件通过 /baw/process-status?process_id=xxx 请求 →
调用 BAW 的 /rest/bpm/wle/v1/process/{id} API →
获取并返回流程状态(如 InProgress, Completed, Failed)

IBM BAW OAuth 认证概览

IBM BAW 的 OAuth 认证通常包括以下步骤:

1.获取 access token
例如通过如下接口:

POST https://<baw_host>/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
client_id=<client_id>
client_secret=<client_secret>

2.调用 BAW REST API 时,在请求头中添加:

Authorization: Bearer <access_token>

修改方向

  1. 添加获取 access token 的函数

  2. 使用 access token 请求 BAW /process/{id} 接口

  3. 将结果返回给 GPT 插件请求方

以下关键信息(可模拟,也可之后替换):

参数示例值是否需要你确认
BAW 主机地址https://baw.example.com
OAuth token URL/oauth2/token
client_idbaw_plugin_client
client_secret**********
BAW API URL/rest/bpm/wle/v1/process/{id}
是否使用 self-signed 证书?是/否

 修改之后的代码:

# GPT Plugin Project (FastAPI + OAuth2 IBM BAW Integration)

from fastapi import FastAPI, Query
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware
import requests
import os

app = FastAPI(title="BAW Plugin", version="0.1.1")

# Enable CORS for GPT plugin host
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Simulated BAW OAuth Config (replace with real values)
BAW_HOST = "https://baw.example.com"
OAUTH_TOKEN_URL = f"{BAW_HOST}/oauth2/token"
CLIENT_ID = "baw_plugin_client"
CLIENT_SECRET = "baw_plugin_secret"
BAW_PROCESS_URL = f"{BAW_HOST}/rest/bpm/wle/v1/process"


def get_baw_access_token():
    payload = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
    }
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    response = requests.post(OAUTH_TOKEN_URL, data=payload, headers=headers, verify=False)
    if response.status_code == 200:
        return response.json().get("access_token")
    else:
        raise Exception(f"Failed to get access token: {response.text}")


@app.get("/baw/process-status")
def get_process_status(process_id: str = Query(..., description="BAW process instance ID")):
    try:
        token = get_baw_access_token()
        headers = {"Authorization": f"Bearer {token}"}
        baw_url = f"{BAW_PROCESS_URL}/{process_id}"
        resp = requests.get(baw_url, headers=headers, verify=False)

        if resp.status_code == 200:
            data = resp.json()
            return {
                "process_id": process_id,
                "status": data.get("status", "Unknown"),
                "last_updated": data.get("lastModifiedTime", "N/A")
            }
        else:
            return {"error": f"Failed to retrieve process. Status {resp.status_code}"}
    except Exception as e:
        return {"error": str(e)}


@app.get("/.well-known/ai-plugin.json")
def serve_manifest():
    return JSONResponse({
        "schema_version": "v1",
        "name_for_human": "BAW Plugin",
        "name_for_model": "baw",
        "description_for_model": "Query IBM BAW process status using process ID.",
        "auth": {"type": "none"},
        "api": {
            "type": "openapi",
            "url": "https://yourdomain.com/openapi.json"
        },
        "logo_url": "https://yourdomain.com/logo.png",
        "contact_email": "you@example.com",
        "legal_info_url": "https://yourdomain.com/legal"
    })


@app.get("/openapi.json")
def custom_openapi():
    return JSONResponse(get_openapi(
        title=app.title,
        version=app.version,
        routes=app.routes
    ))

以上代码已将项目更新为带模拟 OAuth 认证集成的 GPT 插件版本,关键点如下:

OAuth 接入逻辑

  • 模拟配置参数位于代码顶部(你需用实际值替换):

BAW_HOST = "https://baw.example.com"
OAUTH_TOKEN_URL = f"{BAW_HOST}/oauth2/token"
CLIENT_ID = "baw_plugin_client"
CLIENT_SECRET = "baw_plugin_secret"
  • 使用 client_credentials 模式获取 access token

  • /baw/process-status?process_id=xxx 调用中使用该 token 请求 IBM BAW 流程 API

安全注意事项

  • 当前示例中 verify=False 跳过了 SSL 验证,请不要在生产环境中使用

  • 建议你部署前准备:

    • 有效的 CA 证书或将 BAW 证书导入信任链

    • CLIENT_SECRET 等信息用环境变量读取

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深海科技服务

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值