DebugForm.tsx 9.52 KB
import { useState, useEffect, useCallback } from 'react';
import { Select, Radio, Input, Button, Form, message, Tag, Space } from 'antd';
import { ThunderboltOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { accountService } from '../../services/accountService';
import { promptService } from '../../services/promptService';
import { orchestrationService } from '../../services/orchestrationService';
import type { CallResultData } from './DebugConsole';

interface AccountOption {
  id: string;
  account_name: string;
  code: string;
  model_name: string;
}

interface PromptOption {
  id: string;
  title: string;
  code: string;
  template_type: string;
}

interface DebugFormProps {
  onResult: (data: CallResultData) => void;
  setLoading: (v: boolean) => void;
}

export default function DebugForm({ onResult, setLoading }: DebugFormProps) {
  const [form] = Form.useForm();
  const [accounts, setAccounts] = useState<AccountOption[]>([]);
  const [prompts, setPrompts] = useState<PromptOption[]>([]);
  const [callMode, setCallMode] = useState<'sync' | 'async'>('sync');
  const [loadingAccounts, setLoadingAccounts] = useState(false);
  const [loadingPrompts, setLoadingPrompts] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [promptVariables, setPromptVariables] = useState<Array<{ name: string; type: string }>>([]);
  const [selectedPromptId, setSelectedPromptId] = useState<string | null>(null);

  // 加载账号列表
  const loadAccounts = useCallback(async () => {
    setLoadingAccounts(true);
    try {
      const res = await accountService.list({ page_size: 100 });
      setAccounts(
        res.items.map((a) => ({
          id: a.id,
          account_name: a.account_name,
          code: a.code,
          model_name: a.model_name,
        }))
      );
    } catch {
      message.error('加载账号列表失败');
    } finally {
      setLoadingAccounts(false);
    }
  }, []);

  // 加载提示词模板列表
  const loadPrompts = useCallback(async () => {
    setLoadingPrompts(true);
    try {
      const res = await promptService.list({ page_size: 100 });
      setPrompts(
        res.items.map((p) => ({
          id: p.id,
          title: p.title,
          code: p.code,
          template_type: p.template_type,
        }))
      );
    } catch {
      message.error('加载提示词模板失败');
    } finally {
      setLoadingPrompts(false);
    }
  }, []);

  useEffect(() => {
    loadAccounts();
    loadPrompts();
  }, [loadAccounts, loadPrompts]);

  // 从文本中提取 {{变量名}}
  const extractVarsFromText = (text: string): string[] => {
    const matches = text.match(/\{\{(\w+)\}\}/g);
    if (!matches) return [];
    return [...new Set(matches.map((m) => m.replace(/\{|\}/g, '')))];
  };

  // 选择模板后加载变量
  const handlePromptSelect = async (promptId: string | undefined) => {
    if (!promptId) {
      setSelectedPromptId(null);
      setPromptVariables([]);
      return;
    }
    setSelectedPromptId(promptId);
    try {
      const detail = await promptService.getById(promptId);
      // 优先使用数据库中保存的 variables 字段
      if (detail.variables && detail.variables.length > 0) {
        setPromptVariables(detail.variables);
      } else {
        // 兜底:从模板文本中自动提取 {{变量}}
        const allVars = [
          ...extractVarsFromText(detail.system_prompt || ''),
          ...extractVarsFromText(detail.user_prompt || ''),
        ];
        const uniqueVars = [...new Set(allVars)];
        setPromptVariables(uniqueVars.map((name) => ({ name, type: 'string' })));
      }
    } catch {
      message.error('加载模板详情失败');
    }
  };

  // 提交调用
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);
      setLoading(true);

      // Build variables from form
      const variables: Record<string, string> = {};
      if (values.variables) {
        for (const [key, val] of Object.entries(values.variables)) {
          variables[key] = String(val || '');
        }
      }

      const result = await orchestrationService.byTemplate({
        template_id: values.template_id,
        account_id: values.account_id,
        variables: Object.keys(variables).length > 0 ? variables : undefined,
        mode: callMode,
      });

      if (callMode === 'sync') {
        const syncRes = result as { status: string; model_name: string; call_record_id: string; account_id: string; response_content: string | null };
        onResult({
          status: syncRes.status === 'success' ? 'success' : 'error',
          callType: 'sync',
          responseBody: null,
          responseContent: syncRes.response_content,
          executionLog: null,
          modelName: syncRes.model_name,
          accountId: syncRes.account_id,
        });
        message.success('调用完成');
      } else {
        const asyncRes = result as { status: string; task_id: string; call_record_id: string };
        onResult({
          status: 'accepted',
          callType: 'async',
          responseBody: null,
          responseContent: null,
          executionLog: null,
          taskId: asyncRes.task_id,
        });
        message.info('异步任务已提交');
      }
    } catch (err: unknown) {
      const errMsg =
        (err as any)?.response?.data?.detail ||
        (err as Error)?.message ||
        '调用失败';
      message.error(errMsg);
      onResult({
        status: 'error',
        callType: callMode,
        responseBody: null,
        responseContent: null,
        executionLog: null,
        errorMessage: errMsg,
      });
    } finally {
      setSubmitting(false);
      setLoading(false);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      size="middle"
      onFinish={handleSubmit}
    >
      {/* Step 1: Account */}
      <div className="debug-section">
        <div className="debug-section-header">
          <span className="debug-section-badge">1</span>
          <span>选择账号</span>
        </div>
        <Form.Item
          name="account_id"
          label="调用账号"
          rules={[{ required: true, message: '请选择账号' }]}
        >
          <Select
            placeholder="选择调用账号"
            loading={loadingAccounts}
            showSearch
            allowClear
            optionFilterProp="label"
            options={accounts.map((a) => ({
              label: `${a.account_name} (${a.code}) — ${a.model_name}`,
              value: a.id,
            }))}
          />
        </Form.Item>
      </div>

      {/* Step 2: Call Mode */}
      <div className="debug-section">
        <div className="debug-section-header">
          <span className="debug-section-badge">2</span>
          <span>调用模式</span>
        </div>
        <Form.Item label="调用方式">
          <Radio.Group value={callMode} onChange={(e) => setCallMode(e.target.value)}>
            <Radio value="sync">
              <Space>
                <ThunderboltOutlined />
                同步调用
              </Space>
            </Radio>
            <Radio value="async">
              <Space>
                <ClockCircleOutlined />
                异步调用
              </Space>
            </Radio>
          </Radio.Group>
        </Form.Item>
      </div>

      {/* Step 3: Template */}
      <div className="debug-section">
        <div className="debug-section-header">
          <span className="debug-section-badge">3</span>
          <span>提示词模板</span>
        </div>
        <Form.Item
          name="template_id"
          label="选择模板"
          rules={[{ required: true, message: '请选择提示词模板' }]}
        >
          <Select
            placeholder="选择提示词模板"
            loading={loadingPrompts}
            showSearch
            allowClear
            optionFilterProp="label"
            onChange={handlePromptSelect}
            options={prompts.map((p) => ({
              label: `${p.title} (${p.code}) — ${p.template_type}`,
              value: p.id,
            }))}
          />
        </Form.Item>

        {/* Template Variables */}
        {promptVariables.length > 0 && (
          <div style={{ marginTop: 8 }}>
            <div style={{ fontSize: 13, color: '#64748b', marginBottom: 8 }}>
              模板变量
            </div>
            {promptVariables.map((v) => (
              <Form.Item
                key={v.name}
                name={['variables', v.name]}
                label={
                  <Space size={4}>
                    <Tag color="blue">{v.name}</Tag>
                    <span style={{ fontSize: 12, color: '#888' }}>({v.type})</span>
                  </Space>
                }
                style={{ marginBottom: 8 }}
              >
                <Input placeholder={`输入 ${v.name}`} />
              </Form.Item>
            ))}
          </div>
        )}

        {selectedPromptId && promptVariables.length === 0 && (
          <div style={{ padding: '8px 12px', background: '#f8fafc', borderRadius: 6, fontSize: 13, color: '#94a3b8' }}>
            该模板无需变量
          </div>
        )}
      </div>

      {/* Submit */}
      <div className="debug-actions">
        <Button
          type="primary"
          htmlType="submit"
          loading={submitting}
          icon={callMode === 'sync' ? <ThunderboltOutlined /> : <ClockCircleOutlined />}
          size="large"
          block
        >
          {callMode === 'sync' ? '同步调用' : '异步调用'}
        </Button>
      </div>
    </Form>
  );
}