更新 README.md、manifest.json、openapi.json、plugin.json 文件,将插件重构为基于 Cloudflare Workers AI 的图像生成插件,修改设置步骤、认证方式和限制信息,更新 API 参数和描述以支持图像生成。
This commit is contained in:
parent
195f6873c8
commit
14baccffa2
73
README.md
73
README.md
|
@ -1,41 +1,66 @@
|
|||
# LobeChat Google Custom Search Plugin
|
||||
# LobeChat Cloudflare Workers AI Image Generation Plugin
|
||||
|
||||
A LobeChat search plugin that uses the [Google Custom Search API](https://developers.google.com/custom-search).
|
||||
This is a LobeChat plugin that generates high-quality images using the `@cf/black-forest-labs/flux-1-schnell` model from [Cloudflare Workers AI](https://developers.cloudflare.com/workers-ai/).
|
||||
|
||||
## Features
|
||||
|
||||
- Generate high-quality images using Cloudflare's Flux-1-Schnell model
|
||||
- Request proxying through Cloudflare Worker for simplified authentication
|
||||
- Generate and view images directly in LobeChat conversations
|
||||
|
||||
## Setup Steps
|
||||
|
||||
1. Create a Google Custom Search Engine
|
||||
- Visit [Google Programmable Search Engine](https://programmablesearch.google.com/create)
|
||||
- Create a custom search engine
|
||||
- Get your search engine ID (cx parameter)
|
||||
1. Set up Cloudflare Worker
|
||||
- Deploy the provided Worker code to Cloudflare Workers
|
||||
- Configure the following environment variables (Secrets) in your Worker settings:
|
||||
- `WORKER_API_KEY`: Set a secure API key for client authentication
|
||||
- `CLOUDFLARE_API_TOKEN`: Your Cloudflare API token
|
||||
- `CLOUDFLARE_ACCOUNT_ID`: Your Cloudflare account ID
|
||||
|
||||
2. Get Google API Key
|
||||
- Visit [Google Cloud Console](https://console.cloud.google.com/)
|
||||
- Create a project
|
||||
- Enable "Custom Search API"
|
||||
- Create an API key (key parameter)
|
||||
|
||||
3. Configure the Plugin in LobeChat
|
||||
2. Configure the plugin in LobeChat
|
||||
- Add this plugin to LobeChat
|
||||
- Provide your API key and search engine ID in the configuration page
|
||||
- These credentials will be automatically added to each request as secure parameters
|
||||
- In the configuration page:
|
||||
- Configure your Worker API key as `WORKER_API_KEY`
|
||||
- Ensure the Worker URL is correctly configured
|
||||
|
||||
## Authentication Method
|
||||
## Authentication and Parameters
|
||||
|
||||
This plugin uses the following two secure parameters:
|
||||
- `key`: Your Google API key
|
||||
- `cx`: Your custom search engine ID
|
||||
This plugin uses the following configuration to access your Cloudflare Worker:
|
||||
- Worker API key: Used as the X-Api-Key request header
|
||||
- You only need to provide the image description (prompt) when using this plugin
|
||||
- The Worker automatically calls the Cloudflare AI API using the configured credentials
|
||||
|
||||
These two parameters are added as query parameters to the API request.
|
||||
## Usage Instructions
|
||||
|
||||
1. In the chat, request to generate an image, for example:
|
||||
- "Draw a cat standing on a mountain top"
|
||||
- "Generate a beach sunset landscape"
|
||||
|
||||
2. Supported parameters:
|
||||
- prompt: Image description (required, maximum 2048 characters)
|
||||
- steps: Number of diffusion steps (optional, default 4, maximum 8)
|
||||
|
||||
Example: "Generate an image of an astronaut riding a horse, using 8 diffusion steps"
|
||||
|
||||
## API Format Example
|
||||
|
||||
```bash
|
||||
curl https://schnell-worker.foryoung365.workers.dev \
|
||||
-X POST \
|
||||
-H "X-Api-Key: <YOUR_WORKER_API_KEY>" \
|
||||
-d '{ "prompt": "cyberpunk cat", "steps": 8 }'
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
- Google Custom Search API free version is limited to 100 queries per day
|
||||
- Paid version provides more quota
|
||||
- There may be usage limitations based on your Cloudflare account type
|
||||
- The Flux-1-Schnell model has its own capability range; not all prompts will produce ideal results
|
||||
- Higher diffusion steps take longer to generate but may produce higher quality
|
||||
|
||||
## Privacy
|
||||
|
||||
- Your search queries will be sent to Google
|
||||
- Your prompt text is sent to the Cloudflare AI API through the Worker
|
||||
- This plugin does not collect or store your personal data
|
||||
- Generated images are returned directly to your browser through the Worker
|
||||
|
||||
`(Not affiliated with any of the above entities)`
|
||||
`(Not affiliated with any of the above entities)`
|
||||
|
|
75
README_CN.md
75
README_CN.md
|
@ -1,41 +1,66 @@
|
|||
# LobeChat Google Custom Search 插件
|
||||
# LobeChat Cloudflare Workers AI 图像生成插件
|
||||
|
||||
使用 [Google Custom Search API](https://developers.google.com/custom-search) 的LobeChat搜索插件。
|
||||
这是一个LobeChat插件,使用[Cloudflare Workers AI](https://developers.cloudflare.com/workers-ai/)的`@cf/black-forest-labs/flux-1-schnell`模型生成高质量图像。
|
||||
|
||||
## 功能特点
|
||||
|
||||
- 使用Cloudflare的Flux-1-Schnell模型生成高质量图像
|
||||
- 通过Cloudflare Worker代理请求,简化认证过程
|
||||
- 直接在LobeChat对话中生成和查看图像
|
||||
|
||||
## 设置步骤
|
||||
|
||||
1. 创建 Google Custom Search Engine
|
||||
- 访问 [Google Programmable Search Engine](https://programmablesearch.google.com/create)
|
||||
- 创建一个自定义搜索引擎
|
||||
- 获取您的搜索引擎ID (cx参数)
|
||||
1. 设置Cloudflare Worker
|
||||
- 将提供的Worker代码部署到Cloudflare Workers
|
||||
- 在Worker设置中配置以下环境变量(Secrets):
|
||||
- `WORKER_API_KEY`: 设置一个安全的API密钥,用于客户端认证
|
||||
- `CLOUDFLARE_API_TOKEN`: 你的Cloudflare API令牌
|
||||
- `CLOUDFLARE_ACCOUNT_ID`: 你的Cloudflare账户ID
|
||||
|
||||
2. 获取 Google API 密钥
|
||||
- 访问 [Google Cloud Console](https://console.cloud.google.com/)
|
||||
- 创建一个项目
|
||||
- 启用 "Custom Search API"
|
||||
- 创建API密钥 (key参数)
|
||||
|
||||
3. 在LobeChat中配置插件
|
||||
2. 在LobeChat中配置插件
|
||||
- 将此插件添加到LobeChat
|
||||
- 在配置页面中提供您的API密钥和搜索引擎ID
|
||||
- 这些凭据会作为安全参数自动添加到每个请求中
|
||||
- 在配置页面中:
|
||||
- 将你的Worker API密钥配置为`WORKER_API_KEY`
|
||||
- 确保Worker URL配置正确
|
||||
|
||||
## 认证方式
|
||||
## 身份验证和参数
|
||||
|
||||
此插件使用以下两个安全参数:
|
||||
- `key`: 您的Google API密钥
|
||||
- `cx`: 您的自定义搜索引擎ID
|
||||
此插件使用以下配置访问你的Cloudflare Worker:
|
||||
- Worker API密钥:用作X-Api-Key请求头
|
||||
- 每次使用此插件时,你只需要提供图像描述(prompt)
|
||||
- Worker会自动使用配置的凭证调用Cloudflare AI API
|
||||
|
||||
这两个参数会作为查询参数添加到API请求中。
|
||||
## 使用说明
|
||||
|
||||
1. 在聊天中,请求生成图像,例如:
|
||||
- "画一只站在山顶上的猫"
|
||||
- "生成一幅海滩日落的风景画"
|
||||
|
||||
2. 支持的参数:
|
||||
- prompt:图像描述(必需,最大2048字符)
|
||||
- steps:扩散步骤数(可选,默认4,最大8)
|
||||
|
||||
例如:"生成一幅宇航员骑马的图像,使用8个扩散步骤"
|
||||
|
||||
## API格式示例
|
||||
|
||||
```bash
|
||||
curl https://[your-worker-name].[your-account-name].workers.dev \
|
||||
-X POST \
|
||||
-H "X-Api-Key: <YOUR_WORKER_API_KEY>" \
|
||||
-d '{ "prompt": "cyberpunk cat", "steps": 8 }'
|
||||
```
|
||||
|
||||
## 限制
|
||||
|
||||
- Google Custom Search API 免费版每天限制100次查询
|
||||
- 付费版可获得更多配额
|
||||
- 根据你的Cloudflare账户类型,可能有使用限制
|
||||
- Flux-1-Schnell模型有自己的能力范围,不是所有提示都能产生理想结果
|
||||
- 扩散步骤数越大,生成时间越长,但质量可能更高
|
||||
|
||||
## 隐私
|
||||
|
||||
- 您的搜索查询将发送到Google
|
||||
- 此插件不会收集或存储您的个人数据
|
||||
- 你的提示文本将通过Worker发送到Cloudflare AI API
|
||||
- 此插件不会收集或存储你的个人数据
|
||||
- 生成的图像通过Worker直接返回给你的浏览器
|
||||
|
||||
`(与上述任何实体无关联)`
|
||||
`(与上述任何实体均无关联)`
|
||||
|
|
|
@ -1,19 +1,20 @@
|
|||
{
|
||||
"api": {
|
||||
"type": "openapi",
|
||||
"url": "https://raw.githubusercontent.com/foryoung365/lobechat-plugin-google/main/public/openapi.json",
|
||||
"url": "https://raw.githubusercontent.com/foryoung365/lobechat-plugin-workers-schnell/main/public/openapi.json",
|
||||
"is_user_authenticated": false
|
||||
},
|
||||
"auth": {
|
||||
"type": "user_http",
|
||||
"authorization_type": "custom"
|
||||
"type": "service_http",
|
||||
"authorization_type": "custom",
|
||||
"custom_auth_header": "X-Api-Key: ${WORKER_API_KEY}"
|
||||
},
|
||||
"contact_email": "1758359+foryoung365@users.noreply.github.com",
|
||||
"description_for_human": "Google custom search engine API (100🆓/day)",
|
||||
"description_for_model": "Plugin for performing web searches using the Google custom search engine API. Requires Google API key and custom search engine ID.",
|
||||
"legal_info_url": "https://developers.google.com/custom-search/v1/introduction",
|
||||
"logo_url": "https://www.google.com/favicon.ico",
|
||||
"name_for_human": "Search Google via Google Custom Search",
|
||||
"name_for_model": "search-engine-google-custom-search",
|
||||
"description_for_human": "Generate images with Cloudflare Workers AI's flux-1-schnell model",
|
||||
"description_for_model": "This plugin uses the Cloudflare Workers AI's flux-1-schnell model to generate beautiful images.",
|
||||
"legal_info_url": "https://developers.cloudflare.com/ai/",
|
||||
"logo_url": "https://developers.cloudflare.com/favicon.ico",
|
||||
"name_for_human": "AI Image Generator (Flux-1-Schnell)",
|
||||
"name_for_model": "ai-image-generator-flux-schnell",
|
||||
"schema_version": "v1"
|
||||
}
|
||||
|
|
|
@ -1,107 +1,78 @@
|
|||
{
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"googleApiKey": {
|
||||
"apiKeyAuth": {
|
||||
"type": "apiKey",
|
||||
"name": "key",
|
||||
"in": "query",
|
||||
"description": "API key for Google Custom Search API"
|
||||
},
|
||||
"customSearchId": {
|
||||
"type": "apiKey",
|
||||
"name": "cx",
|
||||
"in": "query",
|
||||
"description": "The custom search engine ID to use for this request"
|
||||
"in": "header",
|
||||
"name": "X-Api-Key",
|
||||
"description": "API Key for authentication"
|
||||
}
|
||||
}
|
||||
},
|
||||
"info": {
|
||||
"title": "Web Search",
|
||||
"version": "1.0.0"
|
||||
"title": "AI Image Generator",
|
||||
"version": "1.0.0",
|
||||
"description": "Generate images using Cloudflare Workers AI's @cf/black-forest-labs/flux-1-schnell model"
|
||||
},
|
||||
"openapi": "3.0.0",
|
||||
"paths": {
|
||||
"/customsearch/v1": {
|
||||
"get": {
|
||||
"summary": "Search Google using Custom Search API",
|
||||
"operationId": "searchGoogle",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "q",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"required": true,
|
||||
"description": "Search query string"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "num",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"default": 10
|
||||
},
|
||||
"required": false,
|
||||
"description": "Number of search results to return (1-10)"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "gl",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"required": false,
|
||||
"description": "Geolocation of end user (country code)"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "hl",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"required": false,
|
||||
"description": "Interface language"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful search results",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The title of the search result"
|
||||
},
|
||||
"link": {
|
||||
"type": "string",
|
||||
"description": "The URL of the search result"
|
||||
},
|
||||
"snippet": {
|
||||
"type": "string",
|
||||
"description": "A snippet of text from the search result"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"/": {
|
||||
"post": {
|
||||
"summary": "Generate Image",
|
||||
"operationId": "generateImage",
|
||||
"description": "Generate an image based on text prompt using Cloudflare Workers AI's flux-1-schnell model",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": ["prompt"],
|
||||
"properties": {
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "Text description of the image you want to generate(English only)",
|
||||
"minLength": 1,
|
||||
"maxLength": 2048
|
||||
},
|
||||
"steps": {
|
||||
"type": "integer",
|
||||
"description": "The number of diffusion steps; higher values can improve quality but take longer",
|
||||
"default": 4,
|
||||
"minimum": 1,
|
||||
"maximum": 8
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successfully generated image",
|
||||
"content": {
|
||||
"image/png": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"format": "binary",
|
||||
"description": "Generated image data"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request parameters"
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized, invalid API key"
|
||||
},
|
||||
"500": {
|
||||
"description": "Server error"
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"googleApiKey": [],
|
||||
"customSearchId": []
|
||||
"apiKeyAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -109,13 +80,13 @@
|
|||
},
|
||||
"security": [
|
||||
{
|
||||
"googleApiKey": [],
|
||||
"customSearchId": []
|
||||
"apiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"servers": [
|
||||
{
|
||||
"url": "https://www.googleapis.com"
|
||||
"url": "https://schnell-worker.foryoung365.workers.dev",
|
||||
"description": "Cloudflare Worker for Image Generation"
|
||||
}
|
||||
]
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
{
|
||||
"author": "Barry",
|
||||
"homepage": "https://github.com/GithuBarry/chat-plugin-search-engine",
|
||||
"identifier": "search-engine-google-custom",
|
||||
"manifest": "https://raw.githubusercontent.com/GithuBarry/chat-plugin-search-engine/main/public/manifest.json",
|
||||
"author": "foryoung365",
|
||||
"homepage": "https://github.com/foryoung365/lobechat-plugin-workers-schnell",
|
||||
"identifier": "ai-image-generator-flux-schnell",
|
||||
"manifest": "https://raw.githubusercontent.com/foryoung365/lobechat-plugin-workers-schnell/main/public/manifest.json",
|
||||
"meta": {
|
||||
"avatar": "🔍",
|
||||
"description": "Google search engine via Google Custom Search API (100🆓/day)",
|
||||
"tags": ["web", "search"],
|
||||
"title": "Search Google via Custom Search"
|
||||
"avatar": "🖼️",
|
||||
"description": "Generate images with Cloudflare Workers AI's flux-1-schnell model",
|
||||
"tags": ["image", "ai", "generation"],
|
||||
"title": "AI Image Generator (Flux-1-Schnell)"
|
||||
},
|
||||
"schemaVersion": 1
|
||||
}
|
||||
|
|
|
@ -0,0 +1,99 @@
|
|||
# Cloudflare Worker 部署说明
|
||||
|
||||
本文档提供关于如何部署 Cloudflare Worker 代码的说明,该代码用于处理和代理 LobeChat 插件的请求到 Cloudflare AI API。
|
||||
|
||||
## 前提条件
|
||||
|
||||
1. 一个 Cloudflare 账户
|
||||
2. 已启用 Cloudflare Workers 服务
|
||||
3. 安装并配置了 [Wrangler CLI](https://developers.cloudflare.com/workers/cli-wrangler/install-update)(Cloudflare 的 Worker CLI 工具)
|
||||
|
||||
## 部署步骤
|
||||
|
||||
### 1. 准备工作
|
||||
|
||||
首先,确保你已经获取了以下信息:
|
||||
|
||||
- 你的 Cloudflare 账户 ID(可在 Cloudflare 控制台中找到)
|
||||
- 一个有权限访问 Cloudflare Workers 和 AI API 的 API Token
|
||||
|
||||
### 2. 创建 Worker 项目
|
||||
|
||||
使用 Wrangler 创建一个新的 Worker 项目:
|
||||
|
||||
```bash
|
||||
# 创建新项目
|
||||
wrangler init ai-image-proxy-worker
|
||||
cd ai-image-proxy-worker
|
||||
```
|
||||
|
||||
### 3. 配置 Worker
|
||||
|
||||
将本仓库中的 `src/worker.ts` 文件内容复制到你的 Worker 项目的主文件中(通常是 `src/index.ts`)。
|
||||
|
||||
然后,创建或修改 `wrangler.toml` 文件如下:
|
||||
|
||||
```toml
|
||||
name = "ai-image-proxy-worker"
|
||||
compatibility_date = "2023-10-30"
|
||||
|
||||
[vars]
|
||||
# 这里不要填写敏感信息,这些只是占位符
|
||||
# 实际密钥应使用 Secrets 设置
|
||||
|
||||
# 可选:如果你需要绑定自定义域名
|
||||
# [routes]
|
||||
# pattern = "your-domain.com/*"
|
||||
# zone_id = "your-zone-id"
|
||||
```
|
||||
|
||||
### 4. 设置环境变量(Secrets)
|
||||
|
||||
使用 Wrangler 设置必要的 Secrets:
|
||||
|
||||
```bash
|
||||
# 设置客户端 API 密钥(你自己定义的值,用于客户端访问你的 Worker)
|
||||
wrangler secret put WORKER_API_KEY
|
||||
|
||||
# 设置 Cloudflare API Token(从 Cloudflare 控制台获取)
|
||||
wrangler secret put CLOUDFLARE_API_TOKEN
|
||||
|
||||
# 设置 Cloudflare 账户 ID
|
||||
wrangler secret put CLOUDFLARE_ACCOUNT_ID
|
||||
```
|
||||
|
||||
每条命令运行后,将提示你输入相应的值。
|
||||
|
||||
### 5. 部署 Worker
|
||||
|
||||
完成配置后,部署 Worker:
|
||||
|
||||
```bash
|
||||
wrangler deploy
|
||||
```
|
||||
|
||||
成功部署后,Wrangler 将显示你的 Worker 的 URL,例如:`https://ai-image-proxy-worker.yourusername.workers.dev`。
|
||||
|
||||
### 6. 配置 LobeChat 插件
|
||||
|
||||
按照 README 中的说明配置 LobeChat 插件,将 `WORKER_API_KEY` 设置为你在步骤 4 中配置的客户端 API 密钥。
|
||||
|
||||
## 故障排除
|
||||
|
||||
如果遇到问题,请检查:
|
||||
|
||||
1. Cloudflare 控制台中的 Worker 日志
|
||||
2. 确保所有环境变量(Secrets)都已正确设置
|
||||
3. 验证你的 API Token 是否有足够的权限
|
||||
4. 检查你的账户是否启用了 Workers AI 服务
|
||||
|
||||
## 安全注意事项
|
||||
|
||||
- 定期轮换你的 API 密钥和令牌
|
||||
- 为 Worker API 密钥使用强密码,因为这是客户端用来访问你的 Worker 的凭证
|
||||
- 考虑添加速率限制或其他安全措施来防止滥用
|
||||
|
||||
## 资源链接
|
||||
|
||||
- [Cloudflare Workers 文档](https://developers.cloudflare.com/workers/)
|
||||
- [Workers AI 文档](https://developers.cloudflare.com/workers-ai/)
|
|
@ -0,0 +1,77 @@
|
|||
interface Env {
|
||||
WORKER_API_KEY: string;
|
||||
CLOUDFLARE_API_TOKEN: string;
|
||||
CLOUDFLARE_ACCOUNT_ID: string;
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||
if (request.method !== 'POST') {
|
||||
return new Response('Expected POST', { status: 405 });
|
||||
}
|
||||
|
||||
// 1. 认证客户端 (使用 X-Api-Key 请求头)
|
||||
const clientApiKey = request.headers.get('X-Api-Key');
|
||||
// 'WORKER_API_KEY' 是你在 Cloudflare Secrets 中设置的变量名
|
||||
if (!clientApiKey || clientApiKey !== env.WORKER_API_KEY) {
|
||||
return new Response('Unauthorized: Missing or invalid API Key', { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
// 2. 解析客户端请求体 (只需要 prompt)
|
||||
const clientData = await request.json() as { prompt?: string, steps?: unknown };
|
||||
const prompt = clientData.prompt;
|
||||
const steps = clientData.steps;
|
||||
|
||||
if (!prompt) {
|
||||
return new Response('Missing "prompt" in request body', { status: 400 });
|
||||
}
|
||||
|
||||
// 3. 从环境变量(Secrets)获取 Worker 自身的凭证
|
||||
const apiToken = env.CLOUDFLARE_API_TOKEN;
|
||||
const accountId = env.CLOUDFLARE_ACCOUNT_ID;
|
||||
|
||||
if (!apiToken || !accountId) {
|
||||
console.error('ERROR: Missing Cloudflare credentials in Worker secrets. Ensure CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID secrets are set.');
|
||||
return new Response('Internal Server Error - Configuration Missing', { status: 500 });
|
||||
}
|
||||
|
||||
// 4. 构造发往 Cloudflare AI 的请求 (使用 Worker 的凭证)
|
||||
const aiApiUrl = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/@cf/black-forest-labs/flux-1-schnell`;
|
||||
|
||||
const aiRequest = new Request(aiApiUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${apiToken}`, // 使用 Worker 的 Token
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ prompt: prompt, steps: steps || 4 }), // 使用客户端的 Prompt
|
||||
});
|
||||
|
||||
// 5. 发送请求到 AI API 并获取响应
|
||||
console.log(`Forwarding request to AI API for prompt: "${prompt}"`);
|
||||
const aiResponse = await fetch(aiRequest);
|
||||
console.log(`Received response from AI API with status: ${aiResponse.status}`);
|
||||
|
||||
|
||||
// 6. 将 AI 的响应直接返回给客户端
|
||||
// 创建一个新的 Response 对象以避免潜在的 header 问题或 immutability 问题
|
||||
const responseHeaders = new Headers(aiResponse.headers);
|
||||
//responseHeaders.set('X-Proxied-By', 'my-ai-proxy-worker'); // 添加一个自定义头(可选)
|
||||
|
||||
return new Response(aiResponse.body, {
|
||||
status: aiResponse.status,
|
||||
statusText: aiResponse.statusText,
|
||||
headers: responseHeaders // 返回 AI 的响应头,可以按需修改
|
||||
});
|
||||
|
||||
} catch (error: unknown) {
|
||||
console.error('Error processing request:', error);
|
||||
if (error instanceof SyntaxError) {
|
||||
return new Response('Invalid JSON in request body', { status: 400 });
|
||||
}
|
||||
// 避免将详细错误暴露给客户端
|
||||
return new Response(`Internal Server Error: ${error instanceof Error ? error.message : 'Unknown error'}`, { status: 500 });
|
||||
}
|
||||
},
|
||||
} satisfies ExportedHandler<Env>;
|
Loading…
Reference in New Issue