Skip to content

Instruction seems to be ignored in back to back agent calls with tool output #3207

@nicolas-chaulet

Description

@nicolas-chaulet

Initial Checks

Description

When running two agents one after the next and passing the conversation history from the first to the second AND the second outputs structured output AND there is no user prompt, instructions of the second agent are ignored and the first agent's instructions are used instead. Removing the structured output or passing a user prompt fixes the issue for some reason. Code to reproduce below with logfire trace, you'll notice that the agent.run spans are correct but the second nested openai gpt call is not

Example Code

from pydantic import BaseModel, Field
from pydantic_ai import Agent


class Suggestions(BaseModel):
    """Suggestion for what the user might want to do next. Suggest things based on previous action and what you can do for them."""

    suggestion: str = Field(..., description="Should be very short (a few words)")


agent1 = Agent("openai:gpt-4.1-nano", instructions="You are a first helpful assistant.")
agent2 = Agent(
    "openai:gpt-4.1-nano",
    instructions="You are a second helpful assistant.",
    output_type=Suggestions,
)

import logfire

# configure logfire
logfire.configure(send_to_logfire="if-token-present")
logfire.instrument_pydantic_ai()
logfire.instrument_google_genai()


class LinearWorkflow:
    """A workflow that runs a sequence of agents linearly, passing the output of one as input to the next."""

    def __init__(self, agents) -> None:
        self._agents = agents

    async def run(
        self,
        *,
        message_history,
    ):
        with logfire.span("LinearWorkflow.run"):
            current_history = [*message_history] or []  # Don't mutate input list

            for agent in self._agents:
                result = await agent.run(
                    message_history=current_history,
                )
                current_history.extend(result.new_messages())

            return result


async def bug_multi_agent() -> Agent[None, None]:
    workflow = LinearWorkflow([agent1, agent2])
    result = await workflow.run(
        message_history=[
            {"role": "user", "content": "Hello, how are you?"},
        ],
    )
    print("Final output:", result.output)


if __name__ == "__main__":
    import asyncio

    asyncio.run(bug_multi_agent())


# Public logfire trace:
# https://logfire-eu.pydantic.dev/public-trace/2572b9ff-0097-4722-ba56-062ff3ec29a2?spanId=db9af09001760713
Image

Python, Pydantic AI & LLM client version

Pydantic AI 1.2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions