sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] Enable LLM-driven structured output

Open jer96 opened this issue 1 year ago • 5 comments

Problem Statement

Currently, structured output does not have mechanisms for:

  1. validating and retrying structured output generation
  2. returning a typed object from the agent.structured_output invocation

Proposed Solution

The recommended interface would look something like this:

agent("do something")
thing = agent.structured_output(Thing, "Format something into 'Thing'")

This can also be expanded to enabling structured output directly on the agent invocation:

a: Thing = agent("do something", structure=Thing)

# or 

a: Thing = agent.invoke_async("do something", structure=Thing)

In order to enable validation of tool results, we must introduce a concrete implementation of a structured output validation tool. Currently, we only provide a toolSpec and when the model returns a toolCall we pass this along to the user. Instead, we should provide a concrete tool which attempts to create the user's desired type, if this cannot be done the model request can be retried up until a configurable timeout with appropriate failure messages.

Use Case

Customers using structured output expect reliability and the actual typed object in response to agent.structured_output

Alternatives Solutions

No response

Additional Context

No response

jer96 avatar Aug 22 '25 17:08 jer96

+1 Pydantic allows for model and class validations. We should be able to catch these exceptions, and ask the model to use it's context, and create the model correctly. There could be so many validations that can be done on an object. These can be defined by the user in the Model, in code or descriptions.

There is also a use case for including the first call to get the model's response, and add it to context, while the discussion about errors in the structured model could be ignored, instead of not adding anything to the context when structured_output is called.

keerthanvasist avatar Aug 31 '25 18:08 keerthanvasist

FYI This issue doesn't characterize how structured output works today. Indeed, the output does get serialized to the base model you provide in the method. https://github.com/strands-agents/sdk-python/blob/e7d95d6ad2c13dbde6257afbba96802822f70b26/src/strands/models/bedrock.py#L700

laithalsaadoon avatar Aug 31 '25 19:08 laithalsaadoon

I need functionality like so:

class StructuredAgent(Agent):
    async def structured_invoke_async(self, output_model: Type[T], prompt: AgentInput = None, max_retries: int = 3):
        print(colored(f"Invoking {self.__class__.__name__}", "red"))
        print(colored(f"Prompt: {prompt}", "red"))
        result = await self.invoke_async(prompt)
        retry_count = 0
        error_messages = []
        while retry_count < max_retries:
            try:
                prompt = result.message.get("content")[-1]["text"]
                if error_messages:
                    prompt = f"{prompt}\n Bear these in mind: {' '.join(error_messages)}"
                print(f"Retrying with prompt: {prompt}")
                return await self.structured_output_async(output_model, prompt)
            except ValueError as e:
                error_messages.append(str(e))
                retry_count += 1

Does Agent class already have it?

keerthanvasist avatar Sep 01 '25 00:09 keerthanvasist

+1, but I'm wondering if its less of a limitation and more of a design choice that hasn't been communicated.


My use case: I would like to ensure I receive a structured response when communicating to my agent via A2A.

If we have something like a: Thing = agent.invoke_async("do something", structure=Thing), then I initialize my agent as an A2AServer, I would also want the A2AServer to call the agent invoke/stream_async with the structured output model I initialized either the server or the agent with for structured responses. However this forces only one model for the entire Agent/A2A Server.

However what if instead of extending the Agent to handle this as part of the invoke/stream_async flow, we should be writing specialized agent tools (or wrapping existing tools), in something like this if we really wanted to ensure the structured response:

@tool
def structured_use_aws():
   # invoke agent.use_aws()
   # invoke agent.structured_output()
   # return structured response

In A2A if we treat the different agent tools as different request handlers that can be called (which seems like you can make an argument for this because in the SDK, the A2A skill card is auto-generated from tools), then this allows for the tools themselves to define their own structured output model.

Optionally, this could be done with @tool(structure=Thing) to handle that flow w/o having to write the boilerplate or our own decorator.


Implementation details and proposed solutions aside, structured_output won't be useful by default in an A2A context, so maybe there should be a callout on this as a limitation, or if/when its possible in the framework, have some canonical examples of how this is achieved.

bbckr avatar Sep 16 '25 13:09 bbckr

Hi, in 1.14.0 we introduced a new mechanism for structured_output which we expect to be much more robust. This deprecates the existing

agent.structured_output

pattern in favor of

result = agent(structured_output_model=SomeModel)
some_model: SomeModel = result.structured_output

You can read more about this here https://strandsagents.com/latest/documentation/docs/user-guide/concepts/agents/structured-output/#basic-usage

dbschmigelski avatar Oct 29 '25 19:10 dbschmigelski