Use structured outputs with Pydantic models instead of text parsing

This commit is contained in:
2025-12-08 14:29:29 -05:00
parent 4df7bb42b4
commit 9e92fafd36
4 changed files with 203 additions and 118 deletions

View File

@@ -128,6 +128,7 @@ print(result.usage) # Token counts
```python
from claude_dspy import ClaudeCode, ClaudeCodeConfig
from pydantic import BaseModel, Field
import dspy
class BugReport(BaseModel):
severity: str = Field(description="critical, high, medium, or low")
@@ -137,9 +138,23 @@ class BugReport(BaseModel):
# Create config with Pydantic output
config = ClaudeCodeConfig()
# Option 1: Pre-construct signature in your module (where BugReport is defined)
sig = dspy.Signature("message:str -> report:BugReport")
agent = ClaudeCode(
config,
signature="message:str -> report:BugReport",
signature=sig,
working_directory="."
)
# Option 2: Use class-based signature (recommended)
class BugReportSignature(dspy.Signature):
"""Analyze bugs and generate report."""
message: str = dspy.InputField()
report: BugReport = dspy.OutputField()
agent = ClaudeCode(
config,
signature=BugReportSignature,
working_directory="."
)
@@ -148,6 +163,10 @@ print(result.report.severity) # Typed access!
print(result.report.affected_files)
```
**Note**: String signatures like `"message:str -> report:BugReport"` only work with built-in types unless you use `dspy.Signature()` with `custom_types`. For custom Pydantic models, either:
- Use `dspy.Signature("...", custom_types={...})`
- Use class-based signatures (recommended)
### Push to Modaic Hub
```python