Skip to content

Commit 477a590

Browse files
giacbrdgiacbrd
andauthored
Ignore dynamic instructions returning an empty string (#1961)
Co-authored-by: giacbrd <giacomo.brd@gmail.com>
1 parent e3e435e commit 477a590

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

docs/agents.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,6 +701,8 @@ _(This example is complete, it can be run "as is")_
701701

702702
You can also dynamically change the instructions for an agent by using the `@agent.instructions` decorator.
703703

704+
Note that returning an empty string will result in no instruction message added.
705+
704706
```python {title="dynamic_instructions.py"}
705707
from datetime import date
706708

pydantic_ai_slim/pydantic_ai/agent.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -669,10 +669,11 @@ async def get_instructions(run_context: RunContext[AgentDepsT]) -> str | None:
669669
if self._instructions is None and not self._instructions_functions:
670670
return None
671671

672-
instructions = self._instructions or ''
672+
instructions = [self._instructions] if self._instructions else []
673673
for instructions_runner in self._instructions_functions:
674-
instructions += '\n' + await instructions_runner.run(run_context)
675-
return instructions.strip()
674+
instructions.append(await instructions_runner.run(run_context))
675+
concatenated_instructions = '\n'.join(instruction for instruction in instructions if instruction)
676+
return concatenated_instructions.strip() if concatenated_instructions else None
676677

677678
# Copy the function tools so that retry state is agent-run-specific
678679
# Note that the retry count is reset to 0 when this happens due to the `default=0` and `init=False`.

tests/test_agent.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2425,6 +2425,10 @@ def test_instructions_raise_error_when_instructions_is_set():
24252425
def instructions() -> str:
24262426
return 'An instructions!'
24272427

2428+
@agent.instructions
2429+
def empty_instructions() -> str:
2430+
return ''
2431+
24282432
result = agent.run_sync('Hello')
24292433
assert result.all_messages()[0] == snapshot(
24302434
ModelRequest(
@@ -2512,7 +2516,10 @@ def test_instructions_parameter_with_sequence():
25122516
def instructions() -> str:
25132517
return 'You are a potato.'
25142518

2515-
agent = Agent('test', instructions=('You are a helpful assistant.', instructions))
2519+
def empty_instructions() -> str:
2520+
return ''
2521+
2522+
agent = Agent('test', instructions=('You are a helpful assistant.', empty_instructions, instructions))
25162523
result = agent.run_sync('Hello')
25172524
assert result.all_messages()[0] == snapshot(
25182525
ModelRequest(

0 commit comments

Comments
 (0)