Skip to content

Commit e7ce675

Browse files
timeslerDouweM
andauthored
Add newline separation between Anthropic system prompts (#1638)
Co-authored-by: Douwe Maan <[email protected]>
1 parent 017905c commit e7ce675

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

pydantic_ai_slim/pydantic_ai/models/anthropic.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ def _get_tools(self, model_request_parameters: ModelRequestParameters) -> list[T
284284

285285
async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[MessageParam]]:
286286
"""Just maps a `pydantic_ai.Message` to a `anthropic.types.MessageParam`."""
287-
system_prompt: str = ''
287+
system_prompt_parts: list[str] = []
288288
anthropic_messages: list[MessageParam] = []
289289
for m in messages:
290290
if isinstance(m, ModelRequest):
@@ -293,7 +293,7 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Me
293293
] = []
294294
for request_part in m.parts:
295295
if isinstance(request_part, SystemPromptPart):
296-
system_prompt += request_part.content
296+
system_prompt_parts.append(request_part.content)
297297
elif isinstance(request_part, UserPromptPart):
298298
async for content in self._map_user_prompt(request_part):
299299
user_content_params.append(content)
@@ -333,6 +333,7 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Me
333333
anthropic_messages.append(MessageParam(role='assistant', content=assistant_content_params))
334334
else:
335335
assert_never(m)
336+
system_prompt = '\n\n'.join(system_prompt_parts)
336337
if instructions := self._get_instructions(messages):
337338
system_prompt = f'{instructions}\n\n{system_prompt}'
338339
return system_prompt, anthropic_messages

tests/models/test_anthropic.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,22 @@ def simple_instructions():
927927
)
928928

929929

930+
async def test_multiple_system_prompt_formatting(allow_model_requests: None):
931+
c = completion_message([TextBlock(text='world', type='text')], AnthropicUsage(input_tokens=5, output_tokens=10))
932+
mock_client = MockAnthropic().create_mock(c)
933+
m = AnthropicModel('claude-3-5-haiku-latest', provider=AnthropicProvider(anthropic_client=mock_client))
934+
agent = Agent(m, system_prompt='this is the system prompt')
935+
936+
@agent.system_prompt
937+
def system_prompt() -> str:
938+
return 'and this is another'
939+
940+
await agent.run('hello')
941+
completion_kwargs = get_mock_chat_completion_kwargs(mock_client)[0]
942+
assert 'system' in completion_kwargs
943+
assert completion_kwargs['system'] == 'this is the system prompt\n\nand this is another'
944+
945+
930946
def anth_msg(usage: AnthropicUsage) -> AnthropicMessage:
931947
return AnthropicMessage(
932948
id='x',

0 commit comments

Comments
 (0)