Structured output¶
Get a typed result instead of text. There are two ways.
| Way | When to use |
|---|---|
agent.ask(state, prompt, returns=Type) |
During or after a run, to extract a result without changing the run |
A tool that calls state.finish(value) |
When the model should decide when it is done, and hand over the result itself |
ask¶
from dataclasses import dataclass
from pathlib import Path
from alpineagents import Agent, State
@dataclass
class Review:
approved: bool
reason: str
agent = Agent(model="claude-sonnet-5", system="You review code changes.")
state = State("Review this change:\n" + Path("change.diff").read_text())
agent.run(state)
review = agent.ask(state, "Should this change be merged?", returns=Review)
print(review.approved, review.reason)
agent.run(state)does the work.agent.ask(...)asks the model one more question about the same context.returns=Reviewmakes the answer aReviewobject.
About ask:
returnsacceptsstr, a dataclass or a Pydantic model.- The question and answer are recorded in
state.history, but not added to the context. The run continues as if the question was never asked. - The model cannot call tools while answering.
- If the answer does not fit
returns,askasks again up toretriestimes (default 2), then raisesOutputError. - After
state.finish(),askraisesValueError. So do not combine it with a submit tool on the same State.
A submit tool¶
The model fills the tool's typed parameters, and the tool ends the run with them. See Stop conditions: stop from a tool.