forked from longtao.wu/droboticflow
Include the accumulated workflow scheduling, run history, subtree rerun, operator UI, deployment, data asset, object storage, database browser, and documentation changes currently in the worktree.
718 lines
22 KiB
Go
718 lines
22 KiB
Go
package ai
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"droboticflow/internal/domain"
|
|
)
|
|
|
|
const (
|
|
defaultProvider = "dashscope-openai-compatible"
|
|
defaultRequestTimeout = 240 * time.Second
|
|
defaultMaxAttempts = 2
|
|
)
|
|
|
|
var ErrUnavailable = errors.New("AI service is not configured")
|
|
|
|
type Status struct {
|
|
Enabled bool `json:"enabled"`
|
|
Provider string `json:"provider"`
|
|
BaseURL string `json:"baseURL,omitempty"`
|
|
Model string `json:"model,omitempty"`
|
|
Reason string `json:"reason,omitempty"`
|
|
}
|
|
|
|
type GeneratedWorkflow struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Nodes []domain.WorkflowNode `json:"nodes"`
|
|
Edges []domain.WorkflowEdge `json:"edges"`
|
|
}
|
|
|
|
type GeneratedOperatorPort struct {
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Transmission string `json:"transmission"`
|
|
Description string `json:"description,omitempty"`
|
|
}
|
|
|
|
type GeneratedOperator struct {
|
|
Name string `json:"name"`
|
|
Category string `json:"category"`
|
|
Description string `json:"description"`
|
|
Inputs []GeneratedOperatorPort `json:"inputs"`
|
|
Outputs []GeneratedOperatorPort `json:"outputs"`
|
|
Hyperparams []domain.HyperParam `json:"hyperparams"`
|
|
SkillDefinition string `json:"skillDefinition"`
|
|
}
|
|
|
|
type Service interface {
|
|
Status() Status
|
|
GenerateWorkflow(context.Context, string, []domain.OperatorRecord) (*GeneratedWorkflow, error)
|
|
GenerateOperator(context.Context, string) (*GeneratedOperator, error)
|
|
}
|
|
|
|
type disabledService struct {
|
|
status Status
|
|
}
|
|
|
|
func NewDisabledService(baseURL string, model string, reason string) Service {
|
|
if strings.TrimSpace(reason) == "" {
|
|
reason = "AI 服务未配置"
|
|
}
|
|
return &disabledService{
|
|
status: Status{
|
|
Enabled: false,
|
|
Provider: defaultProvider,
|
|
BaseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
|
|
Model: strings.TrimSpace(model),
|
|
Reason: reason,
|
|
},
|
|
}
|
|
}
|
|
|
|
func (service *disabledService) Status() Status {
|
|
return service.status
|
|
}
|
|
|
|
func (service *disabledService) GenerateWorkflow(context.Context, string, []domain.OperatorRecord) (*GeneratedWorkflow, error) {
|
|
return nil, ErrUnavailable
|
|
}
|
|
|
|
func (service *disabledService) GenerateOperator(context.Context, string) (*GeneratedOperator, error) {
|
|
return nil, ErrUnavailable
|
|
}
|
|
|
|
type client struct {
|
|
httpClient *http.Client
|
|
baseURL string
|
|
apiKey string
|
|
model string
|
|
requestTimeout time.Duration
|
|
maxAttempts int
|
|
}
|
|
|
|
func NewService(baseURL string, apiKey string, model string) Service {
|
|
normalizedBaseURL := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
|
normalizedKey := strings.TrimSpace(apiKey)
|
|
normalizedModel := strings.TrimSpace(model)
|
|
if normalizedModel == "" {
|
|
normalizedModel = "glm-5"
|
|
}
|
|
if normalizedBaseURL == "" {
|
|
normalizedBaseURL = "https://coding.dashscope.aliyuncs.com/v1"
|
|
}
|
|
if normalizedKey == "" {
|
|
return NewDisabledService(normalizedBaseURL, normalizedModel, "服务端未配置 AI_API_KEY")
|
|
}
|
|
return &client{
|
|
httpClient: &http.Client{},
|
|
baseURL: normalizedBaseURL,
|
|
apiKey: normalizedKey,
|
|
model: normalizedModel,
|
|
requestTimeout: defaultRequestTimeout,
|
|
maxAttempts: defaultMaxAttempts,
|
|
}
|
|
}
|
|
|
|
func (client *client) Status() Status {
|
|
return Status{
|
|
Enabled: true,
|
|
Provider: defaultProvider,
|
|
BaseURL: client.baseURL,
|
|
Model: client.model,
|
|
}
|
|
}
|
|
|
|
type chatMessage struct {
|
|
Role string `json:"role"`
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
type chatCompletionRequest struct {
|
|
Model string `json:"model"`
|
|
Messages []chatMessage `json:"messages"`
|
|
Temperature float64 `json:"temperature,omitempty"`
|
|
}
|
|
|
|
type chatCompletionResponse struct {
|
|
Choices []struct {
|
|
Message struct {
|
|
Content any `json:"content"`
|
|
} `json:"message"`
|
|
} `json:"choices"`
|
|
Error *struct {
|
|
Message string `json:"message"`
|
|
} `json:"error,omitempty"`
|
|
}
|
|
|
|
type workflowPlan struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Nodes []workflowPlanNode `json:"nodes"`
|
|
Edges []workflowPlanEdge `json:"edges"`
|
|
}
|
|
|
|
type workflowPlanNode struct {
|
|
ID string `json:"id"`
|
|
Label string `json:"label,omitempty"`
|
|
OperatorID string `json:"operatorId"`
|
|
Position domain.Position `json:"position"`
|
|
HyperparamOverrides []domain.HyperParam `json:"hyperparamOverrides,omitempty"`
|
|
Bucket string `json:"bucket,omitempty"`
|
|
Prefix string `json:"prefix,omitempty"`
|
|
Pattern string `json:"pattern,omitempty"`
|
|
CPU string `json:"cpu,omitempty"`
|
|
Memory string `json:"memory,omitempty"`
|
|
}
|
|
|
|
type workflowPlanEdge struct {
|
|
ID string `json:"id"`
|
|
Source string `json:"source"`
|
|
Target string `json:"target"`
|
|
SourcePort string `json:"sourcePort,omitempty"`
|
|
TargetPort string `json:"targetPort,omitempty"`
|
|
}
|
|
|
|
func (client *client) GenerateWorkflow(ctx context.Context, description string, operators []domain.OperatorRecord) (*GeneratedWorkflow, error) {
|
|
if strings.TrimSpace(description) == "" {
|
|
return nil, fmt.Errorf("description is required")
|
|
}
|
|
if len(operators) == 0 {
|
|
return nil, fmt.Errorf("no operators available")
|
|
}
|
|
|
|
type operatorContext struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Category string `json:"category"`
|
|
Description string `json:"description"`
|
|
Inputs []domain.PortDefinition `json:"inputs"`
|
|
Outputs []domain.PortDefinition `json:"outputs"`
|
|
Image string `json:"image,omitempty"`
|
|
SkillDefinition string `json:"skillDefinition,omitempty"`
|
|
Hyperparams []domain.HyperParam `json:"hyperparams,omitempty"`
|
|
}
|
|
|
|
available := make([]operatorContext, 0, len(operators))
|
|
for _, operator := range operators {
|
|
available = append(available, operatorContext{
|
|
ID: operator.ID,
|
|
Name: operator.Name,
|
|
Category: operator.Category,
|
|
Description: operator.Description,
|
|
Inputs: operator.Inputs,
|
|
Outputs: operator.Outputs,
|
|
Image: operator.Image,
|
|
SkillDefinition: operator.SkillDefinition,
|
|
Hyperparams: operator.Hyperparams,
|
|
})
|
|
}
|
|
|
|
contextJSON, err := json.MarshalIndent(available, "", " ")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
systemPrompt := strings.TrimSpace(`
|
|
You are an expert workflow architect for Drobodata.
|
|
Return a single JSON object only. Do not wrap it in markdown.
|
|
|
|
Your task is to turn the user's requirement into a workflow PLAN using only the provided operators.
|
|
|
|
Rules:
|
|
1. Use only operatorId values from the provided operator catalog.
|
|
2. Nodes must be valid for Drobodata execution and connected in a runnable order.
|
|
3. For each edge, sourcePort and targetPort must match the real port names from the chosen operators.
|
|
4. Prefer batch workflows unless the user explicitly asks for streaming behavior.
|
|
5. Keep names short and production-oriented.
|
|
6. If a node needs operator-specific configuration, put it in hyperparamOverrides using real hyperparameter keys.
|
|
7. Never connect multiple upstream edges into the same target input port. One input port accepts only one incoming edge.
|
|
8. If the workflow needs to upload multiple result sets, create one upload node per result instead of merging them into the same upload input.
|
|
9. Output schema:
|
|
{
|
|
"name": "workflow short name",
|
|
"description": "short summary",
|
|
"nodes": [
|
|
{
|
|
"id": "node-source",
|
|
"label": "optional custom label",
|
|
"operatorId": "operator-id",
|
|
"position": {"x": 120, "y": 80},
|
|
"hyperparamOverrides": [{"key":"ENV_KEY","value":"ENV_VALUE","description":"optional"}],
|
|
"bucket": "optional storage bucket",
|
|
"prefix": "optional storage prefix",
|
|
"pattern": "optional filename pattern",
|
|
"cpu": "optional cpu limit",
|
|
"memory": "optional memory limit"
|
|
}
|
|
],
|
|
"edges": [
|
|
{
|
|
"id": "edge-1",
|
|
"source": "node-source",
|
|
"target": "node-next",
|
|
"sourcePort": "output port name",
|
|
"targetPort": "input port name"
|
|
}
|
|
]
|
|
}`)
|
|
|
|
userPrompt := fmt.Sprintf("User requirement:\n%s\n\nAvailable operators:\n%s", strings.TrimSpace(description), string(contextJSON))
|
|
|
|
var plan workflowPlan
|
|
if err := client.generateJSON(ctx, systemPrompt, userPrompt, &plan); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(plan.Nodes) == 0 {
|
|
return nil, fmt.Errorf("AI did not return any workflow nodes")
|
|
}
|
|
|
|
operatorByID := make(map[string]domain.OperatorRecord, len(operators))
|
|
nodes := make([]domain.WorkflowNode, 0, len(plan.Nodes))
|
|
for _, operator := range operators {
|
|
operatorByID[operator.ID] = operator
|
|
}
|
|
|
|
nodeByID := make(map[string]domain.WorkflowNode, len(plan.Nodes))
|
|
for _, item := range plan.Nodes {
|
|
operator, ok := operatorByID[item.OperatorID]
|
|
if !ok {
|
|
return nil, fmt.Errorf("AI selected unknown operator %q", item.OperatorID)
|
|
}
|
|
if strings.TrimSpace(item.ID) == "" {
|
|
return nil, fmt.Errorf("AI returned a workflow node without id")
|
|
}
|
|
node := domain.WorkflowNode{
|
|
ID: strings.TrimSpace(item.ID),
|
|
Type: "operator",
|
|
Data: domain.WorkflowNodeData{
|
|
Label: chooseValue(item.Label, operator.Name),
|
|
Category: operator.Category,
|
|
Description: operator.Description,
|
|
Inputs: clonePorts(operator.Inputs),
|
|
Outputs: clonePorts(operator.Outputs),
|
|
Image: operator.Image,
|
|
SkillDefinition: operator.SkillDefinition,
|
|
Hyperparams: mergeHyperparams(operator.Hyperparams, item.HyperparamOverrides),
|
|
Bucket: strings.TrimSpace(item.Bucket),
|
|
Prefix: strings.TrimSpace(item.Prefix),
|
|
Pattern: strings.TrimSpace(item.Pattern),
|
|
CPU: strings.TrimSpace(item.CPU),
|
|
Memory: strings.TrimSpace(item.Memory),
|
|
},
|
|
Position: item.Position,
|
|
}
|
|
nodes = append(nodes, node)
|
|
nodeByID[node.ID] = node
|
|
}
|
|
|
|
edges := make([]domain.WorkflowEdge, 0, len(plan.Edges))
|
|
for _, item := range plan.Edges {
|
|
if strings.TrimSpace(item.Source) == "" || strings.TrimSpace(item.Target) == "" {
|
|
return nil, fmt.Errorf("AI returned an edge without source/target")
|
|
}
|
|
sourceNode, sourceOK := nodeByID[item.Source]
|
|
targetNode, targetOK := nodeByID[item.Target]
|
|
if !sourceOK || !targetOK {
|
|
return nil, fmt.Errorf("AI returned an edge with unknown nodes: %s -> %s", item.Source, item.Target)
|
|
}
|
|
sourceHandle, err := resolvePortHandle(sourceNode.Data.Outputs, item.SourcePort)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolve source port for edge %s: %w", chooseValue(item.ID, item.Source+"-"+item.Target), err)
|
|
}
|
|
targetHandle, err := resolvePortHandle(targetNode.Data.Inputs, item.TargetPort)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolve target port for edge %s: %w", chooseValue(item.ID, item.Source+"-"+item.Target), err)
|
|
}
|
|
edges = append(edges, domain.WorkflowEdge{
|
|
ID: chooseValue(strings.TrimSpace(item.ID), "edge-"+item.Source+"-"+item.Target),
|
|
Source: item.Source,
|
|
Target: item.Target,
|
|
SourceHandle: sourceHandle,
|
|
TargetHandle: targetHandle,
|
|
})
|
|
}
|
|
if conflicts := domain.FindInputPortConflicts(nodes, edges); len(conflicts) > 0 {
|
|
return nil, fmt.Errorf("AI generated a workflow with multiple upstream edges feeding the same input port; split those branches or add separate upload operators for each result")
|
|
}
|
|
|
|
return &GeneratedWorkflow{
|
|
Name: chooseValue(strings.TrimSpace(plan.Name), "AI 生成工作流"),
|
|
Description: chooseValue(strings.TrimSpace(plan.Description), strings.TrimSpace(description)),
|
|
Nodes: nodes,
|
|
Edges: edges,
|
|
}, nil
|
|
}
|
|
|
|
func (client *client) GenerateOperator(ctx context.Context, description string) (*GeneratedOperator, error) {
|
|
if strings.TrimSpace(description) == "" {
|
|
return nil, fmt.Errorf("description is required")
|
|
}
|
|
|
|
systemPrompt := strings.TrimSpace(`
|
|
You are an expert Drobodata operator designer.
|
|
Return one JSON object only. Do not wrap it in markdown.
|
|
|
|
Allowed categories: IO, CV, AI, MATH, HUMAN, FLOW
|
|
Allowed port types: json, image, video, tensor, file
|
|
Allowed transmission values: bus, oss, shm, stream
|
|
|
|
Return schema:
|
|
{
|
|
"name": "short operator name",
|
|
"category": "AI",
|
|
"description": "1-2 sentence description",
|
|
"inputs": [{"name":"input","type":"json","transmission":"bus","description":"optional"}],
|
|
"outputs": [{"name":"result","type":"json","transmission":"bus","description":"optional"}],
|
|
"hyperparams": [{"key":"ENV_KEY","value":"default","description":"what it controls"}],
|
|
"skillDefinition": "detailed markdown instructions for future workflow generation and operator usage"
|
|
}`)
|
|
|
|
var generated GeneratedOperator
|
|
if err := client.generateJSON(ctx, systemPrompt, strings.TrimSpace(description), &generated); err != nil {
|
|
return nil, err
|
|
}
|
|
if strings.TrimSpace(generated.Name) == "" {
|
|
return nil, fmt.Errorf("AI did not return operator name")
|
|
}
|
|
if !validCategory(generated.Category) {
|
|
return nil, fmt.Errorf("AI returned unsupported operator category %q", generated.Category)
|
|
}
|
|
if err := validateGeneratedPorts(generated.Inputs); err != nil {
|
|
return nil, fmt.Errorf("invalid generated operator inputs: %w", err)
|
|
}
|
|
if err := validateGeneratedPorts(generated.Outputs); err != nil {
|
|
return nil, fmt.Errorf("invalid generated operator outputs: %w", err)
|
|
}
|
|
if strings.TrimSpace(generated.Description) == "" {
|
|
generated.Description = strings.TrimSpace(description)
|
|
}
|
|
if strings.TrimSpace(generated.SkillDefinition) == "" {
|
|
generated.SkillDefinition = generated.Description
|
|
}
|
|
return &generated, nil
|
|
}
|
|
|
|
func (client *client) generateJSON(ctx context.Context, systemPrompt string, userPrompt string, target any) error {
|
|
requestBody, err := json.Marshal(chatCompletionRequest{
|
|
Model: client.model,
|
|
Messages: []chatMessage{
|
|
{Role: "system", Content: systemPrompt},
|
|
{Role: "user", Content: userPrompt},
|
|
},
|
|
Temperature: 0.1,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
payload, err := client.chatCompletion(ctx, requestBody)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var completion chatCompletionResponse
|
|
if err := json.Unmarshal(payload, &completion); err != nil {
|
|
return fmt.Errorf("decode AI response: %w", err)
|
|
}
|
|
if completion.Error != nil && strings.TrimSpace(completion.Error.Message) != "" {
|
|
return errors.New(completion.Error.Message)
|
|
}
|
|
if len(completion.Choices) == 0 {
|
|
return fmt.Errorf("AI response does not contain choices")
|
|
}
|
|
|
|
content := normalizeMessageContent(completion.Choices[0].Message.Content)
|
|
if strings.TrimSpace(content) == "" {
|
|
return fmt.Errorf("AI response content is empty")
|
|
}
|
|
parsedJSON, err := extractJSONObject(content)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := json.Unmarshal([]byte(parsedJSON), target); err != nil {
|
|
return fmt.Errorf("decode AI JSON payload: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type httpStatusError struct {
|
|
StatusCode int
|
|
Body string
|
|
}
|
|
|
|
func (err *httpStatusError) Error() string {
|
|
body := strings.TrimSpace(err.Body)
|
|
if body == "" {
|
|
return fmt.Sprintf("AI request failed with status %d", err.StatusCode)
|
|
}
|
|
return fmt.Sprintf("AI request failed with status %d: %s", err.StatusCode, body)
|
|
}
|
|
|
|
func (client *client) chatCompletion(ctx context.Context, requestBody []byte) ([]byte, error) {
|
|
attempts := client.maxAttempts
|
|
if attempts < 1 {
|
|
attempts = 1
|
|
}
|
|
|
|
var lastErr error
|
|
for attempt := 1; attempt <= attempts; attempt++ {
|
|
payload, err := client.chatCompletionOnce(ctx, requestBody)
|
|
if err == nil {
|
|
return payload, nil
|
|
}
|
|
lastErr = err
|
|
if !isRetriableAIError(err) || attempt == attempts || ctx.Err() != nil {
|
|
break
|
|
}
|
|
if err := sleepWithContext(ctx, time.Duration(attempt)*2*time.Second); err != nil {
|
|
lastErr = err
|
|
break
|
|
}
|
|
}
|
|
return nil, normalizeAIError(lastErr)
|
|
}
|
|
|
|
func (client *client) chatCompletionOnce(ctx context.Context, requestBody []byte) ([]byte, error) {
|
|
requestCtx := ctx
|
|
cancel := func() {}
|
|
if _, hasDeadline := ctx.Deadline(); !hasDeadline && client.requestTimeout > 0 {
|
|
requestCtx, cancel = context.WithTimeout(ctx, client.requestTimeout)
|
|
}
|
|
defer cancel()
|
|
|
|
request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, client.baseURL+"/chat/completions", bytes.NewReader(requestBody))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
request.Header.Set("Authorization", "Bearer "+client.apiKey)
|
|
request.Header.Set("Content-Type", "application/json")
|
|
|
|
response, err := client.httpClient.Do(request)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer response.Body.Close()
|
|
|
|
payload, err := io.ReadAll(response.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if response.StatusCode >= 400 {
|
|
return nil, &httpStatusError{
|
|
StatusCode: response.StatusCode,
|
|
Body: string(payload),
|
|
}
|
|
}
|
|
return payload, nil
|
|
}
|
|
|
|
func isRetriableAIError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if errors.Is(err, context.DeadlineExceeded) || isTimeoutError(err) {
|
|
return true
|
|
}
|
|
var statusErr *httpStatusError
|
|
if errors.As(err, &statusErr) {
|
|
return statusErr.StatusCode == http.StatusTooManyRequests ||
|
|
statusErr.StatusCode == http.StatusRequestTimeout ||
|
|
statusErr.StatusCode >= http.StatusInternalServerError
|
|
}
|
|
return false
|
|
}
|
|
|
|
func isTimeoutError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
var netErr net.Error
|
|
if errors.As(err, &netErr) && netErr.Timeout() {
|
|
return true
|
|
}
|
|
return strings.Contains(strings.ToLower(err.Error()), "client.timeout")
|
|
}
|
|
|
|
func normalizeAIError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if errors.Is(err, context.DeadlineExceeded) || isTimeoutError(err) {
|
|
return fmt.Errorf("AI 生成超时,请稍后重试,或缩短描述范围后再试")
|
|
}
|
|
var statusErr *httpStatusError
|
|
if errors.As(err, &statusErr) {
|
|
switch {
|
|
case statusErr.StatusCode == http.StatusTooManyRequests:
|
|
return fmt.Errorf("AI 服务当前限流,请稍后重试")
|
|
case statusErr.StatusCode == http.StatusRequestTimeout:
|
|
return fmt.Errorf("AI 服务响应超时,请稍后重试")
|
|
case statusErr.StatusCode >= http.StatusInternalServerError:
|
|
return fmt.Errorf("AI 服务暂时不可用,请稍后重试")
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
func sleepWithContext(ctx context.Context, duration time.Duration) error {
|
|
timer := time.NewTimer(duration)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-timer.C:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func normalizeMessageContent(content any) string {
|
|
switch value := content.(type) {
|
|
case string:
|
|
return value
|
|
case []any:
|
|
parts := make([]string, 0, len(value))
|
|
for _, item := range value {
|
|
typed, ok := item.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if text, ok := typed["text"].(string); ok {
|
|
parts = append(parts, text)
|
|
}
|
|
}
|
|
return strings.Join(parts, "\n")
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func extractJSONObject(raw string) (string, error) {
|
|
trimmed := strings.TrimSpace(raw)
|
|
trimmed = strings.TrimPrefix(trimmed, "```json")
|
|
trimmed = strings.TrimPrefix(trimmed, "```")
|
|
trimmed = strings.TrimSuffix(trimmed, "```")
|
|
trimmed = strings.TrimSpace(trimmed)
|
|
start := strings.Index(trimmed, "{")
|
|
end := strings.LastIndex(trimmed, "}")
|
|
if start < 0 || end < start {
|
|
return "", fmt.Errorf("AI response is not a JSON object")
|
|
}
|
|
return trimmed[start : end+1], nil
|
|
}
|
|
|
|
func clonePorts(ports []domain.PortDefinition) []domain.PortDefinition {
|
|
items := make([]domain.PortDefinition, len(ports))
|
|
copy(items, ports)
|
|
return items
|
|
}
|
|
|
|
func mergeHyperparams(base []domain.HyperParam, overrides []domain.HyperParam) []domain.HyperParam {
|
|
if len(base) == 0 && len(overrides) == 0 {
|
|
return []domain.HyperParam{}
|
|
}
|
|
merged := make([]domain.HyperParam, len(base))
|
|
copy(merged, base)
|
|
indexByKey := make(map[string]int, len(merged))
|
|
for index, item := range merged {
|
|
indexByKey[strings.ToUpper(strings.TrimSpace(item.Key))] = index
|
|
}
|
|
for _, item := range overrides {
|
|
key := strings.ToUpper(strings.TrimSpace(item.Key))
|
|
if key == "" {
|
|
continue
|
|
}
|
|
item.Key = strings.TrimSpace(item.Key)
|
|
if index, ok := indexByKey[key]; ok {
|
|
if strings.TrimSpace(item.Value) != "" {
|
|
merged[index].Value = item.Value
|
|
}
|
|
if strings.TrimSpace(item.Description) != "" {
|
|
merged[index].Description = item.Description
|
|
}
|
|
if strings.TrimSpace(item.Type) != "" {
|
|
merged[index].Type = item.Type
|
|
}
|
|
continue
|
|
}
|
|
merged = append(merged, item)
|
|
indexByKey[key] = len(merged) - 1
|
|
}
|
|
return merged
|
|
}
|
|
|
|
func resolvePortHandle(ports []domain.PortDefinition, name string) (string, error) {
|
|
normalizedName := strings.TrimSpace(strings.ToLower(name))
|
|
if normalizedName == "" {
|
|
if len(ports) == 1 {
|
|
return ports[0].ID, nil
|
|
}
|
|
return "", fmt.Errorf("port name is required when multiple ports are available")
|
|
}
|
|
for _, port := range ports {
|
|
if strings.ToLower(strings.TrimSpace(port.Name)) == normalizedName || strings.ToLower(strings.TrimSpace(port.ID)) == normalizedName {
|
|
return port.ID, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("port %q not found", name)
|
|
}
|
|
|
|
func chooseValue(value string, fallback string) string {
|
|
if strings.TrimSpace(value) == "" {
|
|
return fallback
|
|
}
|
|
return strings.TrimSpace(value)
|
|
}
|
|
|
|
func validCategory(value string) bool {
|
|
switch strings.ToUpper(strings.TrimSpace(value)) {
|
|
case "IO", "CV", "AI", "MATH", "HUMAN", "FLOW":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func validPortType(value string) bool {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "json", "image", "video", "tensor", "file":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func validTransmission(value string) bool {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "bus", "oss", "shm", "stream":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func validateGeneratedPorts(ports []GeneratedOperatorPort) error {
|
|
for _, port := range ports {
|
|
if strings.TrimSpace(port.Name) == "" {
|
|
return fmt.Errorf("port name is required")
|
|
}
|
|
if !validPortType(port.Type) {
|
|
return fmt.Errorf("unsupported port type %q", port.Type)
|
|
}
|
|
if !validTransmission(port.Transmission) {
|
|
return fmt.Errorf("unsupported transmission %q", port.Transmission)
|
|
}
|
|
}
|
|
return nil
|
|
}
|