Skip to content

Commit b7a2870

Browse files
authored
Reuse last request from message history if no user prompt was provided (#1955)
1 parent 2fce134 commit b7a2870

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

pydantic_ai_slim/pydantic_ai/_agent_graph.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,16 @@ async def _prepare_messages(
183183

184184
if user_prompt is not None:
185185
parts.append(_messages.UserPromptPart(user_prompt))
186+
elif (
187+
len(parts) == 0
188+
and message_history
189+
and (last_message := message_history[-1])
190+
and isinstance(last_message, _messages.ModelRequest)
191+
):
192+
# Drop last message that came from history and reuse its parts
193+
messages.pop()
194+
parts.extend(last_message.parts)
195+
186196
return messages, _messages.ModelRequest(parts, instructions=instructions)
187197

188198
async def _reevaluate_dynamic_prompts(

tests/test_agent.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1417,6 +1417,36 @@ async def ret_a(x: str) -> str:
14171417
assert result2.new_messages_json().startswith(b'[{"parts":[{"content":"Hello again",')
14181418

14191419

1420+
def test_run_with_history_and_no_user_prompt():
1421+
messages: list[ModelMessage] = [
1422+
ModelRequest(parts=[UserPromptPart(content='Hello')], instructions='Original instructions'),
1423+
]
1424+
1425+
m = TestModel()
1426+
agent = Agent(m, instructions='New instructions')
1427+
1428+
result = agent.run_sync(message_history=messages)
1429+
assert result.all_messages() == snapshot(
1430+
[
1431+
ModelRequest(
1432+
parts=[
1433+
UserPromptPart(
1434+
content='Hello',
1435+
timestamp=IsDatetime(),
1436+
)
1437+
],
1438+
instructions='New instructions',
1439+
),
1440+
ModelResponse(
1441+
parts=[TextPart(content='success (no tool calls)')],
1442+
usage=Usage(requests=1, request_tokens=51, response_tokens=4, total_tokens=55),
1443+
model_name='test',
1444+
timestamp=IsDatetime(),
1445+
),
1446+
]
1447+
)
1448+
1449+
14201450
def test_empty_tool_calls():
14211451
def empty(_: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
14221452
return ModelResponse(parts=[])

0 commit comments

Comments
 (0)