feat:1.数据库存储功能添加(初版)2.后端REST API版本代码清理
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import request from '@/utils/request'
|
||||
import websocket from '@/utils/websocket'
|
||||
import type { Agent, IApiStepTask, IRawPlanResponse, IRawStepTask } from '@/stores'
|
||||
import { withRetry } from '@/utils/retry'
|
||||
@@ -30,7 +29,7 @@ export type IExecuteRawResponse = {
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE 流式事件类型
|
||||
* WebSocket 流式事件类型
|
||||
*/
|
||||
export type StreamingEvent =
|
||||
| {
|
||||
@@ -77,101 +76,47 @@ export interface IFillAgentSelectionRequest {
|
||||
}
|
||||
|
||||
class Api {
|
||||
// 默认使用WebSocket
|
||||
private useWebSocketDefault = true
|
||||
|
||||
setAgents = (
|
||||
data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[],
|
||||
useWebSocket: boolean = this.useWebSocketDefault,
|
||||
) => {
|
||||
// 如果启用WebSocket且已连接,使用WebSocket
|
||||
if (useWebSocket && websocket.connected) {
|
||||
return websocket.send('set_agents', data)
|
||||
}
|
||||
|
||||
// 否则使用REST API
|
||||
return request({
|
||||
url: '/setAgents',
|
||||
data,
|
||||
method: 'POST',
|
||||
})
|
||||
// 提取响应数据的公共方法
|
||||
private extractResponse<T>(raw: any): T {
|
||||
return (raw.data || raw) as T
|
||||
}
|
||||
|
||||
// 颜色向量转 HSL 字符串
|
||||
private vec2Hsl = (color: number[]): string => {
|
||||
const [h, s, l] = color
|
||||
return `hsl(${h}, ${s}%, ${l}%)`
|
||||
}
|
||||
|
||||
setAgents = (data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[]) =>
|
||||
websocket.send('set_agents', data)
|
||||
|
||||
getAgents = (user_id: string = 'default_user') => websocket.send('get_agents', { user_id })
|
||||
|
||||
generateBasePlan = (data: {
|
||||
goal: string
|
||||
inputs: string[]
|
||||
apiUrl?: string
|
||||
apiKey?: string
|
||||
apiModel?: string
|
||||
useWebSocket?: boolean
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
message?: string
|
||||
[key: string]: any
|
||||
}) => void
|
||||
}) => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// 如果启用WebSocket且已连接,使用WebSocket
|
||||
if (useWs && websocket.connected) {
|
||||
return websocket.send(
|
||||
'generate_base_plan',
|
||||
{
|
||||
'General Goal': data.goal,
|
||||
'Initial Input Object': data.inputs,
|
||||
apiUrl: data.apiUrl,
|
||||
apiKey: data.apiKey,
|
||||
apiModel: data.apiModel,
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
}
|
||||
|
||||
// 否则使用REST API
|
||||
return request<unknown, IRawPlanResponse>({
|
||||
url: '/generate_basePlan',
|
||||
method: 'POST',
|
||||
data: {
|
||||
}) =>
|
||||
websocket.send(
|
||||
'generate_base_plan',
|
||||
{
|
||||
'General Goal': data.goal,
|
||||
'Initial Input Object': data.inputs,
|
||||
apiUrl: data.apiUrl,
|
||||
apiKey: data.apiKey,
|
||||
apiModel: data.apiModel,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
executePlan = (plan: IRawPlanResponse) => {
|
||||
return request<unknown, IExecuteRawResponse[]>({
|
||||
url: '/executePlan',
|
||||
method: 'POST',
|
||||
data: {
|
||||
RehearsalLog: [],
|
||||
num_StepToRun: null,
|
||||
plan: {
|
||||
'Initial Input Object': plan['Initial Input Object'],
|
||||
'General Goal': plan['General Goal'],
|
||||
'Collaboration Process': plan['Collaboration Process']?.map((step) => ({
|
||||
StepName: step.StepName,
|
||||
TaskContent: step.TaskContent,
|
||||
InputObject_List: step.InputObject_List,
|
||||
OutputObject: step.OutputObject,
|
||||
AgentSelection: step.AgentSelection,
|
||||
Collaboration_Brief_frontEnd: step.Collaboration_Brief_frontEnd,
|
||||
TaskProcess: step.TaskProcess.map((action) => ({
|
||||
ActionType: action.ActionType,
|
||||
AgentName: action.AgentName,
|
||||
Description: action.Description,
|
||||
ID: action.ID,
|
||||
ImportantInput: action.ImportantInput,
|
||||
})),
|
||||
})),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
|
||||
/**
|
||||
* 优化版流式执行计划(支持动态追加步骤)
|
||||
@@ -182,23 +127,25 @@ class Api {
|
||||
onMessage: (event: StreamingEvent) => void,
|
||||
onError?: (error: Error) => void,
|
||||
onComplete?: () => void,
|
||||
useWebSocket?: boolean,
|
||||
_useWebSocket?: boolean,
|
||||
existingKeyObjects?: Record<string, any>,
|
||||
enableDynamic?: boolean,
|
||||
onExecutionStarted?: (executionId: string) => void,
|
||||
executionId?: string,
|
||||
restartFromStepIndex?: number, // 新增:从指定步骤重新执行的索引
|
||||
rehearsalLog?: any[], // 新增:传递截断后的 RehearsalLog
|
||||
restartFromStepIndex?: number,
|
||||
rehearsalLog?: any[],
|
||||
TaskID?: string,
|
||||
) => {
|
||||
const useWs = useWebSocket !== undefined ? useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
void _useWebSocket // 保留参数位置以保持兼容性
|
||||
const data = {
|
||||
RehearsalLog: rehearsalLog || [], // ✅ 使用传递的 RehearsalLog
|
||||
RehearsalLog: rehearsalLog || [], // 使用传递的 RehearsalLog
|
||||
num_StepToRun: null,
|
||||
existingKeyObjects: existingKeyObjects || {},
|
||||
enable_dynamic: enableDynamic || false,
|
||||
execution_id: executionId || null,
|
||||
restart_from_step_index: restartFromStepIndex ?? null, // 新增:传递重新执行索引
|
||||
task_id: TaskID || null, // 任务唯一标识,用于写入数据库
|
||||
plan: {
|
||||
'Initial Input Object': plan['Initial Input Object'],
|
||||
'General Goal': plan['General Goal'],
|
||||
@@ -220,103 +167,46 @@ class Api {
|
||||
},
|
||||
}
|
||||
|
||||
// 如果启用WebSocket且已连接,使用WebSocket
|
||||
if (useWs && websocket.connected) {
|
||||
websocket.subscribe(
|
||||
'execute_plan_optimized',
|
||||
data,
|
||||
// onProgress
|
||||
(progressData) => {
|
||||
try {
|
||||
let event: StreamingEvent
|
||||
websocket.subscribe(
|
||||
'execute_plan_optimized',
|
||||
data,
|
||||
// onProgress
|
||||
(progressData) => {
|
||||
try {
|
||||
let event: StreamingEvent
|
||||
|
||||
// 处理不同类型的progress数据
|
||||
if (typeof progressData === 'string') {
|
||||
event = JSON.parse(progressData)
|
||||
} else {
|
||||
event = progressData as StreamingEvent
|
||||
}
|
||||
|
||||
// 处理特殊事件类型
|
||||
if (event && typeof event === 'object') {
|
||||
// 检查是否是execution_started事件
|
||||
if ('status' in event && event.status === 'execution_started') {
|
||||
if ('execution_id' in event && onExecutionStarted) {
|
||||
onExecutionStarted(event.execution_id as string)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
onMessage(event)
|
||||
} catch (e) {
|
||||
// Failed to parse WebSocket data
|
||||
// 处理不同类型的progress数据
|
||||
if (typeof progressData === 'string') {
|
||||
event = JSON.parse(progressData)
|
||||
} else {
|
||||
event = progressData as StreamingEvent
|
||||
}
|
||||
},
|
||||
// onComplete
|
||||
() => {
|
||||
onComplete?.()
|
||||
},
|
||||
// onError
|
||||
(error) => {
|
||||
onError?.(error)
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// 否则使用原有的SSE方式
|
||||
// 处理特殊事件类型
|
||||
if (event && typeof event === 'object') {
|
||||
// 检查是否是execution_started事件
|
||||
if ('status' in event && event.status === 'execution_started') {
|
||||
if ('execution_id' in event && onExecutionStarted) {
|
||||
onExecutionStarted(event.execution_id as string)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
fetch('/api/executePlanOptimized', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
onMessage(event)
|
||||
} catch (e) {
|
||||
// Failed to parse WebSocket data
|
||||
}
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
|
||||
if (!reader) {
|
||||
throw new Error('Response body is null')
|
||||
}
|
||||
|
||||
let buffer = ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
|
||||
if (done) {
|
||||
onComplete?.()
|
||||
break
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const data = line.slice(6)
|
||||
try {
|
||||
const event = JSON.parse(data)
|
||||
onMessage(event)
|
||||
} catch (e) {
|
||||
// Failed to parse SSE data
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
// onComplete
|
||||
() => {
|
||||
onComplete?.()
|
||||
},
|
||||
// onError
|
||||
(error) => {
|
||||
onError?.(error)
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -329,38 +219,16 @@ class Api {
|
||||
Baseline_Completion: number
|
||||
initialInputs: string[]
|
||||
goal: string
|
||||
useWebSocket?: boolean
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
message?: string
|
||||
[key: string]: any
|
||||
}) => void
|
||||
}) => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// 如果启用WebSocket且已连接,使用WebSocket
|
||||
if (useWs && websocket.connected) {
|
||||
return websocket.send(
|
||||
'branch_plan_outline',
|
||||
{
|
||||
branch_Number: data.branch_Number,
|
||||
Modification_Requirement: data.Modification_Requirement,
|
||||
Existing_Steps: data.Existing_Steps,
|
||||
Baseline_Completion: data.Baseline_Completion,
|
||||
'Initial Input Object': data.initialInputs,
|
||||
'General Goal': data.goal,
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
}
|
||||
|
||||
// 否则使用REST API
|
||||
return request<unknown, IRawPlanResponse>({
|
||||
url: '/branch_PlanOutline',
|
||||
method: 'POST',
|
||||
data: {
|
||||
}) =>
|
||||
websocket.send(
|
||||
'branch_plan_outline',
|
||||
{
|
||||
branch_Number: data.branch_Number,
|
||||
Modification_Requirement: data.Modification_Requirement,
|
||||
Existing_Steps: data.Existing_Steps,
|
||||
@@ -368,8 +236,9 @@ class Api {
|
||||
'Initial Input Object': data.initialInputs,
|
||||
'General Goal': data.goal,
|
||||
},
|
||||
})
|
||||
}
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
|
||||
/**
|
||||
* 分支任务流程
|
||||
@@ -381,38 +250,16 @@ class Api {
|
||||
Baseline_Completion: number
|
||||
stepTaskExisting: any
|
||||
goal: string
|
||||
useWebSocket?: boolean
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
message?: string
|
||||
[key: string]: any
|
||||
}) => void
|
||||
}) => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// 如果启用WebSocket且已连接,使用WebSocket
|
||||
if (useWs && websocket.connected) {
|
||||
return websocket.send(
|
||||
'branch_task_process',
|
||||
{
|
||||
branch_Number: data.branch_Number,
|
||||
Modification_Requirement: data.Modification_Requirement,
|
||||
Existing_Steps: data.Existing_Steps,
|
||||
Baseline_Completion: data.Baseline_Completion,
|
||||
stepTaskExisting: data.stepTaskExisting,
|
||||
'General Goal': data.goal,
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
}
|
||||
|
||||
// 否则使用REST API
|
||||
return request<unknown, BranchAction[][]>({
|
||||
url: '/branch_TaskProcess',
|
||||
method: 'POST',
|
||||
data: {
|
||||
}) =>
|
||||
websocket.send(
|
||||
'branch_task_process',
|
||||
{
|
||||
branch_Number: data.branch_Number,
|
||||
Modification_Requirement: data.Modification_Requirement,
|
||||
Existing_Steps: data.Existing_Steps,
|
||||
@@ -420,14 +267,15 @@ class Api {
|
||||
stepTaskExisting: data.stepTaskExisting,
|
||||
'General Goal': data.goal,
|
||||
},
|
||||
})
|
||||
}
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
|
||||
fillStepTask = async (data: {
|
||||
goal: string
|
||||
stepTask: any
|
||||
generation_id?: string
|
||||
useWebSocket?: boolean
|
||||
TaskID?: string
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
@@ -435,72 +283,31 @@ class Api {
|
||||
[key: string]: any
|
||||
}) => void
|
||||
}): Promise<IRawStepTask> => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// 定义实际的 API 调用逻辑
|
||||
const executeRequest = async (): Promise<any> => {
|
||||
if (useWs && websocket.connected) {
|
||||
return await websocket.send(
|
||||
const rawResponse = await withRetry(
|
||||
() =>
|
||||
websocket.send(
|
||||
'fill_step_task',
|
||||
{
|
||||
'General Goal': data.goal,
|
||||
stepTask: data.stepTask,
|
||||
generation_id: data.generation_id || '',
|
||||
task_id: data.TaskID || '',
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
}
|
||||
// 否则使用REST API
|
||||
return await request<
|
||||
{
|
||||
'General Goal': string
|
||||
stepTask: any
|
||||
),
|
||||
{
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 2000,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
console.warn(` [fillStepTask] 第${attempt}次重试,等待 ${delay}ms...`, error?.message)
|
||||
},
|
||||
{
|
||||
AgentSelection?: string[]
|
||||
Collaboration_Brief_FrontEnd?: {
|
||||
template: string
|
||||
data: Record<string, { text: string; color: number[] }>
|
||||
}
|
||||
InputObject_List?: string[]
|
||||
OutputObject?: string
|
||||
StepName?: string
|
||||
TaskContent?: string
|
||||
TaskProcess?: Array<{
|
||||
ID: string
|
||||
ActionType: string
|
||||
AgentName: string
|
||||
Description: string
|
||||
ImportantInput: string[]
|
||||
}>
|
||||
}
|
||||
>({
|
||||
url: '/fill_stepTask',
|
||||
method: 'POST',
|
||||
data: {
|
||||
'General Goal': data.goal,
|
||||
stepTask: data.stepTask,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 使用重试机制执行请求
|
||||
const rawResponse = await withRetry(executeRequest, {
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 2000,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
console.warn(`⚠️ [fillStepTask] 第${attempt}次重试,等待 ${delay}ms...`, error?.message)
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// WebSocket 返回格式: { data: {...}, generation_id, execution_id }
|
||||
// REST API 返回格式: {...}
|
||||
const response = rawResponse.data || rawResponse
|
||||
|
||||
const vec2Hsl = (color: number[]): string => {
|
||||
const [h, s, l] = color
|
||||
return `hsl(${h}, ${s}%, ${l}%)`
|
||||
let response = this.extractResponse<any>(rawResponse)
|
||||
if (response?.filled_stepTask) {
|
||||
response = response.filled_stepTask
|
||||
}
|
||||
|
||||
const briefData: Record<string, { text: string; style?: Record<string, string> }> = {}
|
||||
@@ -509,15 +316,12 @@ class Api {
|
||||
briefData[key] = {
|
||||
text: (value as { text: string; color: number[] }).text,
|
||||
style: {
|
||||
background: vec2Hsl((value as { text: string; color: number[] }).color),
|
||||
background: this.vec2Hsl((value as { text: string; color: number[] }).color),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建前端格式的 IRawStepTask
|
||||
*/
|
||||
return {
|
||||
StepName: response.StepName || '',
|
||||
TaskContent: response.TaskContent || '',
|
||||
@@ -536,7 +340,7 @@ class Api {
|
||||
goal: string
|
||||
stepTask: IApiStepTask
|
||||
agents: string[]
|
||||
useWebSocket?: boolean
|
||||
TaskID?: string
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
@@ -544,15 +348,13 @@ class Api {
|
||||
[key: string]: any
|
||||
}) => void
|
||||
}): Promise<IApiStepTask> => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// 定义实际的 API 调用逻辑
|
||||
const executeRequest = async (): Promise<any> => {
|
||||
if (useWs && websocket.connected) {
|
||||
return await websocket.send(
|
||||
const rawResponse = await withRetry(
|
||||
() =>
|
||||
websocket.send(
|
||||
'fill_step_task_process',
|
||||
{
|
||||
'General Goal': data.goal,
|
||||
task_id: data.TaskID || undefined,
|
||||
stepTask_lackTaskProcess: {
|
||||
StepName: data.stepTask.name,
|
||||
TaskContent: data.stepTask.content,
|
||||
@@ -560,76 +362,26 @@ class Api {
|
||||
OutputObject: data.stepTask.output,
|
||||
AgentSelection: data.agents,
|
||||
},
|
||||
agents: data.agents,
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
}
|
||||
// 否则使用REST API
|
||||
return await request<
|
||||
{
|
||||
'General Goal': string
|
||||
stepTask_lackTaskProcess: {
|
||||
StepName: string
|
||||
TaskContent: string
|
||||
InputObject_List: string[]
|
||||
OutputObject: string
|
||||
AgentSelection: string[]
|
||||
}
|
||||
),
|
||||
{
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 2000,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
console.warn(
|
||||
`[fillStepTaskTaskProcess] 第${attempt}次重试,等待 ${delay}ms...`,
|
||||
error?.message,
|
||||
)
|
||||
},
|
||||
{
|
||||
StepName?: string
|
||||
TaskContent?: string
|
||||
InputObject_List?: string[]
|
||||
OutputObject?: string
|
||||
AgentSelection?: string[]
|
||||
TaskProcess?: Array<{
|
||||
ID: string
|
||||
ActionType: string
|
||||
AgentName: string
|
||||
Description: string
|
||||
ImportantInput: string[]
|
||||
}>
|
||||
Collaboration_Brief_FrontEnd?: {
|
||||
template: string
|
||||
data: Record<string, { text: string; color: number[] }>
|
||||
}
|
||||
}
|
||||
>({
|
||||
url: '/fill_stepTask_TaskProcess',
|
||||
method: 'POST',
|
||||
data: {
|
||||
'General Goal': data.goal,
|
||||
stepTask_lackTaskProcess: {
|
||||
StepName: data.stepTask.name,
|
||||
TaskContent: data.stepTask.content,
|
||||
InputObject_List: data.stepTask.inputs,
|
||||
OutputObject: data.stepTask.output,
|
||||
AgentSelection: data.agents,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 使用重试机制执行请求
|
||||
const rawResponse = await withRetry(executeRequest, {
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 2000,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
console.warn(
|
||||
`⚠️ [fillStepTaskTaskProcess] 第${attempt}次重试,等待 ${delay}ms...`,
|
||||
error?.message,
|
||||
)
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// WebSocket 返回格式: { data: {...}, generation_id, execution_id }
|
||||
// REST API 返回格式: {...}
|
||||
const response = rawResponse.data || rawResponse
|
||||
|
||||
const vec2Hsl = (color: number[]): string => {
|
||||
const [h, s, l] = color
|
||||
return `hsl(${h}, ${s}%, ${l}%)`
|
||||
let response = this.extractResponse<any>(rawResponse)
|
||||
if (response?.filled_stepTask) {
|
||||
response = response.filled_stepTask
|
||||
}
|
||||
|
||||
const briefData: Record<string, { text: string; style: { background: string } }> = {}
|
||||
@@ -638,7 +390,7 @@ class Api {
|
||||
briefData[key] = {
|
||||
text: (value as { text: string; color: number[] }).text,
|
||||
style: {
|
||||
background: vec2Hsl((value as { text: string; color: number[] }).color),
|
||||
background: this.vec2Hsl((value as { text: string; color: number[] }).color),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -672,7 +424,7 @@ class Api {
|
||||
agentSelectModifyInit = async (data: {
|
||||
goal: string
|
||||
stepTask: any
|
||||
useWebSocket?: boolean
|
||||
TaskID?: string
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
@@ -680,78 +432,54 @@ class Api {
|
||||
[key: string]: any
|
||||
}) => void
|
||||
}): Promise<Record<string, Record<string, { reason: string; score: number }>>> => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
|
||||
// 调试日志:打印请求参数
|
||||
const requestPayload = {
|
||||
'General Goal': data.goal,
|
||||
stepTask: {
|
||||
Id: data.stepTask.Id || data.stepTask.id,
|
||||
StepName: data.stepTask.StepName || data.stepTask.name,
|
||||
TaskContent: data.stepTask.TaskContent || data.stepTask.content,
|
||||
InputObject_List: data.stepTask.InputObject_List || data.stepTask.inputs,
|
||||
OutputObject: data.stepTask.OutputObject || data.stepTask.output,
|
||||
},
|
||||
task_id: data.TaskID || '',
|
||||
}
|
||||
console.log('🔍 [agentSelectModifyInit] 请求参数:', {
|
||||
goal: requestPayload['General Goal'],
|
||||
stepTaskName: requestPayload.stepTask.StepName,
|
||||
stepTaskContentLength: requestPayload.stepTask.TaskContent?.length,
|
||||
useWebSocket: useWs && websocket.connected,
|
||||
wsConnected: websocket.connected,
|
||||
})
|
||||
|
||||
// 定义实际的 API 调用逻辑
|
||||
const executeRequest = async (): Promise<
|
||||
Record<string, Record<string, { Reason: string; Score: number }>>
|
||||
> => {
|
||||
if (useWs && websocket.connected) {
|
||||
return await websocket.send(
|
||||
const rawResponse = await withRetry(
|
||||
() =>
|
||||
websocket.send(
|
||||
'agent_select_modify_init',
|
||||
requestPayload,
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
}
|
||||
// 否则使用REST API
|
||||
return await request<
|
||||
{
|
||||
'General Goal': string
|
||||
stepTask: any
|
||||
),
|
||||
{
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 2000,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
console.warn(
|
||||
`[agentSelectModifyInit] 第${attempt}次重试,等待 ${delay}ms...`,
|
||||
error?.message,
|
||||
)
|
||||
},
|
||||
Record<string, Record<string, { Reason: string; Score: number }>>
|
||||
>({
|
||||
url: '/agentSelectModify_init',
|
||||
method: 'POST',
|
||||
data: requestPayload,
|
||||
})
|
||||
}
|
||||
|
||||
// 使用重试机制执行请求
|
||||
const rawResponse = await withRetry(executeRequest, {
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 2000,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
console.warn(
|
||||
`⚠️ [agentSelectModifyInit] 第${attempt}次重试,等待 ${delay}ms...`,
|
||||
error?.message,
|
||||
)
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// WebSocket 返回格式: { data: {...}, generation_id, execution_id }
|
||||
// REST API 返回格式: {...}
|
||||
const response = rawResponse.data || rawResponse
|
||||
let response = this.extractResponse<any>(rawResponse)
|
||||
if (response?.scoreTable) {
|
||||
response = response.scoreTable
|
||||
}
|
||||
|
||||
const transformedData: Record<string, Record<string, { reason: string; score: number }>> = {}
|
||||
|
||||
// 确保 response 存在且是有效对象
|
||||
if (!response || typeof response !== 'object' || Array.isArray(response)) {
|
||||
console.warn('[agentSelectModifyInit] 后端返回数据格式异常:', response)
|
||||
return transformedData
|
||||
}
|
||||
|
||||
for (const [aspect, agents] of Object.entries(response)) {
|
||||
for (const [agentName, scoreInfo] of Object.entries(agents as Record<string, { Reason: string; Score: number }> || {})) {
|
||||
for (const [agentName, scoreInfo] of Object.entries(
|
||||
(agents as Record<string, { Reason: string; Score: number }>) || {},
|
||||
)) {
|
||||
if (!transformedData[agentName]) {
|
||||
transformedData[agentName] = {}
|
||||
}
|
||||
@@ -770,7 +498,14 @@ class Api {
|
||||
*/
|
||||
agentSelectModifyAddAspect = async (data: {
|
||||
aspectList: string[]
|
||||
useWebSocket?: boolean
|
||||
stepTask?: {
|
||||
Id?: string
|
||||
StepName?: string
|
||||
TaskContent?: string
|
||||
InputObject_List?: string[]
|
||||
OutputObject?: string
|
||||
}
|
||||
TaskID?: string
|
||||
onProgress?: (progress: {
|
||||
status: string
|
||||
stage?: string
|
||||
@@ -781,53 +516,33 @@ class Api {
|
||||
aspectName: string
|
||||
agentScores: Record<string, { score: number; reason: string }>
|
||||
}> => {
|
||||
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
|
||||
let response: Record<string, Record<string, { Reason: string; Score: number }>>
|
||||
const rawResponse = await websocket.send(
|
||||
'agent_select_modify_add_aspect',
|
||||
{
|
||||
aspectList: data.aspectList,
|
||||
stepTask: data.stepTask,
|
||||
task_id: data.TaskID || '',
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
|
||||
// 如果启用WebSocket且已连接,使用WebSocket
|
||||
if (useWs && websocket.connected) {
|
||||
const rawResponse = await websocket.send(
|
||||
'agent_select_modify_add_aspect',
|
||||
{
|
||||
aspectList: data.aspectList,
|
||||
},
|
||||
undefined,
|
||||
data.onProgress,
|
||||
)
|
||||
// WebSocket 返回格式: { data: {...}, generation_id, execution_id }
|
||||
response = rawResponse.data || rawResponse
|
||||
} else {
|
||||
// 否则使用REST API
|
||||
response = await request<
|
||||
{
|
||||
aspectList: string[]
|
||||
},
|
||||
Record<string, Record<string, { Reason: string; Score: number }>>
|
||||
>({
|
||||
url: '/agentSelectModify_addAspect',
|
||||
method: 'POST',
|
||||
data: {
|
||||
aspectList: data.aspectList,
|
||||
},
|
||||
})
|
||||
}
|
||||
const response = this.extractResponse<any>(rawResponse)
|
||||
|
||||
/**
|
||||
* 获取新添加的维度
|
||||
*/
|
||||
const newAspect = data.aspectList[data.aspectList.length - 1]
|
||||
if (!newAspect) {
|
||||
throw new Error('aspectList is empty')
|
||||
}
|
||||
|
||||
const newAspectAgents = response[newAspect]
|
||||
const scoreTable = response.scoreTable || response
|
||||
const newAspectAgents = scoreTable[newAspect]
|
||||
const agentScores: Record<string, { score: number; reason: string }> = {}
|
||||
|
||||
if (newAspectAgents) {
|
||||
for (const [agentName, scoreInfo] of Object.entries(newAspectAgents)) {
|
||||
for (const [agentName, scoreInfo] of Object.entries(newAspectAgents as Record<string, { Score?: number; score?: number; Reason?: string; reason?: string }>)) {
|
||||
agentScores[agentName] = {
|
||||
score: scoreInfo.Score,
|
||||
reason: scoreInfo.Reason,
|
||||
score: scoreInfo.Score || scoreInfo.score || 0,
|
||||
reason: scoreInfo.Reason || scoreInfo.reason || '',
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -867,12 +582,126 @@ class Api {
|
||||
})),
|
||||
})
|
||||
|
||||
// WebSocket 返回格式: { data: {...}, generation_id, execution_id }
|
||||
// REST API 返回格式: {...}
|
||||
const response = (rawResponse.data || rawResponse) as { added_count: number }
|
||||
const response = this.extractResponse<{ added_count: number }>(rawResponse)
|
||||
|
||||
return response?.added_count || 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存任务分支数据
|
||||
* @param taskId 任务ID
|
||||
* @param branches 分支数据数组
|
||||
* @returns 是否保存成功
|
||||
*/
|
||||
saveBranches = async (taskId: string, branches: any[]): Promise<boolean> => {
|
||||
if (!websocket.connected) {
|
||||
throw new Error('WebSocket未连接')
|
||||
}
|
||||
|
||||
try {
|
||||
const rawResponse = await websocket.send('save_branches', {
|
||||
task_id: taskId,
|
||||
branches,
|
||||
})
|
||||
|
||||
const response = this.extractResponse<{ status: string }>(rawResponse)
|
||||
return response?.status === 'success' || false
|
||||
} catch (error) {
|
||||
console.error('保存分支数据失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存任务过程分支数据
|
||||
* @param TaskID 大任务ID(数据库主键)
|
||||
* @param branches 任务过程分支数据(Map结构转对象)
|
||||
* @returns 是否保存成功
|
||||
*/
|
||||
saveTaskProcessBranches = async (
|
||||
TaskID: string,
|
||||
branches: Record<string, Record<string, any[]>>,
|
||||
): Promise<boolean> => {
|
||||
if (!websocket.connected) {
|
||||
throw new Error('WebSocket未连接')
|
||||
}
|
||||
|
||||
try {
|
||||
const rawResponse = await websocket.send('save_task_process_branches', {
|
||||
task_id: TaskID,
|
||||
branches,
|
||||
})
|
||||
|
||||
const response = this.extractResponse<{ status: string }>(rawResponse)
|
||||
return response?.status === 'success' || false
|
||||
} catch (error) {
|
||||
console.error('保存任务过程分支数据失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新任务大纲数据
|
||||
* @param taskId 任务ID
|
||||
* @param taskOutline 完整的大纲数据
|
||||
* @returns 是否更新成功
|
||||
*/
|
||||
updateTaskOutline = async (taskId: string, taskOutline: any): Promise<boolean> => {
|
||||
if (!websocket.connected) {
|
||||
throw new Error('WebSocket未连接')
|
||||
}
|
||||
|
||||
try {
|
||||
const rawResponse = await websocket.send('save_task_outline', {
|
||||
task_id: taskId,
|
||||
task_outline: taskOutline,
|
||||
})
|
||||
|
||||
const response = this.extractResponse<{ status: string }>(rawResponse)
|
||||
return response?.status === 'success' || false
|
||||
} catch (error) {
|
||||
console.error('更新任务大纲失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新指定步骤的 assigned_agents
|
||||
* @param params 参数对象
|
||||
* @returns 是否更新成功
|
||||
*/
|
||||
updateAssignedAgents = async (params: {
|
||||
task_id: string // 大任务ID(数据库主键)
|
||||
step_id: string // 步骤级ID(小任务UUID)
|
||||
agents: string[] // 选中的 agent 列表
|
||||
confirmed_groups?: string[][] // 可选:确认的 agent 组合列表
|
||||
agent_combinations?: Record<string, { process: any; brief: any }> // 可选:agent 组合的 TaskProcess 数据
|
||||
}): Promise<boolean> => {
|
||||
if (!websocket.connected) {
|
||||
throw new Error('WebSocket未连接')
|
||||
}
|
||||
|
||||
try {
|
||||
const rawResponse = await websocket.send('update_assigned_agents', {
|
||||
task_id: params.task_id,
|
||||
step_id: params.step_id,
|
||||
agents: params.agents,
|
||||
confirmed_groups: params.confirmed_groups,
|
||||
agent_combinations: params.agent_combinations,
|
||||
})
|
||||
|
||||
const response = this.extractResponse<{ status: string; error?: string }>(rawResponse)
|
||||
if (response?.status === 'success') {
|
||||
console.log('更新 assigned_agents 成功:', params)
|
||||
return true
|
||||
}
|
||||
console.warn('更新 assigned_agents 失败:', response?.error)
|
||||
return false
|
||||
} catch (error) {
|
||||
console.error('更新 assigned_agents 失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new Api()
|
||||
|
||||
Reference in New Issue
Block a user