File size: 10,231 Bytes
7b2787b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""
Pydantic Schemas for API Request/Response Models.

These schemas define the structure of data flowing through the API,
providing automatic validation and documentation.
"""

from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
from datetime import datetime
from enum import Enum


# ============================================================
# Enums
# ============================================================

class ExecutionStatus(str, Enum):
    """Status of a workflow execution."""
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"


# ============================================================
# Node Schemas
# ============================================================

class NodeDefinition(BaseModel):
    """Definition of a node in the graph."""
    name: str = Field(..., description="Unique name for the node")
    handler: str = Field(..., description="Name of the handler function (must be registered)")
    description: Optional[str] = Field(None, description="Human-readable description")
    
    class Config:
        json_schema_extra = {
            "example": {
                "name": "extract",
                "handler": "extract_functions",
                "description": "Extract function definitions from code"
            }
        }


# ============================================================
# Edge Schemas
# ============================================================

class ConditionalRoutes(BaseModel):
    """Routes for a conditional edge."""
    condition: str = Field(..., description="Name of the condition function")
    routes: Dict[str, str] = Field(
        ..., 
        description="Mapping of condition results to target nodes"
    )
    
    class Config:
        json_schema_extra = {
            "example": {
                "condition": "quality_check",
                "routes": {
                    "pass": "__END__",
                    "fail": "improve"
                }
            }
        }


# ============================================================
# Graph Schemas
# ============================================================

class GraphCreateRequest(BaseModel):
    """Request to create a new workflow graph."""
    name: str = Field(..., description="Name of the workflow")
    description: Optional[str] = Field(None, description="Description of what this workflow does")
    nodes: List[NodeDefinition] = Field(..., description="List of nodes in the graph")
    edges: Dict[str, str] = Field(
        default_factory=dict, 
        description="Direct edges: source -> target"
    )
    conditional_edges: Dict[str, ConditionalRoutes] = Field(
        default_factory=dict,
        description="Conditional edges with routing logic"
    )
    entry_point: Optional[str] = Field(None, description="Entry node (defaults to first node)")
    max_iterations: int = Field(100, description="Maximum loop iterations", ge=1, le=1000)
    
    class Config:
        json_schema_extra = {
            "example": {
                "name": "code_review_workflow",
                "description": "Automated code review with quality checks",
                "nodes": [
                    {"name": "extract", "handler": "extract_functions"},
                    {"name": "complexity", "handler": "calculate_complexity"},
                    {"name": "issues", "handler": "detect_issues"},
                    {"name": "improve", "handler": "suggest_improvements"}
                ],
                "edges": {
                    "extract": "complexity",
                    "complexity": "issues"
                },
                "conditional_edges": {
                    "issues": {
                        "condition": "quality_check",
                        "routes": {"pass": "__END__", "fail": "improve"}
                    },
                    "improve": {
                        "condition": "always_continue",
                        "routes": {"continue": "issues"}
                    }
                },
                "entry_point": "extract",
                "max_iterations": 10
            }
        }


class GraphCreateResponse(BaseModel):
    """Response after creating a graph."""
    graph_id: str = Field(..., description="Unique identifier for the created graph")
    name: str = Field(..., description="Name of the workflow")
    message: str = Field(default="Graph created successfully")
    node_count: int = Field(..., description="Number of nodes in the graph")
    
    class Config:
        json_schema_extra = {
            "example": {
                "graph_id": "abc123-def456",
                "name": "code_review_workflow",
                "message": "Graph created successfully",
                "node_count": 4
            }
        }


class GraphInfoResponse(BaseModel):
    """Response with graph information."""
    graph_id: str
    name: str
    description: Optional[str]
    node_count: int
    nodes: List[str]
    entry_point: Optional[str]
    max_iterations: int
    created_at: str
    mermaid_diagram: Optional[str] = Field(None, description="Mermaid diagram of the graph")


class GraphListResponse(BaseModel):
    """Response listing all graphs."""
    graphs: List[GraphInfoResponse]
    total: int


# ============================================================
# Run Schemas
# ============================================================

class GraphRunRequest(BaseModel):
    """Request to run a workflow graph."""
    graph_id: str = Field(..., description="ID of the graph to run")
    initial_state: Dict[str, Any] = Field(
        ..., 
        description="Initial state data for the workflow"
    )
    async_execution: bool = Field(
        False, 
        description="If true, run in background and return immediately"
    )
    
    class Config:
        json_schema_extra = {
            "example": {
                "graph_id": "abc123-def456",
                "initial_state": {
                    "code": "def hello():\n    print('world')",
                    "quality_threshold": 7.0
                },
                "async_execution": False
            }
        }


class ExecutionLogEntry(BaseModel):
    """A single entry in the execution log."""
    step: int
    node: str
    started_at: str
    completed_at: Optional[str]
    duration_ms: Optional[float]
    iteration: int
    result: str
    error: Optional[str]
    route_taken: Optional[str]


class GraphRunResponse(BaseModel):
    """Response after running a graph."""
    run_id: str = Field(..., description="Unique identifier for this run")
    graph_id: str
    status: ExecutionStatus
    final_state: Dict[str, Any]
    execution_log: List[ExecutionLogEntry]
    started_at: Optional[str]
    completed_at: Optional[str]
    total_duration_ms: Optional[float]
    iterations: int
    error: Optional[str] = None
    
    class Config:
        json_schema_extra = {
            "example": {
                "run_id": "run-xyz789",
                "graph_id": "abc123-def456",
                "status": "completed",
                "final_state": {
                    "code": "def hello():\n    print('world')",
                    "functions": [{"name": "hello"}],
                    "quality_score": 8.5
                },
                "execution_log": [
                    {
                        "step": 1,
                        "node": "extract",
                        "started_at": "2024-01-01T12:00:00",
                        "completed_at": "2024-01-01T12:00:01",
                        "duration_ms": 15.5,
                        "iteration": 0,
                        "result": "success",
                        "error": None,
                        "route_taken": None
                    }
                ],
                "started_at": "2024-01-01T12:00:00",
                "completed_at": "2024-01-01T12:00:05",
                "total_duration_ms": 5000.0,
                "iterations": 1,
                "error": None
            }
        }


class RunStateResponse(BaseModel):
    """Response with current run state."""
    run_id: str
    graph_id: str
    status: ExecutionStatus
    current_node: Optional[str]
    current_state: Dict[str, Any]
    iteration: int
    execution_log: List[ExecutionLogEntry]
    started_at: str
    completed_at: Optional[str]
    error: Optional[str]


class RunListResponse(BaseModel):
    """Response listing runs."""
    runs: List[RunStateResponse]
    total: int


# ============================================================
# Tool Schemas
# ============================================================

class ToolInfo(BaseModel):
    """Information about a registered tool."""
    name: str
    description: str
    parameters: Dict[str, str]


class ToolListResponse(BaseModel):
    """Response listing all registered tools."""
    tools: List[ToolInfo]
    total: int


class ToolRegisterRequest(BaseModel):
    """Request to register a new tool (for dynamic registration)."""
    name: str = Field(..., description="Unique name for the tool")
    description: str = Field("", description="Description of what the tool does")
    code: str = Field(..., description="Python code for the tool function")
    
    class Config:
        json_schema_extra = {
            "example": {
                "name": "custom_validator",
                "description": "Custom validation logic",
                "code": "def custom_validator(data):\n    return {'valid': True}"
            }
        }


class ToolRegisterResponse(BaseModel):
    """Response after registering a tool."""
    name: str
    message: str
    warning: Optional[str] = None


# ============================================================
# Error Schemas
# ============================================================

class ErrorResponse(BaseModel):
    """Standard error response."""
    error: str
    detail: Optional[str] = None
    status_code: int


class ValidationErrorResponse(BaseModel):
    """Validation error response."""
    error: str = "Validation Error"
    detail: List[Dict[str, Any]]
    status_code: int = 422