fix(web): align playground chat layout
This commit is contained in:
@@ -0,0 +1,713 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import {
|
||||
AssistantRuntimeProvider,
|
||||
ComposerPrimitive,
|
||||
MessagePrimitive,
|
||||
ThreadPrimitive,
|
||||
useMessagePartText,
|
||||
useLocalRuntime,
|
||||
type ChatModelAdapter,
|
||||
type ThreadMessage,
|
||||
} from '@assistant-ui/react';
|
||||
import { StreamdownTextPrimitive } from '@assistant-ui/react-streamdown';
|
||||
import { cjk } from '@streamdown/cjk';
|
||||
import { code } from '@streamdown/code';
|
||||
import { math } from '@streamdown/math';
|
||||
import { mermaid } from '@streamdown/mermaid';
|
||||
import type { GatewayApiKey, PlatformModel } from '@easyai-ai-gateway/contracts';
|
||||
import { Bot, ChevronDown, Image as ImageIcon, MessageSquarePlus, Paperclip, Send, Sparkles, Video } from 'lucide-react';
|
||||
import { Badge, Button, Select, Textarea } from '../components/ui';
|
||||
import { streamChatCompletionText } from '../api';
|
||||
import type { PlaygroundMode } from '../types';
|
||||
|
||||
type VideoCreateMode = 'text_to_video' | 'first_last_frame' | 'omni_reference';
|
||||
|
||||
interface ModelOption {
|
||||
count: number;
|
||||
label: string;
|
||||
provider: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const modeOptions: Array<{ description: string; icon: ReactNode; label: string; value: PlaygroundMode }> = [
|
||||
{ value: 'chat', label: '大模型对话', description: '对话、推理、结构化输出', icon: <Bot size={16} /> },
|
||||
{ value: 'image', label: '图像生成', description: '文生图、图像编辑参数预览', icon: <ImageIcon size={16} /> },
|
||||
{ value: 'video', label: '视频生成', description: '图生视频、文生视频任务测试', icon: <Video size={16} /> },
|
||||
];
|
||||
|
||||
const videoModeOptions: Array<{ label: string; value: VideoCreateMode }> = [
|
||||
{ value: 'text_to_video', label: '文生视频' },
|
||||
{ value: 'first_last_frame', label: '首尾帧' },
|
||||
{ value: 'omni_reference', label: '全能参考' },
|
||||
];
|
||||
|
||||
const placeholderByMode: Record<PlaygroundMode, string> = {
|
||||
chat: '输入问题、角色设定或测试提示词,支持 OpenAI 兼容格式验证...',
|
||||
image: '描述你想生成的画面,例如:未来城市中的玻璃温室,晨光,电影级构图...',
|
||||
video: '描述视频镜头、主体运动和风格,例如:低角度跟拍,一辆复古跑车穿过雨夜街道...',
|
||||
};
|
||||
|
||||
const quickPrompts: Record<PlaygroundMode, string[]> = {
|
||||
chat: ['写一个产品发布摘要', '生成接口调用示例', '分析失败重试策略'],
|
||||
image: ['产品海报', '角色设定图', '电商主图'],
|
||||
video: ['5 秒运镜', '首帧转视频', '宣传短片'],
|
||||
};
|
||||
|
||||
const publicWorks = [
|
||||
{ title: '雨夜霓虹街区', type: '图像生成', image: 'https://picsum.photos/seed/easyai-neon-city/720/960' },
|
||||
{ title: '玻璃温室晨光', type: '图像生成', image: 'https://picsum.photos/seed/easyai-glasshouse/720/540' },
|
||||
{ title: '山谷航拍镜头', type: '视频生成', image: 'https://picsum.photos/seed/easyai-valley-flight/720/1040' },
|
||||
{ title: '极简产品广告', type: '图像生成', image: 'https://picsum.photos/seed/easyai-product-ad/720/680' },
|
||||
{ title: '机械结构设定', type: '图像编辑', image: 'https://picsum.photos/seed/easyai-mecha-sketch/720/920' },
|
||||
{ title: '城市模型推演', type: '大模型', image: 'https://picsum.photos/seed/easyai-city-plan/720/620' },
|
||||
{ title: '海边人物电影感', type: '图像生成', image: 'https://picsum.photos/seed/easyai-cinematic-sea/720/980' },
|
||||
{ title: '空间站漫游', type: '视频生成', image: 'https://picsum.photos/seed/easyai-orbital-walk/720/860' },
|
||||
{ title: '水彩建筑手稿', type: '图像生成', image: 'https://picsum.photos/seed/easyai-watercolor-arch/720/760' },
|
||||
{ title: '品牌 KV 探索', type: '图像生成', image: 'https://picsum.photos/seed/easyai-brand-kv/720/560' },
|
||||
{ title: '古城夜游镜头', type: '视频生成', image: 'https://picsum.photos/seed/easyai-night-town/720/1020' },
|
||||
{ title: '界面概念板', type: '大模型', image: 'https://picsum.photos/seed/easyai-ui-board/720/650' },
|
||||
];
|
||||
|
||||
const streamdownPlugins = { cjk, code, math, mermaid };
|
||||
|
||||
export function PlaygroundPage(props: {
|
||||
apiKeySecretsById: Record<string, string>;
|
||||
apiKeys: GatewayApiKey[];
|
||||
mode: PlaygroundMode;
|
||||
models: PlatformModel[];
|
||||
selectedApiKeyId: string;
|
||||
token: string;
|
||||
onApiKeyChange: (apiKeyId: string) => void;
|
||||
onCreateApiKey: () => void;
|
||||
onLogin: () => void;
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
}) {
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [selectedModel, setSelectedModel] = useState('');
|
||||
const [imageHasReference, setImageHasReference] = useState(false);
|
||||
const [videoMode, setVideoMode] = useState<VideoCreateMode>('text_to_video');
|
||||
const [threadKey, setThreadKey] = useState(0);
|
||||
const activeMode = useMemo(() => modeOptions.find((item) => item.value === props.mode) ?? modeOptions[0], [props.mode]);
|
||||
const modelOptions = useMemo(
|
||||
() => buildModelOptions(filterModelsForMode(props.models, props.mode, imageHasReference, videoMode)),
|
||||
[imageHasReference, props.mode, props.models, videoMode],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedModel((current) => modelOptions.some((item) => item.value === current) ? current : modelOptions[0]?.value ?? '');
|
||||
}, [modelOptions]);
|
||||
|
||||
return (
|
||||
<div className="playgroundPage">
|
||||
<aside className="playgroundSidebar">
|
||||
<div className="playgroundSidebarTitle">
|
||||
<strong>开启创作</strong>
|
||||
<Badge variant="secondary">Test</Badge>
|
||||
</div>
|
||||
<button type="button" className="playgroundSideItem active" onClick={() => setThreadKey((value) => value + 1)}>
|
||||
<MessageSquarePlus size={15} />
|
||||
新对话
|
||||
</button>
|
||||
<button type="button" className="playgroundSideItem">
|
||||
<Sparkles size={15} />
|
||||
默认创作
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<main className="playgroundStage">
|
||||
<section className="playgroundHero" data-chat={props.mode === 'chat'}>
|
||||
{props.mode === 'chat' ? (
|
||||
<AssistantChatPlayground
|
||||
key={threadKey}
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
modelOptions={modelOptions}
|
||||
selectedApiKeyId={props.selectedApiKeyId}
|
||||
selectedModel={selectedModel}
|
||||
token={props.token}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
onCreateApiKey={props.onCreateApiKey}
|
||||
onModeChange={props.onModeChange}
|
||||
onModelChange={setSelectedModel}
|
||||
onLogin={props.onLogin}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<ModeSwitch activeMode={props.mode} onModeChange={props.onModeChange} />
|
||||
<PlaygroundGreeting activeMode={activeMode} />
|
||||
<Composer
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
mode={props.mode}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
selectedApiKeyId={props.selectedApiKeyId}
|
||||
selectedModel={selectedModel}
|
||||
imageHasReference={imageHasReference}
|
||||
videoMode={videoMode}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
onCreateApiKey={props.onCreateApiKey}
|
||||
onImageReferenceChange={setImageHasReference}
|
||||
onModeChange={props.onModeChange}
|
||||
onModelChange={setSelectedModel}
|
||||
onPromptChange={setPrompt}
|
||||
onSubmit={() => undefined}
|
||||
onVideoModeChange={setVideoMode}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlaygroundEntry(props: {
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
}) {
|
||||
const [mode, setMode] = useState<PlaygroundMode>('chat');
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const activeMode = modeOptions.find((item) => item.value === mode) ?? modeOptions[0];
|
||||
|
||||
function openPlayground(nextMode = mode) {
|
||||
props.onModeChange(nextMode);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="homePlaygroundEntry">
|
||||
<h2>
|
||||
开启你的 <button type="button" onClick={() => openPlayground(mode)}>{activeMode.label}<ChevronDown size={20} /></button> 即刻测试
|
||||
</h2>
|
||||
<Composer
|
||||
mode={mode}
|
||||
modelOptions={[]}
|
||||
prompt={prompt}
|
||||
compact
|
||||
onModeChange={(nextMode) => {
|
||||
setMode(nextMode);
|
||||
openPlayground(nextMode);
|
||||
}}
|
||||
onModelChange={() => undefined}
|
||||
onPromptChange={setPrompt}
|
||||
onSubmit={() => openPlayground(mode)}
|
||||
/>
|
||||
<div className="playgroundModeCards">
|
||||
{modeOptions.map((item) => (
|
||||
<button type="button" key={item.value} onClick={() => openPlayground(item.value)}>
|
||||
<span>{item.icon}</span>
|
||||
<strong>{item.label}</strong>
|
||||
<small>{item.description}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function PublicWorksGallery() {
|
||||
return (
|
||||
<section className="publicWorksSection">
|
||||
<div className="publicWorksHeader">
|
||||
<div>
|
||||
<p className="eyebrow">Community Gallery</p>
|
||||
<h2>公开作品展示</h2>
|
||||
</div>
|
||||
<div className="publicWorksTabs" aria-label="作品类型">
|
||||
<button type="button" data-active="true">发现</button>
|
||||
<button type="button">图片</button>
|
||||
<button type="button">视频</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="publicWorksMasonry">
|
||||
{publicWorks.map((item) => (
|
||||
<article className="publicWorkCard" key={item.title}>
|
||||
<img src={item.image} alt={item.title} loading="lazy" />
|
||||
<div>
|
||||
<Badge variant="secondary">{item.type}</Badge>
|
||||
<strong>{item.title}</strong>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantChatPlayground(props: {
|
||||
apiKeySecretsById: Record<string, string>;
|
||||
apiKeys: GatewayApiKey[];
|
||||
modelOptions: ModelOption[];
|
||||
selectedApiKeyId: string;
|
||||
selectedModel: string;
|
||||
token: string;
|
||||
onApiKeyChange: (apiKeyId: string) => void;
|
||||
onCreateApiKey: () => void;
|
||||
onLogin: () => void;
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
onModelChange: (value: string) => void;
|
||||
}) {
|
||||
const activeApiKeyId = resolveSelectedApiKeyId(props.apiKeys, props.apiKeySecretsById, props.selectedApiKeyId);
|
||||
const activeApiKeySecret = activeApiKeyId ? props.apiKeySecretsById[activeApiKeyId] ?? '' : '';
|
||||
const canRun = Boolean(props.token && props.selectedModel && activeApiKeySecret);
|
||||
const apiKeyNotice = apiKeyNoticeText(props.apiKeys, props.apiKeySecretsById);
|
||||
const adapter = useMemo<ChatModelAdapter>(() => ({
|
||||
async *run({ abortSignal, messages }) {
|
||||
if (!props.token) {
|
||||
props.onLogin();
|
||||
throw new Error('请先登录后再测试模型。');
|
||||
}
|
||||
if (!activeApiKeySecret) {
|
||||
throw new Error('请选择可用于测试的 API Key;如果列表为空,请刷新或重新创建一个 Key。');
|
||||
}
|
||||
if (!props.selectedModel) {
|
||||
throw new Error('当前没有可用的大模型,请确认用户组权限或平台模型配置。');
|
||||
}
|
||||
let text = '';
|
||||
for await (const delta of streamChatCompletionText(
|
||||
activeApiKeySecret,
|
||||
{
|
||||
messages: toGatewayChatMessages(messages),
|
||||
model: props.selectedModel,
|
||||
},
|
||||
abortSignal,
|
||||
)) {
|
||||
text += delta;
|
||||
yield {
|
||||
content: [{ type: 'text', text }],
|
||||
};
|
||||
}
|
||||
yield {
|
||||
content: [{ type: 'text', text }],
|
||||
status: { type: 'complete', reason: 'stop' },
|
||||
};
|
||||
},
|
||||
}), [activeApiKeySecret, props]);
|
||||
const runtime = useLocalRuntime(adapter);
|
||||
|
||||
return (
|
||||
<AssistantRuntimeProvider runtime={runtime}>
|
||||
<ThreadPrimitive.Root className="assistantThreadRoot">
|
||||
<ThreadPrimitive.Empty>
|
||||
<div className="assistantEmptyStage">
|
||||
<AssistantEmptyState
|
||||
apiKeyNotice={apiKeyNotice}
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
canRun={canRun}
|
||||
modelOptions={props.modelOptions}
|
||||
selectedApiKeyId={activeApiKeyId}
|
||||
selectedModel={props.selectedModel}
|
||||
token={props.token}
|
||||
activeApiKeySecret={activeApiKeySecret}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
onCreateApiKey={props.onCreateApiKey}
|
||||
onModeChange={props.onModeChange}
|
||||
onModelChange={props.onModelChange}
|
||||
/>
|
||||
</div>
|
||||
</ThreadPrimitive.Empty>
|
||||
<ThreadPrimitive.If empty={false}>
|
||||
<div className="assistantShell" data-has-notice={Boolean(apiKeyNotice)}>
|
||||
{apiKeyNotice && (
|
||||
<div className="assistantApiKeyNotice">
|
||||
<span>{apiKeyNotice}</span>
|
||||
<Button type="button" size="sm" variant="secondary" onClick={props.onCreateApiKey}>
|
||||
去创建 API Key
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<ThreadPrimitive.Viewport className="assistantThreadViewport">
|
||||
<div className="assistantMessageList">
|
||||
<ThreadPrimitive.Messages components={{ Message: AssistantMessage }} />
|
||||
</div>
|
||||
<ThreadPrimitive.ViewportFooter className="assistantComposerDock">
|
||||
<AssistantChatComposer
|
||||
apiKeyNotice={apiKeyNotice}
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
canRun={canRun}
|
||||
docked
|
||||
modelOptions={props.modelOptions}
|
||||
placeholder={assistantPlaceholder(props.token, props.selectedModel, activeApiKeySecret)}
|
||||
selectedApiKeyId={activeApiKeyId}
|
||||
selectedModel={props.selectedModel}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
onCreateApiKey={props.onCreateApiKey}
|
||||
onModeChange={props.onModeChange}
|
||||
onModelChange={props.onModelChange}
|
||||
/>
|
||||
</ThreadPrimitive.ViewportFooter>
|
||||
</ThreadPrimitive.Viewport>
|
||||
</div>
|
||||
</ThreadPrimitive.If>
|
||||
</ThreadPrimitive.Root>
|
||||
</AssistantRuntimeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ModeSwitch(props: {
|
||||
activeMode: PlaygroundMode;
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="playgroundModeSwitch">
|
||||
{modeOptions.map((item) => (
|
||||
<button
|
||||
type="button"
|
||||
key={item.value}
|
||||
data-active={props.activeMode === item.value}
|
||||
onClick={() => props.onModeChange(item.value)}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlaygroundGreeting(props: {
|
||||
activeMode: { description: string; label: string };
|
||||
}) {
|
||||
return (
|
||||
<div className="playgroundGreeting">
|
||||
<span>你好,想测试什么?</span>
|
||||
<strong>{props.activeMode.label}</strong>
|
||||
<small>{props.activeMode.description}</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantEmptyState(props: {
|
||||
activeApiKeySecret: string;
|
||||
apiKeyNotice: string;
|
||||
apiKeySecretsById: Record<string, string>;
|
||||
apiKeys: GatewayApiKey[];
|
||||
canRun: boolean;
|
||||
modelOptions: ModelOption[];
|
||||
selectedApiKeyId: string;
|
||||
selectedModel: string;
|
||||
token: string;
|
||||
onApiKeyChange: (apiKeyId: string) => void;
|
||||
onCreateApiKey: () => void;
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
onModelChange: (value: string) => void;
|
||||
}) {
|
||||
const activeMode = modeOptions.find((item) => item.value === 'chat') ?? modeOptions[0];
|
||||
const placeholder = props.canRun ? placeholderByMode.chat : assistantPlaceholder(props.token, props.selectedModel, props.activeApiKeySecret);
|
||||
|
||||
return (
|
||||
<div className="assistantEmpty">
|
||||
<ModeSwitch activeMode="chat" onModeChange={props.onModeChange} />
|
||||
<PlaygroundGreeting activeMode={activeMode} />
|
||||
<AssistantChatComposer
|
||||
apiKeyNotice={props.apiKeyNotice}
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
canRun={props.canRun}
|
||||
modelOptions={props.modelOptions}
|
||||
placeholder={placeholder}
|
||||
selectedApiKeyId={props.selectedApiKeyId}
|
||||
selectedModel={props.selectedModel}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
onCreateApiKey={props.onCreateApiKey}
|
||||
onModeChange={props.onModeChange}
|
||||
onModelChange={props.onModelChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantChatComposer(props: {
|
||||
apiKeyNotice: string;
|
||||
apiKeySecretsById: Record<string, string>;
|
||||
apiKeys: GatewayApiKey[];
|
||||
canRun: boolean;
|
||||
docked?: boolean;
|
||||
modelOptions: ModelOption[];
|
||||
placeholder: string;
|
||||
selectedApiKeyId: string;
|
||||
selectedModel: string;
|
||||
onApiKeyChange: (apiKeyId: string) => void;
|
||||
onCreateApiKey: () => void;
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
onModelChange: (value: string) => void;
|
||||
}) {
|
||||
const className = ['playgroundComposer', 'assistantChatComposer', props.docked ? 'assistantDockComposer' : 'assistantEmptyComposer'].join(' ');
|
||||
|
||||
return (
|
||||
<ComposerPrimitive.Root className={className}>
|
||||
<div className="composerBody">
|
||||
<button type="button" className="composerUpload" aria-label="上传参考" disabled>
|
||||
<Paperclip size={18} />
|
||||
</button>
|
||||
<ComposerPrimitive.Input
|
||||
className="assistantEmptyInput"
|
||||
disabled={!props.canRun}
|
||||
placeholder={props.placeholder}
|
||||
/>
|
||||
</div>
|
||||
<div className="composerFooter">
|
||||
<Select value="chat" onChange={(event) => props.onModeChange(event.target.value as PlaygroundMode)}>
|
||||
{modeOptions.map((item) => <option value={item.value} key={item.value}>{item.label}</option>)}
|
||||
</Select>
|
||||
<Select
|
||||
className="playgroundModelSelect"
|
||||
value={props.selectedModel}
|
||||
disabled={!props.modelOptions.length}
|
||||
onChange={(event) => props.onModelChange(event.target.value)}
|
||||
>
|
||||
{props.modelOptions.length ? props.modelOptions.map((item) => (
|
||||
<option value={item.value} key={item.value}>{modelOptionLabel(item)}</option>
|
||||
)) : <option value="">没有可用模型</option>}
|
||||
</Select>
|
||||
<ApiKeySelect
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
selectedApiKeyId={props.selectedApiKeyId}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
/>
|
||||
{props.apiKeyNotice && (
|
||||
<Button type="button" size="sm" variant="secondary" onClick={props.onCreateApiKey}>
|
||||
创建 API Key
|
||||
</Button>
|
||||
)}
|
||||
<ComposerPrimitive.Send className="composerSendButton" disabled={!props.canRun} aria-label="发送消息">
|
||||
<Send size={18} />
|
||||
</ComposerPrimitive.Send>
|
||||
</div>
|
||||
</ComposerPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantMessage() {
|
||||
return (
|
||||
<MessagePrimitive.Root className="assistantMessage">
|
||||
<MessagePrimitive.If user>
|
||||
<div className="assistantBubble user">
|
||||
<MessagePrimitive.Parts components={{ Text: PlainMessageText }} />
|
||||
</div>
|
||||
</MessagePrimitive.If>
|
||||
<MessagePrimitive.If assistant>
|
||||
<div className="assistantBubble assistant">
|
||||
<MessagePrimitive.Parts components={{ Text: AssistantMarkdownText }} />
|
||||
<MessagePrimitive.If hasContent={false}>
|
||||
<span className="assistantTyping">模型正在回复...</span>
|
||||
</MessagePrimitive.If>
|
||||
</div>
|
||||
</MessagePrimitive.If>
|
||||
<MessagePrimitive.Error>
|
||||
<div className="assistantBubble error">调用失败,请检查模型、平台凭证或测试模式配置。</div>
|
||||
</MessagePrimitive.Error>
|
||||
</MessagePrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function PlainMessageText() {
|
||||
const { text } = useMessagePartText();
|
||||
return <span className="assistantPlainText">{text}</span>;
|
||||
}
|
||||
|
||||
function AssistantMarkdownText() {
|
||||
return (
|
||||
<StreamdownTextPrimitive
|
||||
containerClassName="assistantMarkdown"
|
||||
plugins={streamdownPlugins}
|
||||
shikiTheme={['github-light', 'github-dark']}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function toGatewayChatMessages(messages: readonly ThreadMessage[]) {
|
||||
return messages
|
||||
.filter((message) => message.role === 'user' || message.role === 'assistant')
|
||||
.map((message) => ({
|
||||
content: threadMessageText(message),
|
||||
role: message.role,
|
||||
}))
|
||||
.filter((message) => message.content.trim().length > 0);
|
||||
}
|
||||
|
||||
function threadMessageText(message: ThreadMessage) {
|
||||
return message.content
|
||||
.map((part) => part.type === 'text' ? part.text : '')
|
||||
.join('')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function resolveSelectedApiKeyId(apiKeys: GatewayApiKey[], secretsById: Record<string, string>, selectedApiKeyId: string) {
|
||||
if (selectedApiKeyId && secretsById[selectedApiKeyId]) return selectedApiKeyId;
|
||||
const firstUsable = apiKeys.find((item) => Boolean(secretsById[item.id]));
|
||||
return firstUsable?.id ?? '';
|
||||
}
|
||||
|
||||
function apiKeyNoticeText(apiKeys: GatewayApiKey[], secretsById: Record<string, string>) {
|
||||
if (!apiKeys.length) return '当前账号还没有可用 API Key,请先创建一个 Key。';
|
||||
if (!apiKeys.some((item) => Boolean(secretsById[item.id]))) {
|
||||
return '当前没有可用于在线测试的完整 API Key,请重新加载或创建一个 Key。';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function assistantPlaceholder(token: string, selectedModel: string, apiKeySecret: string) {
|
||||
if (!token) return '请先登录后再测试模型';
|
||||
if (!apiKeySecret) return '请选择可用于测试的 API Key';
|
||||
if (!selectedModel) return '当前没有可用模型';
|
||||
return '输入消息,Enter 发送,Shift + Enter 换行';
|
||||
}
|
||||
|
||||
function Composer(props: {
|
||||
apiKeySecretsById?: Record<string, string>;
|
||||
apiKeys?: GatewayApiKey[];
|
||||
compact?: boolean;
|
||||
imageHasReference?: boolean;
|
||||
mode: PlaygroundMode;
|
||||
modelOptions: ModelOption[];
|
||||
prompt: string;
|
||||
selectedApiKeyId?: string;
|
||||
selectedModel?: string;
|
||||
videoMode?: VideoCreateMode;
|
||||
onApiKeyChange?: (apiKeyId: string) => void;
|
||||
onCreateApiKey?: () => void;
|
||||
onImageReferenceChange?: (value: boolean) => void;
|
||||
onModeChange: (mode: PlaygroundMode) => void;
|
||||
onModelChange: (value: string) => void;
|
||||
onPromptChange: (value: string) => void;
|
||||
onSubmit?: () => void;
|
||||
onVideoModeChange?: (value: VideoCreateMode) => void;
|
||||
}) {
|
||||
const quickItems = quickPrompts[props.mode];
|
||||
const apiKeyNotice = props.apiKeys && props.apiKeySecretsById ? apiKeyNoticeText(props.apiKeys, props.apiKeySecretsById) : '';
|
||||
return (
|
||||
<div className={props.compact ? 'playgroundComposer compact' : 'playgroundComposer'}>
|
||||
<div className="composerBody">
|
||||
<button
|
||||
type="button"
|
||||
className="composerUpload"
|
||||
aria-label="上传参考"
|
||||
data-active={props.imageHasReference === true}
|
||||
onClick={() => props.mode === 'image' && props.onImageReferenceChange?.(!props.imageHasReference)}
|
||||
>
|
||||
<Paperclip size={18} />
|
||||
</button>
|
||||
<Textarea
|
||||
size={props.compact ? 'sm' : 'md'}
|
||||
value={props.prompt}
|
||||
placeholder={placeholderByMode[props.mode]}
|
||||
onChange={(event) => props.onPromptChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="composerFooter">
|
||||
<Select value={props.mode} onChange={(event) => props.onModeChange(event.target.value as PlaygroundMode)}>
|
||||
{modeOptions.map((item) => <option value={item.value} key={item.value}>{item.label}</option>)}
|
||||
</Select>
|
||||
{props.mode === 'video' && (
|
||||
<Select value={props.videoMode ?? 'text_to_video'} onChange={(event) => props.onVideoModeChange?.(event.target.value as VideoCreateMode)}>
|
||||
{videoModeOptions.map((item) => <option value={item.value} key={item.value}>{item.label}</option>)}
|
||||
</Select>
|
||||
)}
|
||||
<Select className="playgroundModelSelect" value={props.selectedModel ?? ''} disabled={!props.modelOptions.length} onChange={(event) => props.onModelChange(event.target.value)}>
|
||||
{props.modelOptions.length ? props.modelOptions.map((item) => (
|
||||
<option value={item.value} key={item.value}>{modelOptionLabel(item)}</option>
|
||||
)) : <option value="">模型选择</option>}
|
||||
</Select>
|
||||
{props.apiKeys && props.apiKeySecretsById && props.onApiKeyChange && (
|
||||
<ApiKeySelect
|
||||
apiKeySecretsById={props.apiKeySecretsById}
|
||||
apiKeys={props.apiKeys}
|
||||
selectedApiKeyId={props.selectedApiKeyId ?? ''}
|
||||
onApiKeyChange={props.onApiKeyChange}
|
||||
/>
|
||||
)}
|
||||
{apiKeyNotice && props.onCreateApiKey && (
|
||||
<Button type="button" size="sm" variant="secondary" onClick={props.onCreateApiKey}>
|
||||
创建 API Key
|
||||
</Button>
|
||||
)}
|
||||
<div className="composerQuickPrompts">
|
||||
{quickItems.map((item) => <button type="button" key={item} onClick={() => props.onPromptChange(item)}>{item}</button>)}
|
||||
</div>
|
||||
<Button type="button" size="icon" aria-label="发送测试" onClick={props.onSubmit}>
|
||||
<Send size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ApiKeySelect(props: {
|
||||
apiKeySecretsById: Record<string, string>;
|
||||
apiKeys: GatewayApiKey[];
|
||||
selectedApiKeyId: string;
|
||||
onApiKeyChange: (apiKeyId: string) => void;
|
||||
}) {
|
||||
const activeApiKeyId = resolveSelectedApiKeyId(props.apiKeys, props.apiKeySecretsById, props.selectedApiKeyId);
|
||||
return (
|
||||
<Select
|
||||
className="playgroundApiKeySelect"
|
||||
value={activeApiKeyId}
|
||||
disabled={!props.apiKeys.length}
|
||||
onChange={(event) => props.onApiKeyChange(event.target.value)}
|
||||
>
|
||||
{!activeApiKeyId && <option value="">{props.apiKeys.length ? '选择 API Key' : '暂无 API Key'}</option>}
|
||||
{props.apiKeys.map((item) => {
|
||||
const usable = Boolean(props.apiKeySecretsById[item.id]);
|
||||
return (
|
||||
<option value={item.id} key={item.id} disabled={!usable}>
|
||||
{item.name} · {item.keyPrefix}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
function filterModelsForMode(models: PlatformModel[], mode: PlaygroundMode, hasReference: boolean, videoMode: VideoCreateMode) {
|
||||
if (mode === 'chat') {
|
||||
return filterWithFallback(models, ['text_generate', 'chat', 'responses', 'text']);
|
||||
}
|
||||
if (mode === 'image') {
|
||||
const preferredTypes = hasReference ? ['image_edit', 'images.edits'] : ['image_generate', 'images.generations'];
|
||||
return filterWithFallback(models, [...preferredTypes, 'image']);
|
||||
}
|
||||
const videoTypesByMode: Record<VideoCreateMode, string[]> = {
|
||||
first_last_frame: ['image_to_video', 'video_first_last_frame', 'video_generate'],
|
||||
omni_reference: ['omni_video', 'video_reference', 'video_generate'],
|
||||
text_to_video: ['text_to_video', 'video_generate'],
|
||||
};
|
||||
return filterWithFallback(models, [...videoTypesByMode[videoMode], 'video']);
|
||||
}
|
||||
|
||||
function filterWithFallback(models: PlatformModel[], modelTypes: string[]) {
|
||||
const exact = models.filter((model) => modelTypes.includes(model.modelType));
|
||||
return exact.length ? exact : models.filter((model) => modelTypes.some((type) => model.modelType.includes(type) || type.includes(model.modelType)));
|
||||
}
|
||||
|
||||
function buildModelOptions(models: PlatformModel[]): ModelOption[] {
|
||||
const grouped = new Map<string, ModelOption>();
|
||||
models.forEach((model) => {
|
||||
const value = model.modelAlias || model.modelName;
|
||||
if (!value) return;
|
||||
const current = grouped.get(value);
|
||||
if (current) {
|
||||
current.count += 1;
|
||||
if (!current.provider.includes(model.provider || '')) {
|
||||
current.provider = [current.provider, model.provider].filter(Boolean).join(' / ');
|
||||
}
|
||||
return;
|
||||
}
|
||||
grouped.set(value, {
|
||||
count: 1,
|
||||
label: model.modelAlias || model.displayName || model.modelName,
|
||||
provider: model.provider || model.platformName || '',
|
||||
value,
|
||||
});
|
||||
});
|
||||
return Array.from(grouped.values()).sort((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
function modelOptionLabel(option: ModelOption) {
|
||||
const count = option.count > 1 ? ` · ${option.count} 个客户端` : '';
|
||||
const provider = option.provider ? ` · ${option.provider}` : '';
|
||||
return `${option.label}${provider}${count}`;
|
||||
}
|
||||
Reference in New Issue
Block a user