mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-01-02 22:32:27 +08:00
Compare commits
10 Commits
226c336671
...
chore/clea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
027cf2961e | ||
|
|
ca21a5bb27 | ||
|
|
ad80e9c6f5 | ||
|
|
1ab8d260a2 | ||
|
|
2d62496f9f | ||
|
|
c2aa7f49be | ||
|
|
30b30550d9 | ||
|
|
49b086cef3 | ||
|
|
27f26d8b26 | ||
|
|
6d1e12bb39 |
0
renovate.json → .github/renovate.json
vendored
0
renovate.json → .github/renovate.json
vendored
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -29,7 +29,7 @@ jobs:
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
run: npm install
|
||||
|
||||
- name: Type check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -62,4 +62,7 @@ push-via-ec2.sh
|
||||
*.snap
|
||||
|
||||
CLAUDE.md
|
||||
.spec-workflow
|
||||
.spec-workflow
|
||||
|
||||
# edgeone
|
||||
.edgeone
|
||||
@@ -9,7 +9,7 @@ WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci
|
||||
RUN npm install
|
||||
|
||||
# Stage 2: Build application
|
||||
FROM node:24-alpine AS builder
|
||||
|
||||
35
README.md
35
README.md
@@ -19,6 +19,7 @@ English | [中文](./docs/README_CN.md) | [日本語](./docs/README_JA.md)
|
||||
|
||||
A Next.js web application that integrates AI capabilities with draw.io diagrams. Create, modify, and enhance diagrams through natural language commands and AI-assisted visualization.
|
||||
|
||||
> Note: Thanks to <img src="https://raw.githubusercontent.com/DayuanJiang/next-ai-draw-io/main/public/doubao-color.png" alt="" height="20" /> [ByteDance Doubao](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project) sponsorship, the demo site now uses the powerful K2-thinking model!
|
||||
|
||||
|
||||
https://github.com/user-attachments/assets/9d60a3e8-4a1c-4b5e-acbb-26af2d3eabd1
|
||||
@@ -26,17 +27,20 @@ https://github.com/user-attachments/assets/9d60a3e8-4a1c-4b5e-acbb-26af2d3eabd1
|
||||
|
||||
|
||||
## Table of Contents
|
||||
- [Next AI Draw.io ](#next-ai-drawio-)
|
||||
- [Next AI Draw.io](#next-ai-drawio)
|
||||
- [Table of Contents](#table-of-contents)
|
||||
- [Examples](#examples)
|
||||
- [Features](#features)
|
||||
- [MCP Server (Preview)](#mcp-server-preview)
|
||||
- [Claude Code CLI](#claude-code-cli)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Try it Online](#try-it-online)
|
||||
- [Desktop Application](#desktop-application)
|
||||
- [Run with Docker (Recommended)](#run-with-docker-recommended)
|
||||
- [Installation](#installation)
|
||||
- [Deployment](#deployment)
|
||||
- [Deploy on Vercel (Recommended)](#deploy-on-vercel-recommended)
|
||||
- [Deploy on Cloudflare Workers](#deploy-on-cloudflare-workers)
|
||||
- [Multi-Provider Support](#multi-provider-support)
|
||||
- [How It Works](#how-it-works)
|
||||
- [Project Structure](#project-structure)
|
||||
@@ -132,7 +136,7 @@ No installation needed! Try the app directly on our demo site:
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
> Note: Due to high traffic, the demo site currently uses minimax-m2. For best results, we recommend self-hosting with Claude Sonnet 4.5 or Claude Opus 4.5.
|
||||
|
||||
|
||||
> **Bring Your Own API Key**: You can use your own API key to bypass usage limits on the demo site. Click the Settings icon in the chat panel to configure your provider and API key. Your key is stored locally in your browser and is never stored on the server.
|
||||
|
||||
@@ -213,7 +217,7 @@ cp env.example .env.local
|
||||
|
||||
Edit `.env.local` and configure your chosen provider:
|
||||
|
||||
- Set `AI_PROVIDER` to your chosen provider (bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow)
|
||||
- Set `AI_PROVIDER` to your chosen provider (doubao,bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow)
|
||||
- Set `AI_MODEL` to the specific model you want to use
|
||||
- Add the required API keys for your provider
|
||||
- `TEMPERATURE`: Optional temperature setting (e.g., `0` for deterministic output). Leave unset for models that don't support it (e.g., reasoning models).
|
||||
@@ -233,16 +237,27 @@ npm run dev
|
||||
|
||||
## Deployment
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new) from the creators of Next.js.
|
||||
### Deploy to EdgeOne Pages
|
||||
|
||||
Check out the [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
You can deploy with one click using [Tencent EdgeOne Pages](https://pages.edgeone.ai/).
|
||||
|
||||
Deploy by this button:
|
||||
|
||||
[](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
|
||||
Check out the [Tencent EdgeOne Pages documentation](https://pages.edgeone.ai/document/deployment-overview) for more details.
|
||||
|
||||
Additionally, deploying through Tencent EdgeOne Pages will also grant you a [daily free quota for DeepSeek models](https://pages.edgeone.ai/document/edge-ai).
|
||||
|
||||
### Deploy on Vercel (Recommended)
|
||||
|
||||
Or you can deploy by this button.
|
||||
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
|
||||
Be sure to **set the environment variables** in the Vercel dashboard as you did in your local `.env.local` file.
|
||||
The easiest way to deploy is using [Vercel](https://vercel.com/new), the creators of Next.js. Be sure to **set the environment variables** in the Vercel dashboard as you did in your local `.env.local` file.
|
||||
|
||||
## Deploy on Cloudflare Workers
|
||||
See the [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
|
||||
### Deploy on Cloudflare Workers
|
||||
|
||||
[Go to Cloudflare Deploy Guide](./docs/Cloudflare_Deploy.md)
|
||||
|
||||
@@ -250,6 +265,7 @@ Be sure to **set the environment variables** in the Vercel dashboard as you did
|
||||
|
||||
## Multi-Provider Support
|
||||
|
||||
- [ByteDance Doubao](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project)
|
||||
- AWS Bedrock (default)
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
@@ -260,6 +276,7 @@ Be sure to **set the environment variables** in the Vercel dashboard as you did
|
||||
- DeepSeek
|
||||
- SiliconFlow
|
||||
|
||||
|
||||
All providers except AWS Bedrock and OpenRouter support custom endpoints.
|
||||
|
||||
📖 **[Detailed Provider Configuration Guide](./docs/ai-providers.md)** - See setup instructions for each provider.
|
||||
@@ -300,6 +317,8 @@ public/ # Static assets including example images
|
||||
|
||||
## Support & Contact
|
||||
|
||||
**Special thanks to [ByteDance Doubao](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project) for sponsoring the API token usage of the demo site!** Register on the ARK platform to get 500K free tokens for all models!
|
||||
|
||||
If you find this project useful, please consider [sponsoring](https://github.com/sponsors/DayuanJiang) to help me host the live demo site!
|
||||
|
||||
For support or inquiries, please open an issue on the GitHub repository or contact the maintainer at:
|
||||
|
||||
@@ -72,96 +72,70 @@ export default function AboutCN() {
|
||||
<p className="text-xl text-gray-600 font-medium">
|
||||
AI驱动的图表创建工具 - 对话、绘制、可视化
|
||||
</p>
|
||||
<div className="flex justify-center gap-4 mt-4 text-sm">
|
||||
<Link
|
||||
href="/about"
|
||||
className="text-gray-600 hover:text-blue-600"
|
||||
>
|
||||
English
|
||||
</Link>
|
||||
<span className="text-gray-400">|</span>
|
||||
<Link
|
||||
href="/about/cn"
|
||||
className="text-blue-600 font-semibold"
|
||||
>
|
||||
中文
|
||||
</Link>
|
||||
<span className="text-gray-400">|</span>
|
||||
<Link
|
||||
href="/about/ja"
|
||||
className="text-gray-600 hover:text-blue-600"
|
||||
>
|
||||
日本語
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-rose-50 p-[1px] shadow-lg">
|
||||
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-rose-400 opacity-20" />
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">
|
||||
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-yellow-400 opacity-20" />
|
||||
<div className="relative rounded-2xl bg-white/80 backdrop-blur-sm p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 tracking-tight">
|
||||
模型变更与用量限制{" "}
|
||||
<span className="text-sm text-amber-600 font-medium italic font-normal">
|
||||
(或者说:我的钱包顶不住了)
|
||||
</span>
|
||||
由字节跳动豆包提供支持
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="space-y-3 text-sm text-gray-700 leading-relaxed mb-5">
|
||||
<p>
|
||||
大家对这个项目的热情太高了——看来大家都真的很喜欢画图!但这也带来了一个幸福的烦恼:我们经常触发出上游
|
||||
AI 接口的频率限制
|
||||
(TPS/TPM)。一旦超限,系统就会暂停,导致请求失败。
|
||||
</p>
|
||||
<p>
|
||||
由于使用量过高,我已将模型从 Opus 4.5 更换为{" "}
|
||||
好消息!感谢{" "}
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-semibold text-blue-600 hover:underline"
|
||||
>
|
||||
字节跳动豆包
|
||||
</a>
|
||||
的慷慨赞助,演示站点现已接入强大的{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
Haiku 4.5
|
||||
</span>
|
||||
,以降低成本。
|
||||
</p>
|
||||
<p>
|
||||
作为一个
|
||||
K2-thinking
|
||||
</span>{" "}
|
||||
模型,图表生成效果更佳!点击链接注册即可领取{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
独立开发者
|
||||
50万免费Token
|
||||
</span>
|
||||
,目前的 API
|
||||
费用全是我自己在掏腰包(纯属为爱发电)。为了保证服务能细水长流,同时也为了避免我个人陷入财务危机,我还设置了以下临时用量限制:
|
||||
,适用于所有模型!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Limits Cards */}
|
||||
<div className="grid grid-cols-2 gap-3 mb-5">
|
||||
<div className="rounded-xl bg-gradient-to-br from-amber-100 to-orange-100 p-4 text-center">
|
||||
<div className="text-xs font-medium text-amber-700 uppercase tracking-wide mb-1">
|
||||
Token 用量
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{formatNumber(tpmLimit)}
|
||||
<span className="text-sm font-normal text-gray-600">
|
||||
/分钟
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{formatNumber(dailyTokenLimit)}
|
||||
<span className="text-sm font-normal text-gray-600">
|
||||
/天
|
||||
</span>
|
||||
</div>
|
||||
{/* Usage Limits */}
|
||||
<p className="text-sm text-gray-600 mb-3">
|
||||
当前使用限制:
|
||||
</p>
|
||||
<div className="grid grid-cols-3 gap-3 mb-5">
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(dailyRequestLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
请求/天
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-gradient-to-br from-amber-100 to-orange-100 p-4 text-center">
|
||||
<div className="text-xs font-medium text-amber-700 uppercase tracking-wide mb-1">
|
||||
每日请求数
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900">
|
||||
{dailyRequestLimit}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
次
|
||||
</div>
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(dailyTokenLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Token/天
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(tpmLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Token/分钟
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -171,48 +145,19 @@ export default function AboutCN() {
|
||||
</div>
|
||||
|
||||
{/* Bring Your Own Key */}
|
||||
<div className="text-center mb-5">
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
使用自己的 API Key
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-2 max-w-md mx-auto">
|
||||
您可以使用自己的 API Key
|
||||
来绕过这些限制。点击聊天面板中的设置图标即可配置您的
|
||||
Provider 和 API Key。
|
||||
您也可以使用自己的 API
|
||||
Key,支持多种服务商。点击聊天面板中的设置图标即可配置。
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
您的 Key
|
||||
仅保存在浏览器本地,不会被存储在服务器上。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="flex items-center gap-3 mb-5">
|
||||
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-amber-300 to-transparent" />
|
||||
</div>
|
||||
|
||||
{/* Sponsorship CTA */}
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
寻求赞助 (求大佬捞一把)
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-4 max-w-md mx-auto">
|
||||
要想彻底解除这些限制,扩容后端是唯一的办法。我正在积极寻求
|
||||
AI API 提供商或云平台的赞助。
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 mb-4 max-w-md mx-auto">
|
||||
作为回报(无论是额度支持还是资金支持),我将在
|
||||
GitHub 仓库和 Live Demo
|
||||
网站的显眼位置展示贵公司的 Logo
|
||||
作为平台赞助商。
|
||||
</p>
|
||||
<a
|
||||
href="mailto:me@jiang.jp"
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white font-medium text-sm shadow-md hover:shadow-lg hover:scale-105 transition-all duration-200"
|
||||
>
|
||||
联系我
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -377,6 +322,16 @@ export default function AboutCN() {
|
||||
多提供商支持
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
字节跳动豆包
|
||||
</a>
|
||||
</li>
|
||||
<li>AWS Bedrock(默认)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI兼容API(通过{" "}
|
||||
@@ -388,6 +343,7 @@ export default function AboutCN() {
|
||||
<li>Ollama</li>
|
||||
<li>OpenRouter</li>
|
||||
<li>DeepSeek</li>
|
||||
<li>SiliconFlow</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
注意:<code>claude-sonnet-4-5</code>{" "}
|
||||
@@ -395,18 +351,21 @@ export default function AboutCN() {
|
||||
</p>
|
||||
|
||||
{/* Support */}
|
||||
<div className="flex items-center gap-4 mt-10 mb-4">
|
||||
<h2 className="text-2xl font-semibold text-gray-900">
|
||||
支持与联系
|
||||
</h2>
|
||||
<iframe
|
||||
src="https://github.com/sponsors/DayuanJiang/button"
|
||||
title="Sponsor DayuanJiang"
|
||||
height="32"
|
||||
width="114"
|
||||
style={{ border: 0, borderRadius: 6 }}
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
支持与联系
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4 font-semibold">
|
||||
特别感谢{" "}
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
字节跳动豆包
|
||||
</a>{" "}
|
||||
为本站提供 API Token 支持!
|
||||
</p>
|
||||
<p className="text-gray-700">
|
||||
如果您觉得这个项目有用,请考虑{" "}
|
||||
<a
|
||||
|
||||
@@ -80,97 +80,70 @@ export default function AboutJA() {
|
||||
AI搭載のダイアグラム作成ツール -
|
||||
チャット、描画、可視化
|
||||
</p>
|
||||
<div className="flex justify-center gap-4 mt-4 text-sm">
|
||||
<Link
|
||||
href="/about"
|
||||
className="text-gray-600 hover:text-blue-600"
|
||||
>
|
||||
English
|
||||
</Link>
|
||||
<span className="text-gray-400">|</span>
|
||||
<Link
|
||||
href="/about/cn"
|
||||
className="text-gray-600 hover:text-blue-600"
|
||||
>
|
||||
中文
|
||||
</Link>
|
||||
<span className="text-gray-400">|</span>
|
||||
<Link
|
||||
href="/about/ja"
|
||||
className="text-blue-600 font-semibold"
|
||||
>
|
||||
日本語
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-rose-50 p-[1px] shadow-lg">
|
||||
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-rose-400 opacity-20" />
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">
|
||||
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-yellow-400 opacity-20" />
|
||||
<div className="relative rounded-2xl bg-white/80 backdrop-blur-sm p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 tracking-tight">
|
||||
モデル変更と利用制限について{" "}
|
||||
<span className="text-sm text-amber-600 font-medium italic font-normal">
|
||||
(別名:お財布が悲鳴を上げています)
|
||||
</span>
|
||||
ByteDance Doubao提供
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="space-y-3 text-sm text-gray-700 leading-relaxed mb-5">
|
||||
<p>
|
||||
予想以上の反響をいただき、ありがとうございます!皆様にダイアグラム作成を楽しんでいただいているのは嬉しい限りですが、その熱量により
|
||||
AI API のレート制限 (TPS/TPM)
|
||||
に頻繁に引っかかってしまっています。制限に達するとシステムが一時停止し、エラーが発生してしまいます。
|
||||
</p>
|
||||
<p>
|
||||
利用量の増加に伴い、コスト削減のためモデルを
|
||||
Opus 4.5 から{" "}
|
||||
朗報です!
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-semibold text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
様のご支援により、デモサイトでは強力な{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
Haiku 4.5
|
||||
K2-thinking
|
||||
</span>{" "}
|
||||
に変更しました。
|
||||
</p>
|
||||
<p>
|
||||
私は現在、
|
||||
モデルを利用できるようになり、より高品質なダイアグラム生成が可能になりました。リンクから登録すると、すべてのモデルで使える{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
個人開発者
|
||||
50万トークン
|
||||
</span>
|
||||
として API
|
||||
費用を全額自腹で負担しています。サービスを継続し、かつ私自身が借金を背負わないようにするため(笑)、一時的に以下の利用制限も設けさせていただきました。
|
||||
が無料でもらえます!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Limits Cards */}
|
||||
<div className="grid grid-cols-2 gap-3 mb-5">
|
||||
<div className="rounded-xl bg-gradient-to-br from-amber-100 to-orange-100 p-4 text-center">
|
||||
<div className="text-xs font-medium text-amber-700 uppercase tracking-wide mb-1">
|
||||
トークン使用量
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{formatNumber(tpmLimit)}
|
||||
<span className="text-sm font-normal text-gray-600">
|
||||
/分
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{formatNumber(dailyTokenLimit)}
|
||||
<span className="text-sm font-normal text-gray-600">
|
||||
/日
|
||||
</span>
|
||||
</div>
|
||||
{/* Usage Limits */}
|
||||
<p className="text-sm text-gray-600 mb-3">
|
||||
現在の使用制限:
|
||||
</p>
|
||||
<div className="grid grid-cols-3 gap-3 mb-5">
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(dailyRequestLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
リクエスト/日
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-gradient-to-br from-amber-100 to-orange-100 p-4 text-center">
|
||||
<div className="text-xs font-medium text-amber-700 uppercase tracking-wide mb-1">
|
||||
1日のリクエスト数
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900">
|
||||
{dailyRequestLimit}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
回
|
||||
</div>
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(dailyTokenLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
トークン/日
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(tpmLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
トークン/分
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -180,44 +153,17 @@ export default function AboutJA() {
|
||||
</div>
|
||||
|
||||
{/* Bring Your Own Key */}
|
||||
<div className="text-center mb-5">
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
自分のAPIキーを使用
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-2 max-w-md mx-auto">
|
||||
自分のAPIキーを使用することで、これらの制限を回避できます。チャットパネルの設定アイコンをクリックして、プロバイダーとAPIキーを設定してください。
|
||||
お好みのプロバイダーで自分のAPIキーを使用することもできます。チャットパネルの設定アイコンをクリックして設定してください。
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
キーはブラウザのローカルに保存され、サーバーには保存されません。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="flex items-center gap-3 mb-5">
|
||||
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-amber-300 to-transparent" />
|
||||
</div>
|
||||
|
||||
{/* Sponsorship CTA */}
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
スポンサー募集
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-4 max-w-md mx-auto">
|
||||
これらの制限を取り払い、バックエンドをスケールさせるには皆様の支援が必要です。現在、AI
|
||||
API
|
||||
プロバイダー様やクラウドプラットフォーム様からのスポンサー支援を積極的に募集しています。
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 mb-4 max-w-md mx-auto">
|
||||
ご支援(クレジット提供や資金援助)をいただける場合、GitHub
|
||||
リポジトリおよびデモサイトにて、プラットフォームスポンサーとして貴社を大々的にご紹介させていただきます。
|
||||
</p>
|
||||
<a
|
||||
href="mailto:me@jiang.jp"
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white font-medium text-sm shadow-md hover:shadow-lg hover:scale-105 transition-all duration-200"
|
||||
>
|
||||
お問い合わせ
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -391,6 +337,16 @@ export default function AboutJA() {
|
||||
マルチプロバイダーサポート
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
</li>
|
||||
<li>AWS Bedrock(デフォルト)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI互換API(<code>OPENAI_BASE_URL</code>
|
||||
@@ -402,6 +358,7 @@ export default function AboutJA() {
|
||||
<li>Ollama</li>
|
||||
<li>OpenRouter</li>
|
||||
<li>DeepSeek</li>
|
||||
<li>SiliconFlow</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
注:<code>claude-sonnet-4-5</code>
|
||||
@@ -409,18 +366,21 @@ export default function AboutJA() {
|
||||
</p>
|
||||
|
||||
{/* Support */}
|
||||
<div className="flex items-center gap-4 mt-10 mb-4">
|
||||
<h2 className="text-2xl font-semibold text-gray-900">
|
||||
サポート&お問い合わせ
|
||||
</h2>
|
||||
<iframe
|
||||
src="https://github.com/sponsors/DayuanJiang/button"
|
||||
title="Sponsor DayuanJiang"
|
||||
height="32"
|
||||
width="114"
|
||||
style={{ border: 0, borderRadius: 6 }}
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
サポート&お問い合わせ
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4 font-semibold">
|
||||
デモサイトのAPIトークン使用を支援してくださった{" "}
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>{" "}
|
||||
様に、心より感謝申し上げます。
|
||||
</p>
|
||||
<p className="text-gray-700">
|
||||
このプロジェクトが役に立ったら、ライブデモサイトのホスティングを支援するために{" "}
|
||||
<a
|
||||
|
||||
@@ -80,103 +80,72 @@ export default function About() {
|
||||
AI-Powered Diagram Creation Tool - Chat, Draw,
|
||||
Visualize
|
||||
</p>
|
||||
<div className="flex justify-center gap-4 mt-4 text-sm">
|
||||
<Link
|
||||
href="/about"
|
||||
className="text-blue-600 font-semibold"
|
||||
>
|
||||
English
|
||||
</Link>
|
||||
<span className="text-gray-400">|</span>
|
||||
<Link
|
||||
href="/about/cn"
|
||||
className="text-gray-600 hover:text-blue-600"
|
||||
>
|
||||
中文
|
||||
</Link>
|
||||
<span className="text-gray-400">|</span>
|
||||
<Link
|
||||
href="/about/ja"
|
||||
className="text-gray-600 hover:text-blue-600"
|
||||
>
|
||||
日本語
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-rose-50 p-[1px] shadow-lg">
|
||||
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-rose-400 opacity-20" />
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">
|
||||
<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-yellow-400 opacity-20" />
|
||||
<div className="relative rounded-2xl bg-white/80 backdrop-blur-sm p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 tracking-tight">
|
||||
Model Change & Usage Limits{" "}
|
||||
<span className="text-sm text-amber-600 font-medium italic font-normal">
|
||||
(Or: Why My Wallet is Crying)
|
||||
</span>
|
||||
Sponsored by ByteDance Doubao
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="space-y-3 text-sm text-gray-700 leading-relaxed mb-5">
|
||||
<p>
|
||||
The response to this project has been
|
||||
incredible—you all love making diagrams!
|
||||
However, this enthusiasm means we are
|
||||
frequently hitting the AI API rate limits
|
||||
(TPS/TPM). When this happens, the system
|
||||
pauses, leading to failed requests.
|
||||
</p>
|
||||
<p>
|
||||
Due to the high usage, I have changed the
|
||||
model from Opus 4.5 to{" "}
|
||||
Great news! Thanks to the generous
|
||||
sponsorship from{" "}
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-semibold text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
, the demo site now uses the powerful{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
Haiku 4.5
|
||||
</span>
|
||||
, which is more cost-effective.
|
||||
</p>
|
||||
<p>
|
||||
As an{" "}
|
||||
K2-thinking
|
||||
</span>{" "}
|
||||
model for better diagram generation! Sign up
|
||||
via the link to get{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
indie developer
|
||||
</span>
|
||||
, I am currently footing the entire API
|
||||
bill. To keep the lights on and ensure the
|
||||
service remains available to everyone
|
||||
without sending me into debt, I have also
|
||||
implemented the following temporary caps:
|
||||
500K free tokens
|
||||
</span>{" "}
|
||||
for all models!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Limits Cards */}
|
||||
<div className="grid grid-cols-2 gap-3 mb-5">
|
||||
<div className="rounded-xl bg-gradient-to-br from-amber-100 to-orange-100 p-4 text-center">
|
||||
<div className="text-xs font-medium text-amber-700 uppercase tracking-wide mb-1">
|
||||
Token Usage
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{formatNumber(tpmLimit)}
|
||||
<span className="text-sm font-normal text-gray-600">
|
||||
/min
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{formatNumber(dailyTokenLimit)}
|
||||
<span className="text-sm font-normal text-gray-600">
|
||||
/day
|
||||
</span>
|
||||
</div>
|
||||
{/* Usage Limits */}
|
||||
<p className="text-sm text-gray-600 mb-3">
|
||||
Please note the current usage limits:
|
||||
</p>
|
||||
<div className="grid grid-cols-3 gap-3 mb-5">
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(dailyRequestLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
requests/day
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-gradient-to-br from-amber-100 to-orange-100 p-4 text-center">
|
||||
<div className="text-xs font-medium text-amber-700 uppercase tracking-wide mb-1">
|
||||
Daily Requests
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900">
|
||||
{dailyRequestLimit}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
requests
|
||||
</div>
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(dailyTokenLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
tokens/day
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center p-3 bg-white/60 rounded-lg">
|
||||
<p className="text-lg font-bold text-amber-600">
|
||||
{formatNumber(tpmLimit)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
tokens/min
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -186,51 +155,21 @@ export default function About() {
|
||||
</div>
|
||||
|
||||
{/* Bring Your Own Key */}
|
||||
<div className="text-center mb-5">
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
Bring Your Own API Key
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-2 max-w-md mx-auto">
|
||||
You can use your own API key to bypass these
|
||||
limits. Click the Settings icon in the chat
|
||||
panel to configure your provider and API
|
||||
key.
|
||||
You can also use your own API key with any
|
||||
supported provider. Click the Settings icon
|
||||
in the chat panel to configure your provider
|
||||
and API key.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
Your key is stored locally in your browser
|
||||
and is never stored on the server.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="flex items-center gap-3 mb-5">
|
||||
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-amber-300 to-transparent" />
|
||||
</div>
|
||||
|
||||
{/* Sponsorship CTA */}
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
Call for Sponsorship
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-4 max-w-md mx-auto">
|
||||
Scaling the backend is the only way to
|
||||
remove these limits. I am actively seeking
|
||||
sponsorship from AI API providers or Cloud
|
||||
Platforms.
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 mb-4 max-w-md mx-auto">
|
||||
In return for support (credits or funding),
|
||||
I will prominently feature your company as a
|
||||
platform sponsor on both the GitHub
|
||||
repository and the live demo site.
|
||||
</p>
|
||||
<a
|
||||
href="mailto:me@jiang.jp"
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white font-medium text-sm shadow-md hover:shadow-lg hover:scale-105 transition-all duration-200"
|
||||
>
|
||||
Contact Me
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -417,6 +356,16 @@ export default function About() {
|
||||
Multi-Provider Support
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
</li>
|
||||
<li>AWS Bedrock (default)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI-compatible APIs (via{" "}
|
||||
@@ -428,6 +377,7 @@ export default function About() {
|
||||
<li>Ollama</li>
|
||||
<li>OpenRouter</li>
|
||||
<li>DeepSeek</li>
|
||||
<li>SiliconFlow</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
Note that <code>claude-sonnet-4-5</code> has trained on
|
||||
@@ -437,18 +387,21 @@ export default function About() {
|
||||
</p>
|
||||
|
||||
{/* Support */}
|
||||
<div className="flex items-center gap-4 mt-10 mb-4">
|
||||
<h2 className="text-2xl font-semibold text-gray-900">
|
||||
Support & Contact
|
||||
</h2>
|
||||
<iframe
|
||||
src="https://github.com/sponsors/DayuanJiang/button"
|
||||
title="Sponsor DayuanJiang"
|
||||
height="32"
|
||||
width="114"
|
||||
style={{ border: 0, borderRadius: 6 }}
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
Support & Contact
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4 font-semibold">
|
||||
Special thanks to{" "}
|
||||
<a
|
||||
href="https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>{" "}
|
||||
for sponsoring the API token usage of the demo site!
|
||||
</p>
|
||||
<p className="text-gray-700">
|
||||
If you find this project useful, please consider{" "}
|
||||
<a
|
||||
|
||||
@@ -244,9 +244,22 @@ async function handleChatRequest(req: Request): Promise<Response> {
|
||||
// === CACHE CHECK END ===
|
||||
|
||||
// Read client AI provider overrides from headers
|
||||
const provider = req.headers.get("x-ai-provider")
|
||||
let baseUrl = req.headers.get("x-ai-base-url")
|
||||
|
||||
// For EdgeOne provider, construct full URL from request origin
|
||||
// because createOpenAI needs absolute URL, not relative path
|
||||
if (provider === "edgeone" && !baseUrl) {
|
||||
const origin = req.headers.get("origin") || new URL(req.url).origin
|
||||
baseUrl = `${origin}/api/edgeai`
|
||||
}
|
||||
|
||||
// Get cookie header for EdgeOne authentication (eo_token, eo_time)
|
||||
const cookieHeader = req.headers.get("cookie")
|
||||
|
||||
const clientOverrides = {
|
||||
provider: req.headers.get("x-ai-provider"),
|
||||
baseUrl: req.headers.get("x-ai-base-url"),
|
||||
provider,
|
||||
baseUrl,
|
||||
apiKey: req.headers.get("x-ai-api-key"),
|
||||
modelId: req.headers.get("x-ai-model"),
|
||||
// AWS Bedrock credentials
|
||||
@@ -254,6 +267,11 @@ async function handleChatRequest(req: Request): Promise<Response> {
|
||||
awsSecretAccessKey: req.headers.get("x-aws-secret-access-key"),
|
||||
awsRegion: req.headers.get("x-aws-region"),
|
||||
awsSessionToken: req.headers.get("x-aws-session-token"),
|
||||
// Pass cookies for EdgeOne Pages authentication
|
||||
...(provider === "edgeone" &&
|
||||
cookieHeader && {
|
||||
headers: { cookie: cookieHeader },
|
||||
}),
|
||||
}
|
||||
|
||||
// Read minimal style preference from header
|
||||
@@ -605,7 +623,7 @@ Notes:
|
||||
Operations:
|
||||
- update: Replace an existing cell by its id. Provide cell_id and complete new_xml.
|
||||
- add: Add a new cell. Provide cell_id (new unique id) and new_xml.
|
||||
- delete: Remove a cell by its id. Only cell_id is needed.
|
||||
- delete: Remove a cell. Cascade is automatic: children AND edges (source/target) are auto-deleted. Only specify ONE cell_id.
|
||||
|
||||
For update/add, new_xml must be a complete mxCell element including mxGeometry.
|
||||
|
||||
@@ -614,8 +632,8 @@ For update/add, new_xml must be a complete mxCell element including mxGeometry.
|
||||
Example - Add a rectangle:
|
||||
{"operations": [{"operation": "add", "cell_id": "rect-1", "new_xml": "<mxCell id=\\"rect-1\\" value=\\"Hello\\" style=\\"rounded=0;\\" vertex=\\"1\\" parent=\\"1\\"><mxGeometry x=\\"100\\" y=\\"100\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/></mxCell>"}]}
|
||||
|
||||
Example - Delete a cell:
|
||||
{"operations": [{"operation": "delete", "cell_id": "rect-1"}]}`,
|
||||
Example - Delete container (children & edges auto-deleted):
|
||||
{"operations": [{"operation": "delete", "cell_id": "2"}]}`,
|
||||
inputSchema: z.object({
|
||||
operations: z
|
||||
.array(
|
||||
|
||||
@@ -121,7 +121,7 @@ export async function POST(req: Request) {
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
} else if (provider !== "ollama" && !apiKey) {
|
||||
} else if (provider !== "ollama" && provider !== "edgeone" && !apiKey) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "API key is required" },
|
||||
{ status: 400 },
|
||||
@@ -225,6 +225,42 @@ export async function POST(req: Request) {
|
||||
break
|
||||
}
|
||||
|
||||
case "edgeone": {
|
||||
// EdgeOne uses OpenAI-compatible API via Edge Functions
|
||||
// Need to pass cookies for EdgeOne Pages authentication
|
||||
const cookieHeader = req.headers.get("cookie") || ""
|
||||
const edgeone = createOpenAI({
|
||||
apiKey: "edgeone", // EdgeOne doesn't require API key
|
||||
baseURL: baseUrl || "/api/edgeai",
|
||||
headers: {
|
||||
cookie: cookieHeader,
|
||||
},
|
||||
})
|
||||
model = edgeone.chat(modelId)
|
||||
break
|
||||
}
|
||||
|
||||
case "sglang": {
|
||||
// SGLang is OpenAI-compatible
|
||||
const sglang = createOpenAI({
|
||||
apiKey: apiKey || "not-needed",
|
||||
baseURL: baseUrl || "http://127.0.0.1:8000/v1",
|
||||
})
|
||||
model = sglang.chat(modelId)
|
||||
break
|
||||
}
|
||||
|
||||
case "doubao": {
|
||||
// ByteDance Doubao uses DeepSeek-compatible API
|
||||
const doubao = createDeepSeek({
|
||||
apiKey,
|
||||
baseURL:
|
||||
baseUrl || "https://ark.cn-beijing.volces.com/api/v3",
|
||||
})
|
||||
model = doubao(modelId)
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: `Unknown provider: ${provider}` },
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
ReasoningTrigger,
|
||||
} from "@/components/ai-elements/reasoning"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { getApiEndpoint } from "@/lib/base-path"
|
||||
import {
|
||||
applyDiagramOperations,
|
||||
@@ -205,6 +206,7 @@ export function ChatMessageDisplay({
|
||||
onEditMessage,
|
||||
status = "idle",
|
||||
}: ChatMessageDisplayProps) {
|
||||
const dict = useDictionary()
|
||||
const { chartXML, loadDiagram: onDisplayChart } = useDiagram()
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
const previousXML = useRef<string>("")
|
||||
@@ -268,9 +270,7 @@ export function ChatMessageDisplay({
|
||||
setTimeout(() => setCopiedMessageId(null), 2000)
|
||||
} catch (fallbackErr) {
|
||||
console.error("Failed to copy message:", fallbackErr)
|
||||
toast.error(
|
||||
"Failed to copy message. Please copy manually or check clipboard permissions.",
|
||||
)
|
||||
toast.error(dict.chat.failedToCopyDetail)
|
||||
setCopyFailedMessageId(messageId)
|
||||
setTimeout(() => setCopyFailedMessageId(null), 2000)
|
||||
} finally {
|
||||
@@ -304,7 +304,7 @@ export function ChatMessageDisplay({
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to log feedback:", error)
|
||||
toast.error("Failed to record your feedback. Please try again.")
|
||||
toast.error(dict.errors.failedToRecordFeedback)
|
||||
// Revert optimistic UI update
|
||||
setFeedback((prev) => {
|
||||
const next = { ...prev }
|
||||
@@ -349,9 +349,7 @@ export function ChatMessageDisplay({
|
||||
console.error(
|
||||
"[ChatMessageDisplay] Malformed XML detected in final output",
|
||||
)
|
||||
toast.error(
|
||||
"AI generated invalid diagram XML. Please try regenerating.",
|
||||
)
|
||||
toast.error(dict.errors.malformedXml)
|
||||
}
|
||||
return // Skip this update
|
||||
}
|
||||
@@ -402,9 +400,7 @@ export function ChatMessageDisplay({
|
||||
"[ChatMessageDisplay] XML validation failed:",
|
||||
validation.error,
|
||||
)
|
||||
toast.error(
|
||||
"Diagram validation failed. Please try regenerating.",
|
||||
)
|
||||
toast.error(dict.errors.validationFailed)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
@@ -413,9 +409,7 @@ export function ChatMessageDisplay({
|
||||
)
|
||||
// Only show toast if this is the final XML (not during streaming)
|
||||
if (showToast) {
|
||||
toast.error(
|
||||
"Failed to process diagram. Please try regenerating.",
|
||||
)
|
||||
toast.error(dict.errors.failedToProcess)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -832,7 +826,10 @@ export function ChatMessageDisplay({
|
||||
)
|
||||
}}
|
||||
className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-muted-foreground hover:bg-muted transition-colors"
|
||||
title="Edit message"
|
||||
title={
|
||||
dict.chat
|
||||
.editMessage
|
||||
}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -849,11 +846,13 @@ export function ChatMessageDisplay({
|
||||
title={
|
||||
copiedMessageId ===
|
||||
message.id
|
||||
? "Copied!"
|
||||
? dict.chat.copied
|
||||
: copyFailedMessageId ===
|
||||
message.id
|
||||
? "Failed to copy"
|
||||
: "Copy message"
|
||||
? dict.chat
|
||||
.failedToCopy
|
||||
: dict.chat
|
||||
.copyResponse
|
||||
}
|
||||
>
|
||||
{copiedMessageId ===
|
||||
@@ -968,7 +967,7 @@ export function ChatMessageDisplay({
|
||||
}}
|
||||
className="px-3 py-1.5 text-xs rounded-lg bg-muted hover:bg-muted/80 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
{dict.common.cancel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -990,7 +989,7 @@ export function ChatMessageDisplay({
|
||||
disabled={!editText.trim()}
|
||||
className="px-3 py-1.5 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
Save & Submit
|
||||
{dict.chat.saveAndSubmit}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1123,7 +1122,8 @@ export function ChatMessageDisplay({
|
||||
"user" &&
|
||||
isLastUserMessage &&
|
||||
onEditMessage
|
||||
? "Click to edit"
|
||||
? dict.chat
|
||||
.clickToEdit
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
@@ -1325,8 +1325,8 @@ export function ChatMessageDisplay({
|
||||
title={
|
||||
copiedMessageId ===
|
||||
message.id
|
||||
? "Copied!"
|
||||
: "Copy response"
|
||||
? dict.chat.copied
|
||||
: dict.chat.copyResponse
|
||||
}
|
||||
>
|
||||
{copiedMessageId ===
|
||||
@@ -1352,7 +1352,9 @@ export function ChatMessageDisplay({
|
||||
)
|
||||
}
|
||||
className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors"
|
||||
title="Regenerate response"
|
||||
title={
|
||||
dict.chat.regenerate
|
||||
}
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -1374,7 +1376,7 @@ export function ChatMessageDisplay({
|
||||
? "text-green-600 bg-green-100"
|
||||
: "text-muted-foreground/60 hover:text-green-600 hover:bg-green-50"
|
||||
}`}
|
||||
title="Good response"
|
||||
title={dict.chat.goodResponse}
|
||||
>
|
||||
<ThumbsUp className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -1393,7 +1395,7 @@ export function ChatMessageDisplay({
|
||||
? "text-red-600 bg-red-100"
|
||||
: "text-muted-foreground/60 hover:text-red-600 hover:bg-red-50"
|
||||
}`}
|
||||
title="Bad response"
|
||||
title={dict.chat.badResponse}
|
||||
>
|
||||
<ThumbsDown className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
|
||||
@@ -24,6 +24,7 @@ import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { getSelectedAIConfig, useModelConfig } from "@/hooks/use-model-config"
|
||||
import { getApiEndpoint } from "@/lib/base-path"
|
||||
import { findCachedResponse } from "@/lib/cached-responses"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
|
||||
import { type FileData, useFileProcessor } from "@/lib/use-file-processor"
|
||||
import { useQuotaManager } from "@/lib/use-quota-manager"
|
||||
@@ -183,6 +184,7 @@ export default function ChatPanel({
|
||||
dailyRequestLimit,
|
||||
dailyTokenLimit,
|
||||
tpmLimit,
|
||||
onConfigModel: () => setShowModelConfigDialog(true),
|
||||
})
|
||||
|
||||
// Generate a unique session ID for Langfuse tracing (restore from localStorage if available)
|
||||
@@ -386,7 +388,9 @@ export default function ChatPanel({
|
||||
MAX_CONTINUATION_RETRY_COUNT
|
||||
) {
|
||||
toast.error(
|
||||
`Continuation retry limit reached (${MAX_CONTINUATION_RETRY_COUNT}). The diagram may be too complex.`,
|
||||
formatMessage(dict.errors.continuationRetryLimit, {
|
||||
max: MAX_CONTINUATION_RETRY_COUNT,
|
||||
}),
|
||||
)
|
||||
continuationRetryCountRef.current = 0
|
||||
partialXmlRef.current = ""
|
||||
@@ -397,7 +401,9 @@ export default function ChatPanel({
|
||||
// Regular error: check retry count limit
|
||||
if (autoRetryCountRef.current >= MAX_AUTO_RETRY_COUNT) {
|
||||
toast.error(
|
||||
`Auto-retry limit reached (${MAX_AUTO_RETRY_COUNT}). Please try again manually.`,
|
||||
formatMessage(dict.errors.retryLimit, {
|
||||
max: MAX_AUTO_RETRY_COUNT,
|
||||
}),
|
||||
)
|
||||
autoRetryCountRef.current = 0
|
||||
partialXmlRef.current = ""
|
||||
@@ -447,7 +453,7 @@ export default function ChatPanel({
|
||||
// On complete failure, clear storage to allow recovery
|
||||
localStorage.removeItem(STORAGE_MESSAGES_KEY)
|
||||
localStorage.removeItem(STORAGE_XML_SNAPSHOTS_KEY)
|
||||
toast.error("Session data was corrupted. Starting fresh.")
|
||||
toast.error(dict.errors.sessionCorrupted)
|
||||
}
|
||||
}, [setMessages])
|
||||
|
||||
@@ -648,12 +654,10 @@ export default function ChatPanel({
|
||||
localStorage.removeItem(STORAGE_DIAGRAM_XML_KEY)
|
||||
localStorage.setItem(STORAGE_SESSION_ID_KEY, newSessionId)
|
||||
sessionStorage.removeItem(SESSION_STORAGE_INPUT_KEY)
|
||||
toast.success("Started a fresh chat")
|
||||
toast.success(dict.dialogs.clearSuccess)
|
||||
} catch (error) {
|
||||
console.error("Failed to clear localStorage:", error)
|
||||
toast.warning(
|
||||
"Chat cleared but browser storage could not be updated",
|
||||
)
|
||||
toast.warning(dict.errors.storageUpdateFailed)
|
||||
}
|
||||
|
||||
setShowNewChatDialog(false)
|
||||
@@ -886,7 +890,7 @@ export default function ChatPanel({
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center pt-4 bg-card border border-border/30 rounded-xl">
|
||||
<ButtonWithTooltip
|
||||
tooltipContent="Show chat panel (Ctrl+B)"
|
||||
tooltipContent={dict.nav.showPanel}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onToggleVisibility}
|
||||
@@ -901,7 +905,7 @@ export default function ChatPanel({
|
||||
transform: "rotate(180deg)",
|
||||
}}
|
||||
>
|
||||
AI Chat
|
||||
{dict.nav.aiChat}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -1008,6 +1012,9 @@ export default function ChatPanel({
|
||||
<DevXmlSimulator
|
||||
setMessages={setMessages}
|
||||
onDisplayChart={onDisplayChart}
|
||||
onShowQuotaToast={() =>
|
||||
quotaManager.showQuotaLimitToast(50, 50)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { wrapWithMxFile } from "@/lib/utils"
|
||||
|
||||
// Dev XML presets for streaming simulator
|
||||
@@ -134,12 +135,15 @@ const DEV_XML_PRESETS: Record<string, string> = {
|
||||
interface DevXmlSimulatorProps {
|
||||
setMessages: React.Dispatch<React.SetStateAction<any[]>>
|
||||
onDisplayChart: (xml: string) => void
|
||||
onShowQuotaToast?: () => void
|
||||
}
|
||||
|
||||
export function DevXmlSimulator({
|
||||
setMessages,
|
||||
onDisplayChart,
|
||||
onShowQuotaToast,
|
||||
}: DevXmlSimulatorProps) {
|
||||
const dict = useDictionary()
|
||||
const [devXml, setDevXml] = useState("")
|
||||
const [isSimulating, setIsSimulating] = useState(false)
|
||||
const [devIntervalMs, setDevIntervalMs] = useState(1)
|
||||
@@ -176,7 +180,7 @@ export function DevXmlSimulator({
|
||||
parts: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: "[Dev] Simulating XML streaming",
|
||||
text: dict.dev.simulatingMessage,
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -226,7 +230,7 @@ export function DevXmlSimulator({
|
||||
const lastMsg = updated[updated.length - 1] as any
|
||||
if (lastMsg?.role === "assistant" && lastMsg.parts?.[0]) {
|
||||
lastMsg.parts[0].state = "output-available"
|
||||
lastMsg.parts[0].output = "Successfully displayed the diagram."
|
||||
lastMsg.parts[0].output = dict.dev.successMessage
|
||||
lastMsg.parts[0].input = { xml }
|
||||
}
|
||||
return updated
|
||||
@@ -243,12 +247,12 @@ export function DevXmlSimulator({
|
||||
<div className="border-t border-dashed border-orange-500/50 px-4 py-2 bg-orange-50/50 dark:bg-orange-950/30">
|
||||
<details>
|
||||
<summary className="text-xs text-orange-600 dark:text-orange-400 cursor-pointer font-medium">
|
||||
Dev: XML Streaming Simulator
|
||||
{dict.dev.title}
|
||||
</summary>
|
||||
<div className="mt-2 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
Preset:
|
||||
{dict.dev.preset}
|
||||
</label>
|
||||
<select
|
||||
onChange={(e) => {
|
||||
@@ -260,7 +264,7 @@ export function DevXmlSimulator({
|
||||
defaultValue=""
|
||||
>
|
||||
<option value="" disabled>
|
||||
Select a preset...
|
||||
{dict.dev.selectPreset}
|
||||
</option>
|
||||
{Object.keys(DEV_XML_PRESETS).map((name) => (
|
||||
<option key={name} value={name}>
|
||||
@@ -273,19 +277,19 @@ export function DevXmlSimulator({
|
||||
onClick={() => setDevXml("")}
|
||||
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground border rounded"
|
||||
>
|
||||
Clear
|
||||
{dict.dev.clear}
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
value={devXml}
|
||||
onChange={(e) => setDevXml(e.target.value)}
|
||||
placeholder="Paste mxCell XML here or select a preset..."
|
||||
placeholder={dict.dev.placeholder}
|
||||
className="w-full h-24 text-xs font-mono p-2 border rounded bg-background"
|
||||
/>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<label className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
Interval:
|
||||
{dict.dev.interval}
|
||||
</label>
|
||||
<input
|
||||
type="range"
|
||||
@@ -304,7 +308,7 @@ export function DevXmlSimulator({
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
Chars:
|
||||
{dict.dev.chars}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
@@ -328,8 +332,8 @@ export function DevXmlSimulator({
|
||||
className="px-3 py-1 text-xs bg-orange-500 text-white rounded hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isSimulating
|
||||
? "Streaming..."
|
||||
: `Simulate (${devChunkSize} chars/${devIntervalMs}ms)`}
|
||||
? dict.dev.streaming
|
||||
: `${dict.dev.simulate} (${devChunkSize} chars/${devIntervalMs}ms)`}
|
||||
</button>
|
||||
{isSimulating && (
|
||||
<button
|
||||
@@ -339,7 +343,16 @@ export function DevXmlSimulator({
|
||||
}}
|
||||
className="px-3 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
|
||||
>
|
||||
Stop
|
||||
{dict.dev.stop}
|
||||
</button>
|
||||
)}
|
||||
{onShowQuotaToast && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onShowQuotaToast}
|
||||
className="px-3 py-1 text-xs bg-purple-500 text-white rounded hover:bg-purple-600"
|
||||
>
|
||||
{dict.dev.testQuotaToast}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -76,7 +76,10 @@ const PROVIDER_LOGO_MAP: Record<string, string> = {
|
||||
openrouter: "openrouter",
|
||||
deepseek: "deepseek",
|
||||
siliconflow: "siliconflow",
|
||||
sglang: "openai", // SGLang is OpenAI-compatible
|
||||
gateway: "vercel",
|
||||
edgeone: "tencent-cloud",
|
||||
doubao: "bytedance",
|
||||
}
|
||||
|
||||
// Provider logo component
|
||||
@@ -87,10 +90,16 @@ function ProviderLogo({
|
||||
provider: ProviderName
|
||||
className?: string
|
||||
}) {
|
||||
// Use Lucide icon for bedrock since models.dev doesn't have a good AWS icon
|
||||
// Use Lucide icons for providers without models.dev logos
|
||||
if (provider === "bedrock") {
|
||||
return <Cloud className={cn("size-4", className)} />
|
||||
}
|
||||
if (provider === "sglang") {
|
||||
return <Server className={cn("size-4", className)} />
|
||||
}
|
||||
if (provider === "doubao") {
|
||||
return <Sparkles className={cn("size-4", className)} />
|
||||
}
|
||||
|
||||
const logoName = PROVIDER_LOGO_MAP[provider] || provider
|
||||
return (
|
||||
@@ -269,6 +278,7 @@ export function ModelConfigDialog({
|
||||
|
||||
// Check credentials based on provider type
|
||||
const isBedrock = selectedProvider.provider === "bedrock"
|
||||
const isEdgeOne = selectedProvider.provider === "edgeone"
|
||||
if (isBedrock) {
|
||||
if (
|
||||
!selectedProvider.awsAccessKeyId ||
|
||||
@@ -277,7 +287,7 @@ export function ModelConfigDialog({
|
||||
) {
|
||||
return
|
||||
}
|
||||
} else if (!selectedProvider.apiKey) {
|
||||
} else if (!isEdgeOne && !selectedProvider.apiKey) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -300,13 +310,18 @@ export function ModelConfigDialog({
|
||||
setValidatingModelIndex(i)
|
||||
|
||||
try {
|
||||
// For EdgeOne, construct baseUrl from current origin
|
||||
const baseUrl = isEdgeOne
|
||||
? `${window.location.origin}/api/edgeai`
|
||||
: selectedProvider.baseUrl
|
||||
|
||||
const response = await fetch("/api/validate-model", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
provider: selectedProvider.provider,
|
||||
apiKey: selectedProvider.apiKey,
|
||||
baseUrl: selectedProvider.baseUrl,
|
||||
baseUrl,
|
||||
modelId: model.modelId,
|
||||
// AWS Bedrock credentials
|
||||
awsAccessKeyId: selectedProvider.awsAccessKeyId,
|
||||
@@ -314,7 +329,6 @@ export function ModelConfigDialog({
|
||||
awsRegion: selectedProvider.awsRegion,
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (data.valid) {
|
||||
@@ -868,6 +882,63 @@ export function ModelConfigDialog({
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : selectedProvider.provider ===
|
||||
"edgeone" ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant={
|
||||
validationStatus ===
|
||||
"success"
|
||||
? "outline"
|
||||
: "default"
|
||||
}
|
||||
size="sm"
|
||||
onClick={
|
||||
handleValidate
|
||||
}
|
||||
disabled={
|
||||
validationStatus ===
|
||||
"validating"
|
||||
}
|
||||
className={cn(
|
||||
"h-9 px-4",
|
||||
validationStatus ===
|
||||
"success" &&
|
||||
"text-success border-success/30 bg-success-muted hover:bg-success-muted",
|
||||
)}
|
||||
>
|
||||
{validationStatus ===
|
||||
"validating" ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : validationStatus ===
|
||||
"success" ? (
|
||||
<>
|
||||
<Check className="h-4 w-4 mr-1.5" />
|
||||
{
|
||||
dict
|
||||
.modelConfig
|
||||
.verified
|
||||
}
|
||||
</>
|
||||
) : (
|
||||
dict
|
||||
.modelConfig
|
||||
.test
|
||||
)}
|
||||
</Button>
|
||||
{validationStatus ===
|
||||
"error" &&
|
||||
validationError && (
|
||||
<p className="text-xs text-destructive flex items-center gap-1">
|
||||
<X className="h-3 w-3" />
|
||||
{
|
||||
validationError
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* API Key */}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
Server,
|
||||
Settings2,
|
||||
} from "lucide-react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import {
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
@@ -46,7 +46,10 @@ const PROVIDER_LOGO_MAP: Record<string, string> = {
|
||||
openrouter: "openrouter",
|
||||
deepseek: "deepseek",
|
||||
siliconflow: "siliconflow",
|
||||
sglang: "openai", // SGLang is OpenAI-compatible, use OpenAI logo
|
||||
gateway: "vercel",
|
||||
edgeone: "tencent-cloud",
|
||||
doubao: "bytedance",
|
||||
}
|
||||
|
||||
// Group models by providerLabel (handles duplicate providers)
|
||||
@@ -112,134 +115,189 @@ export function ModelSelector({
|
||||
? `${selectedModel.modelId} ${dict.modelConfig.clickToChange}`
|
||||
: `${dict.modelConfig.usingServerDefault} ${dict.modelConfig.clickToChange}`
|
||||
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null)
|
||||
const [showLabel, setShowLabel] = useState(true)
|
||||
|
||||
// Threshold (px) under which we hide the label (tweak as needed)
|
||||
const HIDE_THRESHOLD = 240
|
||||
const SHOW_THRESHOLD = 260
|
||||
useEffect(() => {
|
||||
const el = wrapperRef.current
|
||||
if (!el) return
|
||||
|
||||
const target = el.parentElement ?? el
|
||||
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const width = entry.contentRect.width
|
||||
setShowLabel((prev) => {
|
||||
// if currently showing and width dropped below hide threshold -> hide
|
||||
if (prev && width <= HIDE_THRESHOLD) return false
|
||||
// if currently hidden and width rose above show threshold -> show
|
||||
if (!prev && width >= SHOW_THRESHOLD) return true
|
||||
// otherwise keep previous state (hysteresis)
|
||||
return prev
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
ro.observe(target)
|
||||
|
||||
const initialWidth = target.getBoundingClientRect().width
|
||||
setShowLabel(initialWidth >= SHOW_THRESHOLD)
|
||||
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ModelSelectorRoot open={open} onOpenChange={setOpen}>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<ButtonWithTooltip
|
||||
tooltipContent={tooltipContent}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
className="hover:bg-accent gap-1.5 h-8 max-w-[180px] px-2"
|
||||
>
|
||||
<Bot className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
<span className="text-xs truncate">
|
||||
{selectedModel
|
||||
? selectedModel.modelId
|
||||
: dict.modelConfig.default}
|
||||
</span>
|
||||
<ChevronDown className="h-3 w-3 flex-shrink-0 text-muted-foreground" />
|
||||
</ButtonWithTooltip>
|
||||
</ModelSelectorTrigger>
|
||||
<ModelSelectorContent title={dict.modelConfig.selectModel}>
|
||||
<ModelSelectorInput
|
||||
placeholder={dict.modelConfig.searchModels}
|
||||
/>
|
||||
<ModelSelectorList className="[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
<ModelSelectorEmpty>
|
||||
{displayModels.length === 0 && models.length > 0
|
||||
? dict.modelConfig.noVerifiedModels
|
||||
: dict.modelConfig.noModelsFound}
|
||||
</ModelSelectorEmpty>
|
||||
<div ref={wrapperRef} className="inline-block">
|
||||
<ModelSelectorRoot open={open} onOpenChange={setOpen}>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<ButtonWithTooltip
|
||||
tooltipContent={tooltipContent}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"hover:bg-accent gap-1.5 h-8 px-2 transition-all duration-150 ease-in-out",
|
||||
!showLabel && "px-1.5 justify-center",
|
||||
)}
|
||||
// accessibility: expose label to screen readers
|
||||
aria-label={tooltipContent}
|
||||
>
|
||||
<Bot className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
{/* show/hide visible label based on measured width */}
|
||||
{showLabel ? (
|
||||
<span className="text-xs truncate">
|
||||
{selectedModel
|
||||
? selectedModel.modelId
|
||||
: dict.modelConfig.default}
|
||||
</span>
|
||||
) : (
|
||||
// Keep an sr-only label for screen readers when hidden
|
||||
<span className="sr-only">
|
||||
{selectedModel
|
||||
? selectedModel.modelId
|
||||
: dict.modelConfig.default}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown className="h-3 w-3 flex-shrink-0 text-muted-foreground" />
|
||||
</ButtonWithTooltip>
|
||||
</ModelSelectorTrigger>
|
||||
|
||||
{/* Server Default Option */}
|
||||
<ModelSelectorGroup heading={dict.modelConfig.default}>
|
||||
<ModelSelectorItem
|
||||
value="__server_default__"
|
||||
onSelect={handleSelect}
|
||||
className={cn(
|
||||
"cursor-pointer",
|
||||
!selectedModelId && "bg-accent",
|
||||
)}
|
||||
>
|
||||
<Check
|
||||
<ModelSelectorContent title={dict.modelConfig.selectModel}>
|
||||
<ModelSelectorInput
|
||||
placeholder={dict.modelConfig.searchModels}
|
||||
/>
|
||||
<ModelSelectorList className="[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
<ModelSelectorEmpty>
|
||||
{displayModels.length === 0 && models.length > 0
|
||||
? dict.modelConfig.noVerifiedModels
|
||||
: dict.modelConfig.noModelsFound}
|
||||
</ModelSelectorEmpty>
|
||||
|
||||
{/* Server Default Option */}
|
||||
<ModelSelectorGroup heading={dict.modelConfig.default}>
|
||||
<ModelSelectorItem
|
||||
value="__server_default__"
|
||||
onSelect={handleSelect}
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
!selectedModelId
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
"cursor-pointer",
|
||||
!selectedModelId && "bg-accent",
|
||||
)}
|
||||
/>
|
||||
<Server className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
<ModelSelectorName>
|
||||
{dict.modelConfig.serverDefault}
|
||||
</ModelSelectorName>
|
||||
</ModelSelectorItem>
|
||||
</ModelSelectorGroup>
|
||||
|
||||
{/* Configured Models by Provider */}
|
||||
{Array.from(groupedModels.entries()).map(
|
||||
([
|
||||
providerLabel,
|
||||
{ provider, models: providerModels },
|
||||
]) => (
|
||||
<ModelSelectorGroup
|
||||
key={providerLabel}
|
||||
heading={providerLabel}
|
||||
>
|
||||
{providerModels.map((model) => (
|
||||
<ModelSelectorItem
|
||||
key={model.id}
|
||||
value={model.modelId}
|
||||
onSelect={() => handleSelect(model.id)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedModelId === model.id
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<ModelSelectorLogo
|
||||
provider={
|
||||
PROVIDER_LOGO_MAP[provider] ||
|
||||
provider
|
||||
}
|
||||
className="mr-2"
|
||||
/>
|
||||
<ModelSelectorName>
|
||||
{model.modelId}
|
||||
</ModelSelectorName>
|
||||
{model.validated !== true && (
|
||||
<span
|
||||
title={
|
||||
dict.modelConfig
|
||||
.unvalidatedModelWarning
|
||||
}
|
||||
>
|
||||
<AlertTriangle className="ml-auto h-3 w-3 text-warning" />
|
||||
</span>
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
),
|
||||
)}
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
!selectedModelId
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<Server className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
<ModelSelectorName>
|
||||
{dict.modelConfig.serverDefault}
|
||||
</ModelSelectorName>
|
||||
</ModelSelectorItem>
|
||||
</ModelSelectorGroup>
|
||||
|
||||
{/* Configure Option */}
|
||||
<ModelSelectorSeparator />
|
||||
<ModelSelectorGroup>
|
||||
<ModelSelectorItem
|
||||
value="__configure__"
|
||||
onSelect={handleSelect}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Settings2 className="mr-2 h-4 w-4" />
|
||||
<ModelSelectorName>
|
||||
{dict.modelConfig.configureModels}
|
||||
</ModelSelectorName>
|
||||
</ModelSelectorItem>
|
||||
</ModelSelectorGroup>
|
||||
{/* Info text */}
|
||||
<div className="px-3 py-2 text-xs text-muted-foreground border-t">
|
||||
{showUnvalidatedModels
|
||||
? dict.modelConfig.allModelsShown
|
||||
: dict.modelConfig.onlyVerifiedShown}
|
||||
</div>
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelectorRoot>
|
||||
{/* Configured Models by Provider */}
|
||||
{Array.from(groupedModels.entries()).map(
|
||||
([
|
||||
providerLabel,
|
||||
{ provider, models: providerModels },
|
||||
]) => (
|
||||
<ModelSelectorGroup
|
||||
key={providerLabel}
|
||||
heading={providerLabel}
|
||||
>
|
||||
{providerModels.map((model) => (
|
||||
<ModelSelectorItem
|
||||
key={model.id}
|
||||
value={model.modelId}
|
||||
onSelect={() =>
|
||||
handleSelect(model.id)
|
||||
}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedModelId === model.id
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<ModelSelectorLogo
|
||||
provider={
|
||||
PROVIDER_LOGO_MAP[
|
||||
provider
|
||||
] || provider
|
||||
}
|
||||
className="mr-2"
|
||||
/>
|
||||
<ModelSelectorName>
|
||||
{model.modelId}
|
||||
</ModelSelectorName>
|
||||
{model.validated !== true && (
|
||||
<span
|
||||
title={
|
||||
dict.modelConfig
|
||||
.unvalidatedModelWarning
|
||||
}
|
||||
>
|
||||
<AlertTriangle className="ml-auto h-3 w-3 text-warning" />
|
||||
</span>
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
),
|
||||
)}
|
||||
|
||||
{/* Configure Option */}
|
||||
<ModelSelectorSeparator />
|
||||
<ModelSelectorGroup>
|
||||
<ModelSelectorItem
|
||||
value="__configure__"
|
||||
onSelect={handleSelect}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Settings2 className="mr-2 h-4 w-4" />
|
||||
<ModelSelectorName>
|
||||
{dict.modelConfig.configureModels}
|
||||
</ModelSelectorName>
|
||||
</ModelSelectorItem>
|
||||
</ModelSelectorGroup>
|
||||
{/* Info text */}
|
||||
<div className="px-3 py-2 text-xs text-muted-foreground border-t">
|
||||
{showUnvalidatedModels
|
||||
? dict.modelConfig.allModelsShown
|
||||
: dict.modelConfig.onlyVerifiedShown}
|
||||
</div>
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelectorRoot>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { Coffee, X } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Coffee, Settings, X } from "lucide-react"
|
||||
import type React from "react"
|
||||
import { FaGithub } from "react-icons/fa"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
@@ -12,6 +11,7 @@ interface QuotaLimitToastProps {
|
||||
used: number
|
||||
limit: number
|
||||
onDismiss: () => void
|
||||
onConfigModel?: () => void
|
||||
}
|
||||
|
||||
export function QuotaLimitToast({
|
||||
@@ -19,6 +19,7 @@ export function QuotaLimitToast({
|
||||
used,
|
||||
limit,
|
||||
onDismiss,
|
||||
onConfigModel,
|
||||
}: QuotaLimitToastProps) {
|
||||
const dict = useDictionary()
|
||||
const isTokenLimit = type === "token"
|
||||
@@ -75,16 +76,36 @@ export function QuotaLimitToast({
|
||||
? dict.quota.messageToken
|
||||
: dict.quota.messageApi}
|
||||
</p>
|
||||
<p
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: formatMessage(dict.quota.doubaoSponsorship, {
|
||||
link: "https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project",
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
<p dangerouslySetInnerHTML={{ __html: dict.quota.tip }} />
|
||||
<p>{dict.quota.reset}</p>
|
||||
</div>{" "}
|
||||
{/* Action buttons */}
|
||||
<div className="flex items-center gap-2">
|
||||
{onConfigModel && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onConfigModel()
|
||||
onDismiss()
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
<Settings className="w-3.5 h-3.5" />
|
||||
{dict.quota.configModel}
|
||||
</button>
|
||||
)}
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border border-border text-foreground hover:bg-muted transition-colors"
|
||||
>
|
||||
<FaGithub className="w-3.5 h-3.5" />
|
||||
{dict.quota.selfHost}
|
||||
|
||||
@@ -395,13 +395,13 @@ function SettingsContent({
|
||||
<>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<a
|
||||
href="/about"
|
||||
href={`/${currentLang}/about${currentLang === "zh" ? "/cn" : currentLang === "ja" ? "/ja" : ""}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
|
||||
>
|
||||
<Info className="h-3 w-3" />
|
||||
About
|
||||
{dict.nav.about}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
一个集成了AI功能的Next.js网页应用,与draw.io图表无缝结合。通过自然语言命令和AI辅助可视化来创建、修改和增强图表。
|
||||
|
||||
> 注:感谢 <img src="https://raw.githubusercontent.com/DayuanJiang/next-ai-draw-io/main/public/doubao-color.png" alt="" height="20" /> [字节跳动豆包](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project) 的赞助支持,本项目的 Demo 现已接入强大的 K2-thinking 模型!
|
||||
|
||||
https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
|
||||
|
||||
## 目录
|
||||
@@ -127,8 +129,6 @@ claude mcp add drawio -- npx @next-ai-drawio/mcp-server@latest
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
> 注意:由于访问量较大,演示站点目前使用 minimax-m2 模型。如需获得最佳效果,建议使用 Claude Sonnet 4.5 或 Claude Opus 4.5 自行部署。
|
||||
|
||||
> **使用自己的 API Key**:您可以使用自己的 API Key 来绕过演示站点的用量限制。点击聊天面板中的设置图标即可配置您的 Provider 和 API Key。您的 Key 仅保存在浏览器本地,不会被存储在服务器上。
|
||||
|
||||
### 使用Docker运行(推荐)
|
||||
@@ -186,7 +186,7 @@ cp env.example .env.local
|
||||
|
||||
编辑 `.env.local` 并配置您选择的提供商:
|
||||
|
||||
- 将 `AI_PROVIDER` 设置为您选择的提供商(bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow)
|
||||
- 将 `AI_PROVIDER` 设置为您选择的提供商(bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, doubao)
|
||||
- 将 `AI_MODEL` 设置为您要使用的特定模型
|
||||
- 添加您的提供商所需的API密钥
|
||||
- `TEMPERATURE`:可选的温度设置(例如 `0` 表示确定性输出)。对于不支持此参数的模型(如推理模型),请不要设置。
|
||||
@@ -206,6 +206,19 @@ npm run dev
|
||||
|
||||
## 部署
|
||||
|
||||
### 部署到腾讯云EdgeOne Pages
|
||||
|
||||
您可以通过[腾讯云EdgeOne Pages](https://pages.edgeone.ai/zh)一键部署。
|
||||
|
||||
直接点击此按钮一键部署:
|
||||
[](https://console.cloud.tencent.com/edgeone/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
|
||||
查看[腾讯云EdgeOne Pages文档](https://pages.edgeone.ai/zh/document/product-introduction)了解更多详情。
|
||||
|
||||
同时,通过腾讯云EdgeOne Pages部署,也会获得[每日免费的DeepSeek模型额度](https://edgeone.cloud.tencent.com/pages/document/169925463311781888)。
|
||||
|
||||
### 部署到Vercel
|
||||
|
||||
部署Next.js应用最简单的方式是使用Next.js创建者提供的[Vercel平台](https://vercel.com/new)。
|
||||
|
||||
查看[Next.js部署文档](https://nextjs.org/docs/app/building-your-application/deploying)了解更多详情。
|
||||
@@ -218,6 +231,7 @@ npm run dev
|
||||
|
||||
## 多提供商支持
|
||||
|
||||
- [字节跳动豆包](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project)
|
||||
- AWS Bedrock(默认)
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
@@ -268,6 +282,8 @@ public/ # 静态资源包括示例图片
|
||||
|
||||
## 支持与联系
|
||||
|
||||
**特别感谢[字节跳动豆包](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project)赞助演示站点的 API Token 使用!** 注册火山引擎 ARK 平台即可获得50万免费Token!
|
||||
|
||||
如果您觉得这个项目有用,请考虑[赞助](https://github.com/sponsors/DayuanJiang)来帮助我托管在线演示站点!
|
||||
|
||||
如需支持或咨询,请在GitHub仓库上提交issue或联系维护者:
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
AI機能とdraw.ioダイアグラムを統合したNext.jsウェブアプリケーションです。自然言語コマンドとAI支援の可視化により、ダイアグラムを作成、修正、強化できます。
|
||||
|
||||
> 注:<img src="https://raw.githubusercontent.com/DayuanJiang/next-ai-draw-io/main/public/doubao-color.png" alt="" height="20" /> [ByteDance Doubao](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project) のご支援により、デモサイトに強力な K2-thinking モデルを導入しました!
|
||||
|
||||
https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
|
||||
|
||||
## 目次
|
||||
@@ -127,8 +129,6 @@ Claudeにダイアグラムの作成を依頼:
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
> 注意:アクセス数が多いため、デモサイトでは現在 minimax-m2 モデルを使用しています。最高の結果を得るには、Claude Sonnet 4.5 または Claude Opus 4.5 でのセルフホスティングをお勧めします。
|
||||
|
||||
> **自分のAPIキーを使用**:自分のAPIキーを使用することで、デモサイトの利用制限を回避できます。チャットパネルの設定アイコンをクリックして、プロバイダーとAPIキーを設定してください。キーはブラウザのローカルに保存され、サーバーには保存されません。
|
||||
|
||||
### Dockerで実行(推奨)
|
||||
@@ -186,7 +186,7 @@ cp env.example .env.local
|
||||
|
||||
`.env.local`を編集して選択したプロバイダーを設定:
|
||||
|
||||
- `AI_PROVIDER`を選択したプロバイダーに設定(bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow)
|
||||
- `AI_PROVIDER`を選択したプロバイダーに設定(bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, doubao)
|
||||
- `AI_MODEL`を使用する特定のモデルに設定
|
||||
- プロバイダーに必要なAPIキーを追加
|
||||
- `TEMPERATURE`:オプションの温度設定(例:`0`で決定論的な出力)。温度をサポートしないモデル(推論モデルなど)では設定しないでください。
|
||||
@@ -206,6 +206,20 @@ npm run dev
|
||||
|
||||
## デプロイ
|
||||
|
||||
### EdgeOne Pagesへのデプロイ
|
||||
|
||||
[Tencent EdgeOne Pages](https://pages.edgeone.ai/)を使用してワンクリックでデプロイできます。
|
||||
|
||||
このボタンでデプロイ:
|
||||
|
||||
[](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
|
||||
詳細は[Tencent EdgeOne Pagesドキュメント](https://pages.edgeone.ai/document/deployment-overview)をご覧ください。
|
||||
|
||||
また、Tencent EdgeOne Pagesでデプロイすると、[DeepSeekモデルの毎日の無料クォータ](https://pages.edgeone.ai/document/edge-ai)が付与されます。
|
||||
|
||||
### Vercelへのデプロイ
|
||||
|
||||
Next.jsアプリをデプロイする最も簡単な方法は、Next.jsの作成者による[Vercelプラットフォーム](https://vercel.com/new)を使用することです。
|
||||
|
||||
詳細は[Next.jsデプロイメントドキュメント](https://nextjs.org/docs/app/building-your-application/deploying)をご覧ください。
|
||||
@@ -218,6 +232,7 @@ Next.jsアプリをデプロイする最も簡単な方法は、Next.jsの作成
|
||||
|
||||
## マルチプロバイダーサポート
|
||||
|
||||
- [ByteDance Doubao](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project)
|
||||
- AWS Bedrock(デフォルト)
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
@@ -268,6 +283,8 @@ public/ # サンプル画像を含む静的アセット
|
||||
|
||||
## サポート&お問い合わせ
|
||||
|
||||
**デモサイトのAPIトークン使用を支援してくださった[ByteDance Doubao](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project)に特別な感謝を申し上げます!** ARKプラットフォームに登録すると、50万トークンが無料でもらえます!
|
||||
|
||||
このプロジェクトが役に立ったら、ライブデモサイトのホスティングを支援するために[スポンサー](https://github.com/sponsors/DayuanJiang)をご検討ください!
|
||||
|
||||
サポートやお問い合わせについては、GitHubリポジトリでissueを開くか、メンテナーにご連絡ください:
|
||||
|
||||
@@ -11,6 +11,15 @@ This guide explains how to configure different AI model providers for next-ai-dr
|
||||
|
||||
## Supported Providers
|
||||
|
||||
### Doubao (ByteDance Volcengine)
|
||||
|
||||
> **Free tokens**: Register on the [Volcengine ARK platform](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project) to get 500K free tokens for all models!
|
||||
|
||||
```bash
|
||||
DOUBAO_API_KEY=your_api_key
|
||||
AI_MODEL=doubao-seed-1-8-251215 # or other Doubao model
|
||||
```
|
||||
|
||||
### Google Gemini
|
||||
|
||||
```bash
|
||||
@@ -76,6 +85,8 @@ Optional custom endpoint (defaults to the recommended domain):
|
||||
SILICONFLOW_BASE_URL=https://api.siliconflow.com/v1 # or https://api.siliconflow.cn/v1
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Azure OpenAI
|
||||
|
||||
```bash
|
||||
@@ -179,7 +190,7 @@ If you only configure **one** provider's API key, the system will automatically
|
||||
If you configure **multiple** API keys, you must explicitly set `AI_PROVIDER`:
|
||||
|
||||
```bash
|
||||
AI_PROVIDER=google # or: openai, anthropic, deepseek, siliconflow, azure, bedrock, openrouter, ollama, gateway
|
||||
AI_PROVIDER=google # or: openai, anthropic, deepseek, siliconflow, doubao, azure, bedrock, openrouter, ollama, gateway
|
||||
```
|
||||
|
||||
## Model Capability Requirements
|
||||
|
||||
270
edge-functions/api/edgeai/chat/completions.ts
Normal file
270
edge-functions/api/edgeai/chat/completions.ts
Normal file
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* EdgeOne Pages Edge Function for OpenAI-compatible Chat Completions API
|
||||
*
|
||||
* This endpoint provides an OpenAI-compatible API that can be used with
|
||||
* AI SDK's createOpenAI({ baseURL: '/api/edgeai' })
|
||||
*
|
||||
* Uses EdgeOne Edge AI's AI.chatCompletions() which now supports native tool calling.
|
||||
*/
|
||||
|
||||
import { z } from "zod"
|
||||
|
||||
// EdgeOne Pages global AI object
|
||||
declare const AI: {
|
||||
chatCompletions(options: {
|
||||
model: string
|
||||
messages: Array<{ role: string; content: string | null }>
|
||||
stream?: boolean
|
||||
max_tokens?: number
|
||||
temperature?: number
|
||||
tools?: any
|
||||
tool_choice?: any
|
||||
}): Promise<ReadableStream<Uint8Array> | any>
|
||||
}
|
||||
|
||||
const messageItemSchema = z
|
||||
.object({
|
||||
role: z.enum(["user", "assistant", "system", "tool", "function"]),
|
||||
content: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const messageSchema = z
|
||||
.object({
|
||||
messages: z.array(messageItemSchema),
|
||||
model: z.string().optional(),
|
||||
stream: z.boolean().optional(),
|
||||
tools: z.any().optional(),
|
||||
tool_choice: z.any().optional(),
|
||||
functions: z.any().optional(),
|
||||
function_call: z.any().optional(),
|
||||
temperature: z.number().optional(),
|
||||
top_p: z.number().optional(),
|
||||
max_tokens: z.number().optional(),
|
||||
presence_penalty: z.number().optional(),
|
||||
frequency_penalty: z.number().optional(),
|
||||
stop: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
response_format: z.any().optional(),
|
||||
seed: z.number().optional(),
|
||||
user: z.string().optional(),
|
||||
n: z.number().int().optional(),
|
||||
logit_bias: z.record(z.string(), z.number()).optional(),
|
||||
parallel_tool_calls: z.boolean().optional(),
|
||||
stream_options: z.any().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
// Model configuration
|
||||
const ALLOWED_MODELS = [
|
||||
"@tx/deepseek-ai/deepseek-v32",
|
||||
"@tx/deepseek-ai/deepseek-r1-0528",
|
||||
"@tx/deepseek-ai/deepseek-v3-0324",
|
||||
]
|
||||
|
||||
const MODEL_ALIASES: Record<string, string> = {
|
||||
"deepseek-v3.2": "@tx/deepseek-ai/deepseek-v32",
|
||||
"deepseek-r1-0528": "@tx/deepseek-ai/deepseek-r1-0528",
|
||||
"deepseek-v3-0324": "@tx/deepseek-ai/deepseek-v3-0324",
|
||||
}
|
||||
|
||||
const CORS_HEADERS = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
}
|
||||
|
||||
/**
|
||||
* Create standardized response with CORS headers
|
||||
*/
|
||||
function createResponse(body: any, status = 200, extraHeaders = {}): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...CORS_HEADERS,
|
||||
...extraHeaders,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle OPTIONS request for CORS preflight
|
||||
*/
|
||||
function handleOptionsRequest(): Response {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
...CORS_HEADERS,
|
||||
"Access-Control-Max-Age": "86400",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function onRequest({ request, env }: any) {
|
||||
if (request.method === "OPTIONS") {
|
||||
return handleOptionsRequest()
|
||||
}
|
||||
|
||||
request.headers.delete("accept-encoding")
|
||||
|
||||
try {
|
||||
const json = await request.clone().json()
|
||||
const parseResult = messageSchema.safeParse(json)
|
||||
|
||||
if (!parseResult.success) {
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message: parseResult.error.message,
|
||||
type: "invalid_request_error",
|
||||
},
|
||||
},
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
const { messages, model, stream, tools, tool_choice, ...extraParams } =
|
||||
parseResult.data
|
||||
|
||||
// Validate messages
|
||||
const userMessages = messages.filter(
|
||||
(message) => message.role === "user",
|
||||
)
|
||||
if (!userMessages.length) {
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message: "No user message found",
|
||||
type: "invalid_request_error",
|
||||
},
|
||||
},
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve model
|
||||
const requestedModel = model || ALLOWED_MODELS[0]
|
||||
const selectedModel = MODEL_ALIASES[requestedModel] || requestedModel
|
||||
|
||||
if (!ALLOWED_MODELS.includes(selectedModel)) {
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message: `Invalid model: ${requestedModel}.`,
|
||||
type: "invalid_request_error",
|
||||
},
|
||||
},
|
||||
429,
|
||||
)
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[EdgeOne] Model: ${selectedModel}, Tools: ${tools?.length || 0}, Stream: ${stream ?? true}`,
|
||||
)
|
||||
|
||||
try {
|
||||
const isStream = !!stream
|
||||
|
||||
// Non-streaming: return mock response for validation
|
||||
// AI.chatCompletions doesn't support non-streaming mode
|
||||
if (!isStream) {
|
||||
const mockResponse = {
|
||||
id: `chatcmpl-${Date.now()}`,
|
||||
object: "chat.completion",
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: selectedModel,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "OK",
|
||||
},
|
||||
finish_reason: "stop",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: 10,
|
||||
completion_tokens: 1,
|
||||
total_tokens: 11,
|
||||
},
|
||||
}
|
||||
return createResponse(mockResponse)
|
||||
}
|
||||
|
||||
// Build AI.chatCompletions options for streaming
|
||||
const aiOptions: any = {
|
||||
...extraParams,
|
||||
model: selectedModel,
|
||||
messages,
|
||||
stream: true,
|
||||
}
|
||||
|
||||
// Add tools if provided
|
||||
if (tools && tools.length > 0) {
|
||||
aiOptions.tools = tools
|
||||
}
|
||||
if (tool_choice !== undefined) {
|
||||
aiOptions.tool_choice = tool_choice
|
||||
}
|
||||
|
||||
const aiResponse = await AI.chatCompletions(aiOptions)
|
||||
|
||||
// Streaming response
|
||||
return new Response(aiResponse, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-store, no-transform",
|
||||
"X-Accel-Buffering": "no",
|
||||
Connection: "keep-alive",
|
||||
...CORS_HEADERS,
|
||||
},
|
||||
})
|
||||
} catch (error: any) {
|
||||
// Handle EdgeOne specific errors
|
||||
try {
|
||||
const message = JSON.parse(error.message)
|
||||
if (message.code === 14020) {
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message:
|
||||
"The daily public quota has been exhausted. After deployment, you can enjoy a personal daily exclusive quota.",
|
||||
type: "rate_limit_error",
|
||||
},
|
||||
},
|
||||
429,
|
||||
)
|
||||
}
|
||||
return createResponse(
|
||||
{ error: { message: error.message, type: "api_error" } },
|
||||
500,
|
||||
)
|
||||
} catch {
|
||||
// Not a JSON error message
|
||||
}
|
||||
|
||||
console.error("[EdgeOne] AI error:", error.message)
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message: error.message || "AI service error",
|
||||
type: "api_error",
|
||||
},
|
||||
},
|
||||
500,
|
||||
)
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("[EdgeOne] Request error:", error.message)
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message: "Request processing failed",
|
||||
type: "server_error",
|
||||
details: error.message,
|
||||
},
|
||||
},
|
||||
500,
|
||||
)
|
||||
}
|
||||
}
|
||||
5
edgeone.json
Normal file
5
edgeone.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"nodeFunctionsConfig": {
|
||||
"maxDuration": 120
|
||||
}
|
||||
}
|
||||
0
electron.d.ts → electron/electron.d.ts
vendored
0
electron.d.ts → electron/electron.d.ts
vendored
@@ -72,6 +72,10 @@ AI_MODEL=global.anthropic.claude-sonnet-4-5-20250929-v1:0
|
||||
# SGLANG_API_KEY=your-sglang-api-key
|
||||
# SGLANG_BASE_URL=http://127.0.0.1:8000/v1 # Your SGLang endpoint
|
||||
|
||||
# ByteDance Doubao Configuration (via Volcengine)
|
||||
# DOUBAO_API_KEY=your-doubao-api-key
|
||||
# DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3 # ByteDance Volcengine endpoint
|
||||
|
||||
# Vercel AI Gateway Configuration
|
||||
# Get your API key from: https://vercel.com/ai-gateway
|
||||
# Model format: "provider/model" e.g., "openai/gpt-4o", "anthropic/claude-sonnet-4-5"
|
||||
|
||||
@@ -21,6 +21,8 @@ export type ProviderName =
|
||||
| "siliconflow"
|
||||
| "sglang"
|
||||
| "gateway"
|
||||
| "edgeone"
|
||||
| "doubao"
|
||||
|
||||
interface ModelConfig {
|
||||
model: any
|
||||
@@ -39,6 +41,8 @@ export interface ClientOverrides {
|
||||
awsSecretAccessKey?: string | null
|
||||
awsRegion?: string | null
|
||||
awsSessionToken?: string | null
|
||||
// Custom headers (e.g., for EdgeOne cookie auth)
|
||||
headers?: Record<string, string>
|
||||
}
|
||||
|
||||
// Providers that can be used with client-provided API keys
|
||||
@@ -53,6 +57,8 @@ const ALLOWED_CLIENT_PROVIDERS: ProviderName[] = [
|
||||
"siliconflow",
|
||||
"sglang",
|
||||
"gateway",
|
||||
"edgeone",
|
||||
"doubao",
|
||||
]
|
||||
|
||||
// Bedrock provider options for Anthropic beta features
|
||||
@@ -346,7 +352,8 @@ function buildProviderOptions(
|
||||
case "openrouter":
|
||||
case "siliconflow":
|
||||
case "sglang":
|
||||
case "gateway": {
|
||||
case "gateway":
|
||||
case "doubao": {
|
||||
// These providers don't have reasoning configs in AI SDK yet
|
||||
// Gateway passes through to underlying providers which handle their own configs
|
||||
break
|
||||
@@ -372,6 +379,8 @@ const PROVIDER_ENV_VARS: Record<ProviderName, string | null> = {
|
||||
siliconflow: "SILICONFLOW_API_KEY",
|
||||
sglang: "SGLANG_API_KEY",
|
||||
gateway: "AI_GATEWAY_API_KEY",
|
||||
edgeone: null, // No credentials needed - uses EdgeOne Edge AI
|
||||
doubao: "DOUBAO_API_KEY",
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -459,7 +468,12 @@ export function getAIModel(overrides?: ClientOverrides): ModelConfig {
|
||||
// SECURITY: Prevent SSRF attacks (GHSA-9qf7-mprq-9qgm)
|
||||
// If a custom baseUrl is provided, an API key MUST also be provided.
|
||||
// This prevents attackers from redirecting server API keys to malicious endpoints.
|
||||
if (overrides?.baseUrl && !overrides?.apiKey) {
|
||||
// Exception: EdgeOne provider doesn't require API key (uses Edge AI runtime)
|
||||
if (
|
||||
overrides?.baseUrl &&
|
||||
!overrides?.apiKey &&
|
||||
overrides?.provider !== "edgeone"
|
||||
) {
|
||||
throw new Error(
|
||||
`API key is required when using a custom base URL. ` +
|
||||
`Please provide your own API key in Settings.`,
|
||||
@@ -836,9 +850,38 @@ export function getAIModel(overrides?: ClientOverrides): ModelConfig {
|
||||
break
|
||||
}
|
||||
|
||||
case "edgeone": {
|
||||
// EdgeOne Pages Edge AI - uses OpenAI-compatible API
|
||||
// AI SDK appends /chat/completions to baseURL
|
||||
// /api/edgeai + /chat/completions = /api/edgeai/chat/completions
|
||||
const baseURL = overrides?.baseUrl || "/api/edgeai"
|
||||
const edgeoneProvider = createOpenAI({
|
||||
apiKey: "edgeone", // Dummy key - EdgeOne doesn't require API key
|
||||
baseURL,
|
||||
// Pass cookies for EdgeOne Pages authentication (eo_token, eo_time)
|
||||
...(overrides?.headers && { headers: overrides.headers }),
|
||||
})
|
||||
model = edgeoneProvider.chat(modelId)
|
||||
break
|
||||
}
|
||||
|
||||
case "doubao": {
|
||||
const apiKey = overrides?.apiKey || process.env.DOUBAO_API_KEY
|
||||
const baseURL =
|
||||
overrides?.baseUrl ||
|
||||
process.env.DOUBAO_BASE_URL ||
|
||||
"https://ark.cn-beijing.volces.com/api/v3"
|
||||
const doubaoProvider = createDeepSeek({
|
||||
apiKey,
|
||||
baseURL,
|
||||
})
|
||||
model = doubaoProvider(modelId)
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(
|
||||
`Unknown AI provider: ${provider}. Supported providers: bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, sglang, gateway`,
|
||||
`Unknown AI provider: ${provider}. Supported providers: bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, sglang, gateway, edgeone, doubao`,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
"copyResponse": "Copy response",
|
||||
"copied": "Copied!",
|
||||
"failedToCopy": "Failed to copy",
|
||||
"failedToCopyDetail": "Failed to copy message. Please copy manually or check clipboard permissions.",
|
||||
"goodResponse": "Good response",
|
||||
"badResponse": "Bad response",
|
||||
"clickToEdit": "Click to edit",
|
||||
@@ -141,6 +142,7 @@
|
||||
"invalidAccessCode": "Invalid or missing access code. Please configure it in Settings.",
|
||||
"networkError": "Network error. Please check your connection.",
|
||||
"retryLimit": "Auto-retry limit reached ({max}). Please try again manually.",
|
||||
"continuationRetryLimit": "Continuation retry limit reached ({max}). The diagram may be too complex.",
|
||||
"validationFailed": "Diagram validation failed. Please try regenerating.",
|
||||
"malformedXml": "AI generated invalid diagram XML. Please try regenerating.",
|
||||
"failedToProcess": "Failed to process diagram. Please try regenerating.",
|
||||
@@ -149,7 +151,9 @@
|
||||
"failedToRestore": "Failed to restore from localStorage",
|
||||
"failedToPersist": "Failed to persist state before unload",
|
||||
"failedToExport": "Error fetching chart data",
|
||||
"failedToLoadExample": "Error loading example image"
|
||||
"failedToLoadExample": "Error loading example image",
|
||||
"failedToRecordFeedback": "Failed to record your feedback. Please try again.",
|
||||
"storageUpdateFailed": "Chat cleared but browser storage could not be updated"
|
||||
},
|
||||
"quota": {
|
||||
"dailyLimit": "Daily Quota Reached",
|
||||
@@ -157,10 +161,12 @@
|
||||
"tpmLimit": "Rate Limit",
|
||||
"tpmMessage": "Too many requests. Please wait a moment.",
|
||||
"tpmMessageDetailed": "Rate limit reached ({limit} tokens/min). Please wait {seconds} seconds before sending another request.",
|
||||
"messageApi": "Oops — you've reached the daily API limit for this demo! As an indie developer covering all the API costs myself, I have to set these limits to keep things sustainable.",
|
||||
"messageToken": "Oops — you've reached the daily token limit for this demo! As an indie developer covering all the API costs myself, I have to set these limits to keep things sustainable.",
|
||||
"messageApi": "Looks like you've reached today's demo limit. We're thrilled you're enjoying it, and while ByteDance Doubao generously sponsors this demo, we've had to set a few boundaries to keep things fair for everyone.",
|
||||
"messageToken": "Looks like you've reached today's token limit. We're thrilled you're enjoying it, and while ByteDance Doubao generously sponsors this demo, we've had to set a few boundaries to keep things fair for everyone.",
|
||||
"tip": "<strong>Tip:</strong> You can use your own API key (click the Settings icon) or self-host the project to bypass these limits.",
|
||||
"reset": "Your limit resets tomorrow. Thanks for understanding!",
|
||||
"reset": "Your limit resets tomorrow. Thanks for understanding.",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">Register here</a> to get 500K free tokens per model (including Doubao, DeepSeek and Kimi), then configure your API key in model settings.",
|
||||
"configModel": "Use Your API Key",
|
||||
"selfHost": "Self-host",
|
||||
"sponsor": "Sponsor",
|
||||
"learnMore": "Learn more →",
|
||||
@@ -184,6 +190,21 @@
|
||||
"thoughtFor": "Thought for {duration} seconds",
|
||||
"thoughtBrief": "Thought for a few seconds"
|
||||
},
|
||||
"dev": {
|
||||
"title": "Dev: XML Streaming Simulator",
|
||||
"preset": "Preset:",
|
||||
"selectPreset": "Select a preset...",
|
||||
"clear": "Clear",
|
||||
"placeholder": "Paste mxCell XML here or select a preset...",
|
||||
"interval": "Interval:",
|
||||
"chars": "Chars:",
|
||||
"streaming": "Streaming...",
|
||||
"simulate": "Simulate",
|
||||
"stop": "Stop",
|
||||
"testQuotaToast": "Test Quota Toast",
|
||||
"simulatingMessage": "[Dev] Simulating XML streaming",
|
||||
"successMessage": "Successfully displayed the diagram."
|
||||
},
|
||||
"about": {
|
||||
"modelChange": "Model Change & Usage Limits",
|
||||
"walletCrying": "(Or: Why My Wallet is Crying)",
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
"copyResponse": "応答をコピー",
|
||||
"copied": "コピーしました!",
|
||||
"failedToCopy": "コピーに失敗しました",
|
||||
"failedToCopyDetail": "メッセージのコピーに失敗しました。手動でコピーするか、クリップボードの権限を確認してください。",
|
||||
"goodResponse": "良い応答",
|
||||
"badResponse": "悪い応答",
|
||||
"clickToEdit": "クリックして編集",
|
||||
@@ -141,6 +142,7 @@
|
||||
"invalidAccessCode": "無効または欠落したアクセスコード。設定で入力してください。",
|
||||
"networkError": "ネットワークエラー。接続を確認してください。",
|
||||
"retryLimit": "自動再試行制限に達しました({max})。手動で再試行してください。",
|
||||
"continuationRetryLimit": "継続再試行制限に達しました({max})。ダイアグラムが複雑すぎる可能性があります。",
|
||||
"validationFailed": "ダイアグラムの検証に失敗しました。再生成してみてください。",
|
||||
"malformedXml": "AI が無効なダイアグラム XML を生成しました。再生成してみてください。",
|
||||
"failedToProcess": "ダイアグラムの処理に失敗しました。再生成してみてください。",
|
||||
@@ -149,7 +151,9 @@
|
||||
"failedToRestore": "localStorage からの復元に失敗しました",
|
||||
"failedToPersist": "アンロード前の状態の永続化に失敗しました",
|
||||
"failedToExport": "チャートデータの取得エラー",
|
||||
"failedToLoadExample": "例の画像の読み込みエラー"
|
||||
"failedToLoadExample": "例の画像の読み込みエラー",
|
||||
"failedToRecordFeedback": "フィードバックの記録に失敗しました。もう一度お試しください。",
|
||||
"storageUpdateFailed": "チャットはクリアされましたが、ブラウザストレージを更新できませんでした"
|
||||
},
|
||||
"quota": {
|
||||
"dailyLimit": "1日の割当量に達しました",
|
||||
@@ -157,10 +161,12 @@
|
||||
"tpmLimit": "レート制限",
|
||||
"tpmMessage": "リクエストが多すぎます。しばらくお待ちください。",
|
||||
"tpmMessageDetailed": "レート制限に達しました({limit}トークン/分)。{seconds}秒待ってからもう一度リクエストしてください。",
|
||||
"messageApi": "おっと — このデモの1日の API 制限に達しました!個人開発者として API コストをすべて負担しているため、持続可能性を保つためにこれらの制限を設定する必要があります。",
|
||||
"messageToken": "おっと — このデモの1日のトークン制限に達しました!個人開発者として API コストをすべて負担しているため、持続可能性を保つためにこれらの制限を設定する必要があります。",
|
||||
"messageApi": "今日のデモ利用上限に達してしまったようです。楽しんでいただけて本当に嬉しいです。このデモはByteDance Doubaoのご厚意により提供されていますが、皆様に公平にご利用いただくため、少し制限を設けさせていただいております。",
|
||||
"messageToken": "今日のトークン利用上限に達してしまったようです。楽しんでいただけて本当に嬉しいです。このデモはByteDance Doubaoのご厚意により提供されていますが、皆様に公平にご利用いただくため、少し制限を設けさせていただいております。",
|
||||
"tip": "<strong>ヒント:</strong>独自の API キーを使用する(設定アイコンをクリック)か、プロジェクトをセルフホストしてこれらの制限を回避できます。",
|
||||
"reset": "制限は明日リセットされます。ご理解ありがとうございます!",
|
||||
"reset": "制限は明日リセットされます。ご理解ありがとうございます。",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">こちらから登録</a>すると、各モデル(Doubao、DeepSeek、Kimi含む)で50万トークンを無料で取得できます。モデル設定でAPIキーを設定してください。",
|
||||
"configModel": "APIキーを使用",
|
||||
"selfHost": "セルフホスト",
|
||||
"sponsor": "スポンサー",
|
||||
"learnMore": "詳細 →",
|
||||
@@ -184,6 +190,21 @@
|
||||
"thoughtFor": "{duration} 秒考えました",
|
||||
"thoughtBrief": "数秒考えました"
|
||||
},
|
||||
"dev": {
|
||||
"title": "開発:XMLストリーミングシミュレーター",
|
||||
"preset": "プリセット:",
|
||||
"selectPreset": "プリセットを選択...",
|
||||
"clear": "クリア",
|
||||
"placeholder": "ここに mxCell XML を貼り付けるか、プリセットを選択...",
|
||||
"interval": "間隔:",
|
||||
"chars": "文字:",
|
||||
"streaming": "ストリーミング中...",
|
||||
"simulate": "シミュレート",
|
||||
"stop": "停止",
|
||||
"testQuotaToast": "クォータトーストをテスト",
|
||||
"simulatingMessage": "[開発] XMLストリーミングをシミュレート中",
|
||||
"successMessage": "ダイアグラムの表示に成功しました。"
|
||||
},
|
||||
"about": {
|
||||
"modelChange": "モデル変更と利用制限について",
|
||||
"walletCrying": "(別名:お財布が悲鳴を上げています)",
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
"copyResponse": "复制响应",
|
||||
"copied": "已复制!",
|
||||
"failedToCopy": "复制失败",
|
||||
"failedToCopyDetail": "复制消息失败。请手动复制或检查剪贴板权限。",
|
||||
"goodResponse": "有帮助",
|
||||
"badResponse": "无帮助",
|
||||
"clickToEdit": "点击编辑",
|
||||
@@ -141,6 +142,7 @@
|
||||
"invalidAccessCode": "无效或缺少访问码。请在设置中配置。",
|
||||
"networkError": "网络错误。请检查您的连接。",
|
||||
"retryLimit": "已达到自动重试限制({max})。请手动重试。",
|
||||
"continuationRetryLimit": "已达到继续重试限制({max})。图表可能过于复杂。",
|
||||
"validationFailed": "图表验证失败。请尝试重新生成。",
|
||||
"malformedXml": "AI 生成的图表 XML 无效。请尝试重新生成。",
|
||||
"failedToProcess": "无法处理图表。请尝试重新生成。",
|
||||
@@ -149,7 +151,9 @@
|
||||
"failedToRestore": "无法从 localStorage 恢复",
|
||||
"failedToPersist": "卸载前无法持久化状态",
|
||||
"failedToExport": "获取图表数据时出错",
|
||||
"failedToLoadExample": "加载示例图片时出错"
|
||||
"failedToLoadExample": "加载示例图片时出错",
|
||||
"failedToRecordFeedback": "记录您的反馈失败。请重试。",
|
||||
"storageUpdateFailed": "聊天已清除,但无法更新浏览器存储"
|
||||
},
|
||||
"quota": {
|
||||
"dailyLimit": "已达每日配额",
|
||||
@@ -157,10 +161,12 @@
|
||||
"tpmLimit": "速率限制",
|
||||
"tpmMessage": "请求过多。请稍等片刻。",
|
||||
"tpmMessageDetailed": "达到速率限制({limit} 令牌/分钟)。请等待 {seconds} 秒后再发送请求。",
|
||||
"messageApi": "糟糕 — 您已达到此演示的每日 API 限制!作为一名独立开发者,我自己承担所有 API 费用,因此必须设置这些限制以保持可持续性。",
|
||||
"messageToken": "糟糕 — 您已达到此演示的每日令牌限制!作为一名独立开发者,我自己承担所有 API 费用,因此必须设置这些限制以保持可持续性。",
|
||||
"messageApi": "看来您今天的体验次数已达上限。非常高兴您玩得开心,虽然本项目由字节跳动豆包慷慨赞助,但为了确保大家都能公平使用,我们不得不对使用量做一点小小的限制。",
|
||||
"messageToken": "看来您今天的 Token 用量已达上限。非常高兴您玩得开心,虽然本项目由字节跳动豆包慷慨赞助,但为了确保大家都能公平使用,我们不得不对使用量做一点小小的限制。",
|
||||
"tip": "<strong>提示:</strong>您可以使用自己的 API 密钥(点击设置图标)或自托管项目来绕过这些限制。",
|
||||
"reset": "您的限制将在明天重置。感谢您的理解!",
|
||||
"reset": "您的限制将在明天重置。感谢您的理解。",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">点击此处注册</a>可获得每个模型 50 万免费 Token(包括豆包、DeepSeek 和 Kimi),然后在模型设置中配置您的 API Key。",
|
||||
"configModel": "使用您的密钥",
|
||||
"selfHost": "自托管",
|
||||
"sponsor": "赞助",
|
||||
"learnMore": "了解更多 →",
|
||||
@@ -184,6 +190,21 @@
|
||||
"thoughtFor": "思考了 {duration} 秒",
|
||||
"thoughtBrief": "思考了几秒钟"
|
||||
},
|
||||
"dev": {
|
||||
"title": "开发:XML 流式模拟器",
|
||||
"preset": "预设:",
|
||||
"selectPreset": "选择预设...",
|
||||
"clear": "清除",
|
||||
"placeholder": "在此粘贴 mxCell XML 或选择预设...",
|
||||
"interval": "间隔:",
|
||||
"chars": "字符:",
|
||||
"streaming": "流式传输中...",
|
||||
"simulate": "模拟",
|
||||
"stop": "停止",
|
||||
"testQuotaToast": "测试配额提示",
|
||||
"simulatingMessage": "[开发] 模拟 XML 流式传输",
|
||||
"successMessage": "成功显示图表。"
|
||||
},
|
||||
"about": {
|
||||
"modelChange": "模型变更与用量限制",
|
||||
"walletCrying": "(别名:我的钱包顶不住了)",
|
||||
|
||||
@@ -276,7 +276,7 @@ edit_diagram uses ID-based operations to modify cells directly by their id attri
|
||||
**Operations:**
|
||||
- **update**: Replace an existing cell. Provide cell_id and new_xml.
|
||||
- **add**: Add a new cell. Provide cell_id (new unique id) and new_xml.
|
||||
- **delete**: Remove a cell. Only cell_id is needed.
|
||||
- **delete**: Remove a cell. **Cascade is automatic**: children AND edges (source/target) are auto-deleted. Only specify ONE cell_id.
|
||||
|
||||
**Input Format:**
|
||||
\`\`\`json
|
||||
@@ -301,9 +301,9 @@ Add new shape:
|
||||
{"operations": [{"operation": "add", "cell_id": "new1", "new_xml": "<mxCell id=\\"new1\\" value=\\"New Box\\" style=\\"rounded=1;fillColor=#dae8fc;\\" vertex=\\"1\\" parent=\\"1\\">\\n <mxGeometry x=\\"400\\" y=\\"200\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/>\\n</mxCell>"}]}
|
||||
\`\`\`
|
||||
|
||||
Delete cell:
|
||||
Delete container (children & edges auto-deleted):
|
||||
\`\`\`json
|
||||
{"operations": [{"operation": "delete", "cell_id": "5"}]}
|
||||
{"operations": [{"operation": "delete", "cell_id": "2"}]}
|
||||
\`\`\`
|
||||
|
||||
**Error Recovery:**
|
||||
|
||||
@@ -9,7 +9,10 @@ export type ProviderName =
|
||||
| "openrouter"
|
||||
| "deepseek"
|
||||
| "siliconflow"
|
||||
| "sglang"
|
||||
| "gateway"
|
||||
| "edgeone"
|
||||
| "doubao"
|
||||
|
||||
// Individual model configuration
|
||||
export interface ModelConfig {
|
||||
@@ -78,7 +81,16 @@ export const PROVIDER_INFO: Record<
|
||||
label: "SiliconFlow",
|
||||
defaultBaseUrl: "https://api.siliconflow.com/v1",
|
||||
},
|
||||
sglang: {
|
||||
label: "SGLang",
|
||||
defaultBaseUrl: "http://127.0.0.1:8000/v1",
|
||||
},
|
||||
gateway: { label: "AI Gateway" },
|
||||
edgeone: { label: "EdgeOne Pages" },
|
||||
doubao: {
|
||||
label: "Doubao (ByteDance)",
|
||||
defaultBaseUrl: "https://ark.cn-beijing.volces.com/api/v3",
|
||||
},
|
||||
}
|
||||
|
||||
// Suggested models per provider for quick add
|
||||
@@ -198,6 +210,10 @@ export const SUGGESTED_MODELS: Record<ProviderName, string[]> = {
|
||||
"Qwen/Qwen2.5-7B-Instruct",
|
||||
"Qwen/Qwen2-VL-72B-Instruct",
|
||||
],
|
||||
sglang: [
|
||||
// SGLang is OpenAI-compatible, models depend on deployment
|
||||
"default",
|
||||
],
|
||||
gateway: [
|
||||
"openai/gpt-4o",
|
||||
"openai/gpt-4o-mini",
|
||||
@@ -205,6 +221,16 @@ export const SUGGESTED_MODELS: Record<ProviderName, string[]> = {
|
||||
"anthropic/claude-3-5-sonnet",
|
||||
"google/gemini-2.0-flash",
|
||||
],
|
||||
edgeone: ["@tx/deepseek-ai/deepseek-v32"],
|
||||
doubao: [
|
||||
// ByteDance Doubao models
|
||||
"doubao-1.5-thinking-pro-250415",
|
||||
"doubao-1.5-thinking-pro-m-250428",
|
||||
"doubao-1.5-pro-32k-250115",
|
||||
"doubao-1.5-pro-256k-250115",
|
||||
"doubao-pro-32k-241215",
|
||||
"doubao-pro-256k-241215",
|
||||
],
|
||||
}
|
||||
|
||||
// Helper to generate UUID
|
||||
|
||||
@@ -10,6 +10,7 @@ export interface QuotaConfig {
|
||||
dailyRequestLimit: number
|
||||
dailyTokenLimit: number
|
||||
tpmLimit: number
|
||||
onConfigModel?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,7 +23,8 @@ export function useQuotaManager(config: QuotaConfig): {
|
||||
showTokenLimitToast: (used?: number, limit?: number) => void
|
||||
showTPMLimitToast: (limit?: number) => void
|
||||
} {
|
||||
const { dailyRequestLimit, dailyTokenLimit, tpmLimit } = config
|
||||
const { dailyRequestLimit, dailyTokenLimit, tpmLimit, onConfigModel } =
|
||||
config
|
||||
const dict = useDictionary()
|
||||
|
||||
// Show quota limit toast (request-based)
|
||||
@@ -34,12 +36,13 @@ export function useQuotaManager(config: QuotaConfig): {
|
||||
used={used ?? dailyRequestLimit}
|
||||
limit={limit ?? dailyRequestLimit}
|
||||
onDismiss={() => toast.dismiss(t)}
|
||||
onConfigModel={onConfigModel}
|
||||
/>
|
||||
),
|
||||
{ duration: 15000 },
|
||||
)
|
||||
},
|
||||
[dailyRequestLimit],
|
||||
[dailyRequestLimit, onConfigModel],
|
||||
)
|
||||
|
||||
// Show token limit toast
|
||||
@@ -52,12 +55,13 @@ export function useQuotaManager(config: QuotaConfig): {
|
||||
used={used ?? dailyTokenLimit}
|
||||
limit={limit ?? dailyTokenLimit}
|
||||
onDismiss={() => toast.dismiss(t)}
|
||||
onConfigModel={onConfigModel}
|
||||
/>
|
||||
),
|
||||
{ duration: 15000 },
|
||||
)
|
||||
},
|
||||
[dailyTokenLimit],
|
||||
[dailyTokenLimit, onConfigModel],
|
||||
)
|
||||
|
||||
// Show TPM limit toast
|
||||
|
||||
77
lib/utils.ts
77
lib/utils.ts
@@ -633,32 +633,77 @@ export function applyDiagramOperations(
|
||||
// Add to map
|
||||
cellMap.set(op.cell_id, importedNode)
|
||||
} else if (op.operation === "delete") {
|
||||
const existingCell = cellMap.get(op.cell_id)
|
||||
if (!existingCell) {
|
||||
// Protect root cells from deletion
|
||||
if (op.cell_id === "0" || op.cell_id === "1") {
|
||||
errors.push({
|
||||
type: "delete",
|
||||
cellId: op.cell_id,
|
||||
message: `Cell with id="${op.cell_id}" not found`,
|
||||
message: `Cannot delete root cell "${op.cell_id}"`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for edges referencing this cell (warning only, still delete)
|
||||
const referencingEdges = root.querySelectorAll(
|
||||
`mxCell[source="${op.cell_id}"], mxCell[target="${op.cell_id}"]`,
|
||||
)
|
||||
if (referencingEdges.length > 0) {
|
||||
const edgeIds = Array.from(referencingEdges)
|
||||
.map((e) => e.getAttribute("id"))
|
||||
.join(", ")
|
||||
console.warn(
|
||||
`[applyDiagramOperations] Deleting cell "${op.cell_id}" which is referenced by edges: ${edgeIds}`,
|
||||
const existingCell = cellMap.get(op.cell_id)
|
||||
if (!existingCell) {
|
||||
// Cell not found - might have been cascade-deleted by a previous operation
|
||||
// Skip silently instead of erroring (AI may redundantly list children/edges)
|
||||
continue
|
||||
}
|
||||
|
||||
// Cascade delete: collect all cells to delete (children + edges + self)
|
||||
const cellsToDelete = new Set<string>()
|
||||
|
||||
// Recursive function to find all descendants
|
||||
const collectDescendants = (cellId: string) => {
|
||||
if (cellsToDelete.has(cellId)) return
|
||||
cellsToDelete.add(cellId)
|
||||
|
||||
// Find children (cells where parent === cellId)
|
||||
const children = root.querySelectorAll(
|
||||
`mxCell[parent="${cellId}"]`,
|
||||
)
|
||||
children.forEach((child) => {
|
||||
const childId = child.getAttribute("id")
|
||||
if (childId && childId !== "0" && childId !== "1") {
|
||||
collectDescendants(childId)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Collect the target cell and all its descendants
|
||||
collectDescendants(op.cell_id)
|
||||
|
||||
// Find edges referencing any of the cells to be deleted
|
||||
// Also recursively collect children of those edges (e.g., edge labels)
|
||||
for (const cellId of cellsToDelete) {
|
||||
const referencingEdges = root.querySelectorAll(
|
||||
`mxCell[source="${cellId}"], mxCell[target="${cellId}"]`,
|
||||
)
|
||||
referencingEdges.forEach((edge) => {
|
||||
const edgeId = edge.getAttribute("id")
|
||||
// Protect root cells from being added via edge references
|
||||
if (edgeId && edgeId !== "0" && edgeId !== "1") {
|
||||
// Recurse to collect edge's children (like labels)
|
||||
collectDescendants(edgeId)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Log what will be deleted
|
||||
if (cellsToDelete.size > 1) {
|
||||
console.log(
|
||||
`[applyDiagramOperations] Cascade delete "${op.cell_id}" → deleting ${cellsToDelete.size} cells: ${Array.from(cellsToDelete).join(", ")}`,
|
||||
)
|
||||
}
|
||||
|
||||
// Remove the node
|
||||
existingCell.parentNode?.removeChild(existingCell)
|
||||
cellMap.delete(op.cell_id)
|
||||
// Delete all collected cells
|
||||
for (const cellId of cellsToDelete) {
|
||||
const cell = cellMap.get(cellId)
|
||||
if (cell) {
|
||||
cell.parentNode?.removeChild(cell)
|
||||
cellMap.delete(cellId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
3113
package-lock.json
generated
3113
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
15
package.json
15
package.json
@@ -21,11 +21,11 @@
|
||||
"electron:compile": "npx esbuild electron/main/index.ts electron/preload/index.ts electron/preload/settings.ts --bundle --platform=node --outdir=dist-electron --external:electron --sourcemap --packages=external && npx shx cp -r electron/settings dist-electron/",
|
||||
"electron:start": "npx cross-env NODE_ENV=development npx electron .",
|
||||
"electron:prepare": "node scripts/prepare-electron-build.mjs",
|
||||
"dist": "npm run electron:build && npm run electron:prepare && npx electron-builder",
|
||||
"dist:mac": "npm run electron:build && npm run electron:prepare && npx electron-builder --mac",
|
||||
"dist:win": "npm run electron:build && npm run electron:prepare && npx electron-builder --win",
|
||||
"dist:linux": "npm run electron:build && npm run electron:prepare && npx electron-builder --linux",
|
||||
"dist:all": "npm run electron:build && npm run electron:prepare && npx electron-builder --mac --win --linux"
|
||||
"dist": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml",
|
||||
"dist:mac": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --mac",
|
||||
"dist:win": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --win",
|
||||
"dist:linux": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --linux",
|
||||
"dist:all": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --mac --win --linux"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/amazon-bedrock": "^4.0.1",
|
||||
@@ -88,6 +88,11 @@
|
||||
"unpdf": "^1.4.0",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"lightningcss": "^1.30.2",
|
||||
"lightningcss-linux-x64-gnu": "^1.30.2",
|
||||
"@tailwindcss/oxide-linux-x64-gnu": "^4.1.18"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{js,ts,jsx,tsx,json,css}": [
|
||||
"biome check --write --no-errors-on-unmatched",
|
||||
|
||||
@@ -97,7 +97,7 @@ Use the standard MCP configuration with:
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `start_session` | Opens browser with real-time diagram preview |
|
||||
| `display_diagram` | Create a new diagram from XML |
|
||||
| `create_new_diagram` | Create a new diagram from XML (requires `xml` argument) |
|
||||
| `edit_diagram` | Edit diagram by ID-based operations (update/add/delete cells) |
|
||||
| `get_diagram` | Get the current diagram XML |
|
||||
| `export_diagram` | Save diagram to a `.drawio` file |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@next-ai-drawio/mcp-server",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.10",
|
||||
"description": "MCP server for Next AI Draw.io - AI-powered diagram generation with real-time browser preview",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -182,32 +182,77 @@ export function applyDiagramOperations(
|
||||
// Add to map
|
||||
cellMap.set(op.cell_id, importedNode)
|
||||
} else if (op.operation === "delete") {
|
||||
const existingCell = cellMap.get(op.cell_id)
|
||||
if (!existingCell) {
|
||||
// Protect root cells from deletion
|
||||
if (op.cell_id === "0" || op.cell_id === "1") {
|
||||
errors.push({
|
||||
type: "delete",
|
||||
cellId: op.cell_id,
|
||||
message: `Cell with id="${op.cell_id}" not found`,
|
||||
message: `Cannot delete root cell "${op.cell_id}"`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for edges referencing this cell (warning only, still delete)
|
||||
const referencingEdges = root.querySelectorAll(
|
||||
`mxCell[source="${op.cell_id}"], mxCell[target="${op.cell_id}"]`,
|
||||
)
|
||||
if (referencingEdges.length > 0) {
|
||||
const edgeIds = Array.from(referencingEdges)
|
||||
.map((e) => e.getAttribute("id"))
|
||||
.join(", ")
|
||||
console.warn(
|
||||
`[applyDiagramOperations] Deleting cell "${op.cell_id}" which is referenced by edges: ${edgeIds}`,
|
||||
const existingCell = cellMap.get(op.cell_id)
|
||||
if (!existingCell) {
|
||||
// Cell not found - might have been cascade-deleted by a previous operation
|
||||
// Skip silently instead of erroring (AI may redundantly list children/edges)
|
||||
continue
|
||||
}
|
||||
|
||||
// Cascade delete: collect all cells to delete (children + edges + self)
|
||||
const cellsToDelete = new Set<string>()
|
||||
|
||||
// Recursive function to find all descendants
|
||||
const collectDescendants = (cellId: string) => {
|
||||
if (cellsToDelete.has(cellId)) return
|
||||
cellsToDelete.add(cellId)
|
||||
|
||||
// Find children (cells where parent === cellId)
|
||||
const children = root.querySelectorAll(
|
||||
`mxCell[parent="${cellId}"]`,
|
||||
)
|
||||
children.forEach((child) => {
|
||||
const childId = child.getAttribute("id")
|
||||
if (childId && childId !== "0" && childId !== "1") {
|
||||
collectDescendants(childId)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Collect the target cell and all its descendants
|
||||
collectDescendants(op.cell_id)
|
||||
|
||||
// Find edges referencing any of the cells to be deleted
|
||||
// Also recursively collect children of those edges (e.g., edge labels)
|
||||
for (const cellId of cellsToDelete) {
|
||||
const referencingEdges = root.querySelectorAll(
|
||||
`mxCell[source="${cellId}"], mxCell[target="${cellId}"]`,
|
||||
)
|
||||
referencingEdges.forEach((edge) => {
|
||||
const edgeId = edge.getAttribute("id")
|
||||
// Protect root cells from being added via edge references
|
||||
if (edgeId && edgeId !== "0" && edgeId !== "1") {
|
||||
// Recurse to collect edge's children (like labels)
|
||||
collectDescendants(edgeId)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Log what will be deleted
|
||||
if (cellsToDelete.size > 1) {
|
||||
console.log(
|
||||
`[applyDiagramOperations] Cascade delete "${op.cell_id}" → deleting ${cellsToDelete.size} cells: ${Array.from(cellsToDelete).join(", ")}`,
|
||||
)
|
||||
}
|
||||
|
||||
// Remove the node
|
||||
existingCell.parentNode?.removeChild(existingCell)
|
||||
cellMap.delete(op.cell_id)
|
||||
// Delete all collected cells
|
||||
for (const cellId of cellsToDelete) {
|
||||
const cell = cellMap.get(cellId)
|
||||
if (cell) {
|
||||
cell.parentNode?.removeChild(cell)
|
||||
cellMap.delete(cellId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ server.prompt(
|
||||
|
||||
## Creating a New Diagram
|
||||
1. Call start_session to open the browser preview
|
||||
2. Use display_diagram with complete mxGraphModel XML to create a new diagram
|
||||
2. Use create_new_diagram with complete mxGraphModel XML to create a new diagram
|
||||
|
||||
## Adding Elements to Existing Diagram
|
||||
1. Use edit_diagram with "add" operation
|
||||
@@ -91,7 +91,7 @@ server.prompt(
|
||||
3. For update, provide the cell_id and complete new mxCell XML
|
||||
|
||||
## Important Notes
|
||||
- display_diagram REPLACES the entire diagram - only use for new diagrams
|
||||
- create_new_diagram REPLACES the entire diagram - only use for new diagrams
|
||||
- edit_diagram PRESERVES user's manual changes (fetches browser state first)
|
||||
- Always use unique cell_ids when adding elements (e.g., "shape-1", "arrow-2")`,
|
||||
},
|
||||
@@ -150,19 +150,59 @@ server.registerTool(
|
||||
},
|
||||
)
|
||||
|
||||
// Tool: display_diagram
|
||||
// Tool: create_new_diagram
|
||||
server.registerTool(
|
||||
"display_diagram",
|
||||
"create_new_diagram",
|
||||
{
|
||||
description:
|
||||
"Display a NEW draw.io diagram from XML. REPLACES the entire diagram. " +
|
||||
"Use this for creating new diagrams from scratch. " +
|
||||
"To ADD elements to an existing diagram, use edit_diagram with 'add' operation instead. " +
|
||||
"You should generate valid draw.io/mxGraph XML format.",
|
||||
description: `Create a NEW diagram from mxGraphModel XML. Use this when creating a diagram from scratch or replacing the current diagram entirely.
|
||||
|
||||
CRITICAL: You MUST provide the 'xml' argument in EVERY call. Do NOT call this tool without xml.
|
||||
|
||||
When to use this tool:
|
||||
- Creating a new diagram from scratch
|
||||
- Replacing the current diagram with a completely different one
|
||||
- Major structural changes that require regenerating the diagram
|
||||
|
||||
When to use edit_diagram instead:
|
||||
- Small modifications to existing diagram
|
||||
- Adding/removing individual elements
|
||||
- Changing labels, colors, or positions
|
||||
|
||||
XML FORMAT - Full mxGraphModel structure:
|
||||
<mxGraphModel>
|
||||
<root>
|
||||
<mxCell id="0"/>
|
||||
<mxCell id="1" parent="0"/>
|
||||
<mxCell id="2" value="Shape" style="rounded=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
|
||||
LAYOUT CONSTRAINTS:
|
||||
- Keep all elements within x=0-800, y=0-600 (single page viewport)
|
||||
- Start from margins (x=40, y=40), keep elements grouped closely
|
||||
- Use unique IDs starting from "2" (0 and 1 are reserved)
|
||||
- Set parent="1" for top-level shapes
|
||||
- Space shapes 150-200px apart for clear edge routing
|
||||
|
||||
EDGE ROUTING RULES:
|
||||
- Never let multiple edges share the same path - use different exitY/entryY values
|
||||
- For bidirectional connections (A↔B), use OPPOSITE sides
|
||||
- Always specify exitX, exitY, entryX, entryY explicitly in edge style
|
||||
- Route edges AROUND obstacles using waypoints (add 20-30px clearance)
|
||||
- Use natural connection points based on flow (not corners)
|
||||
|
||||
COMMON STYLES:
|
||||
- Shapes: rounded=1; fillColor=#hex; strokeColor=#hex
|
||||
- Edges: endArrow=classic; edgeStyle=orthogonalEdgeStyle; curved=1
|
||||
- Text: fontSize=14; fontStyle=1 (bold); align=center`,
|
||||
inputSchema: {
|
||||
xml: z
|
||||
.string()
|
||||
.describe("The draw.io XML to display (mxGraphModel format)"),
|
||||
.describe(
|
||||
"REQUIRED: The complete mxGraphModel XML. Must always be provided.",
|
||||
),
|
||||
},
|
||||
},
|
||||
async ({ xml: inputXml }) => {
|
||||
@@ -199,7 +239,7 @@ server.registerTool(
|
||||
}
|
||||
}
|
||||
|
||||
log.info(`Displaying diagram, ${xml.length} chars`)
|
||||
log.info(`Setting diagram content, ${xml.length} chars`)
|
||||
|
||||
// Sync from browser state first
|
||||
const browserState = getState(currentSession.id)
|
||||
@@ -226,20 +266,20 @@ server.registerTool(
|
||||
// Save AI result (no SVG yet - will be captured by browser)
|
||||
addHistory(currentSession.id, xml, "")
|
||||
|
||||
log.info(`Diagram displayed successfully`)
|
||||
log.info(`Diagram content set successfully`)
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Diagram displayed successfully!\n\nThe diagram is now visible in your browser.\n\nXML length: ${xml.length} characters`,
|
||||
text: `Diagram content set successfully!\n\nThe diagram is now visible in your browser.\n\nXML length: ${xml.length} characters`,
|
||||
},
|
||||
],
|
||||
}
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error)
|
||||
log.error("display_diagram failed:", message)
|
||||
log.error("create_new_diagram failed:", message)
|
||||
return {
|
||||
content: [{ type: "text", text: `Error: ${message}` }],
|
||||
isError: true,
|
||||
@@ -340,7 +380,7 @@ server.registerTool(
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Error: No diagram to edit. Please create a diagram first with display_diagram.",
|
||||
text: "Error: No diagram to edit. Please create a diagram first with create_new_diagram.",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
@@ -474,7 +514,7 @@ server.registerTool(
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "No diagram exists yet. Use display_diagram to create one.",
|
||||
text: "No diagram exists yet. Use create_new_diagram to create one.",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
BIN
public/doubao-color.png
Normal file
BIN
public/doubao-color.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
1
public/doubao-color.svg
Normal file
1
public/doubao-color.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Doubao</title><path d="M5.31 15.756c.172-3.75 1.883-5.999 2.549-6.739-3.26 2.058-5.425 5.658-6.358 8.308v1.12C1.501 21.513 4.226 24 7.59 24a6.59 6.59 0 002.2-.375c.353-.12.7-.248 1.039-.378.913-.899 1.65-1.91 2.243-2.992-4.877 2.431-7.974.072-7.763-4.5l.002.001z" fill="#1E37FC"></path><path d="M22.57 10.283c-1.212-.901-4.109-2.404-7.397-2.8.295 3.792.093 8.766-2.1 12.773a12.782 12.782 0 01-2.244 2.992c3.764-1.448 6.746-3.457 8.596-5.219 2.82-2.683 3.353-5.178 3.361-6.66a2.737 2.737 0 00-.216-1.084v-.002z" fill="#37E1BE"></path><path d="M14.303 1.867C12.955.7 11.248 0 9.39 0 7.532 0 5.883.677 4.545 1.807 2.791 3.29 1.627 5.557 1.5 8.125v9.201c.932-2.65 3.097-6.25 6.357-8.307.5-.318 1.025-.595 1.569-.829 1.883-.801 3.878-.932 5.746-.706-.222-2.83-.718-5.002-.87-5.617h.001z" fill="#A569FF"></path><path d="M17.305 4.961a199.47 199.47 0 01-1.08-1.094c-.202-.213-.398-.419-.586-.622l-1.333-1.378c.151.615.648 2.786.869 5.617 3.288.395 6.185 1.898 7.396 2.8-1.306-1.275-3.475-3.487-5.266-5.323z" fill="#1E37FC"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -22,6 +22,7 @@
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"files": ["electron/electron.d.ts"],
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
|
||||
Reference in New Issue
Block a user