Instructions: what the model is told
Instructions tell the model its job. They can be a fixed string, a function that runs at the start of every run, or extra text for one run.
The examples use a model function that answers with the instructions it received, so you can see exactly what a model would be sent:
from pydantic_ai import Agent, ModelResponse, TextPart
from pydantic_ai.models.function import FunctionModel
def show_instructions(messages, info):
return ModelResponse(parts=[TextPart(info.instructions or "(no instructions)")])
spy = FunctionModel(show_instructions)agent = Agent(spy, instructions="You answer support tickets for an online shop.")
print(agent.run_sync("hi").output)Instructions that change
shop_status = {"delayed": False} stands for something your app knows, like a delivery problem, and agent is the agent above.
@agent.instructions
def deliveries() -> str:
if shop_status["delayed"]:
return "Deliveries are running two days late. Say so when asked about a parcel."
return ""
print(agent.run_sync("hi").output)
print("---")
shop_status["delayed"] = True
print(agent.run_sync("hi").output)@agent.instructions registers a function that runs at the start of every run, so the model sees the shop as it is at that moment. Returning an empty string adds nothing. Lesson 11 gives these functions access to the customer and your database.
Instructions for one run
agent = Agent(spy, instructions="You answer support tickets for an online shop.")
print(agent.run_sync("hi", instructions="Reply in Hindi.").output)Text passed to run_sync is added for that run only. All the pieces are sent to the model as one string, separated by blank lines.
instructions or system_prompt
Agent also takes system_prompt, and there is an @agent.system_prompt decorator. The difference shows when a conversation continues, lesson 14: a system prompt is stored in the messages and sent again with them, while instructions are not stored, and every run sends the current agent's instructions. The Pydantic AI docs recommend instructions unless you need the old prompt kept.
- Register a second
@agent.instructionsfunction and check where its text appears. - Return
Nonefromdeliveriesinstead of an empty string. - Pass
instructions=["Be short.", "Be kind."]toAgent.
This is what real progress feels like.