|
| 1 | +import os |
| 2 | +import asyncio |
| 3 | +import logging |
| 4 | +from typing import List |
| 5 | + |
| 6 | +from openai.types.chat.chat_completion_assistant_message_param import ChatCompletionAssistantMessageParam |
| 7 | + |
| 8 | +from eval_protocol.models import EvaluationRow, Message |
| 9 | +from eval_protocol.pytest.rollout_processor import RolloutProcessor |
| 10 | +from eval_protocol.pytest.types import RolloutProcessorConfig |
| 11 | +from openai.types.chat import ChatCompletion, ChatCompletionMessageParam |
| 12 | +from openai.types.chat.chat_completion import Choice as ChatCompletionChoice |
| 13 | + |
| 14 | +from pydantic_ai.models.openai import OpenAIModel |
| 15 | +from pydantic import TypeAdapter |
| 16 | +from pydantic_ai.messages import ModelMessage |
| 17 | +from pydantic_ai._utils import generate_tool_call_id |
| 18 | +from pydantic_ai import Agent |
| 19 | +from pydantic_ai.messages import ( |
| 20 | + ModelRequest, |
| 21 | + SystemPromptPart, |
| 22 | + ToolReturnPart, |
| 23 | + UserPromptPart, |
| 24 | +) |
| 25 | +from pydantic_ai.providers.openai import OpenAIProvider |
| 26 | +from pydantic_ai.providers.fireworks import FireworksProvider |
| 27 | + |
| 28 | +logger = logging.getLogger(__name__) |
| 29 | + |
| 30 | + |
| 31 | +class PydanticAgentRolloutProcessor(RolloutProcessor): |
| 32 | + """Rollout processor for Pydantic AI agents. Mainly converts |
| 33 | + EvaluationRow.messages to and from Pydantic AI ModelMessage format.""" |
| 34 | + |
| 35 | + def __init__(self): |
| 36 | + # dummy model used for its helper functions for processing messages |
| 37 | + self.util = OpenAIModel("dummy-model", provider=OpenAIProvider(api_key="dummy")) |
| 38 | + |
| 39 | + def __call__(self, rows: List[EvaluationRow], config: RolloutProcessorConfig) -> List[asyncio.Task[EvaluationRow]]: |
| 40 | + """Create agent rollout tasks and return them for external handling.""" |
| 41 | + |
| 42 | + max_concurrent = getattr(config, "max_concurrent_rollouts", 8) or 8 |
| 43 | + semaphore = asyncio.Semaphore(max_concurrent) |
| 44 | + |
| 45 | + # validate that the "agent" field is present with a valid Pydantic AI Agent instance in the completion_params dict |
| 46 | + if "agent" not in config.kwargs: |
| 47 | + raise ValueError("kwargs must contain an 'agent' field with a valid Pydantic AI Agent instance") |
| 48 | + if not isinstance(config.kwargs["agent"], Agent): |
| 49 | + raise ValueError("kwargs['agent'] must be a valid Pydantic AI Agent instance") |
| 50 | + |
| 51 | + agent: Agent = config.kwargs["agent"] |
| 52 | + |
| 53 | + model = OpenAIModel( |
| 54 | + config.completion_params["model"], |
| 55 | + provider=config.completion_params["provider"], |
| 56 | + ) |
| 57 | + |
| 58 | + async def process_row(row: EvaluationRow) -> EvaluationRow: |
| 59 | + """Process a single row with agent rollout.""" |
| 60 | + model_messages = [self.convert_ep_message_to_pyd_message(m, row) for m in row.messages] |
| 61 | + response = await agent.run(message_history=model_messages, model=model) |
| 62 | + row.messages = await self.convert_pyd_message_to_ep_message(response.all_messages()) |
| 63 | + return row |
| 64 | + |
| 65 | + async def _sem_wrapper(r: EvaluationRow) -> EvaluationRow: |
| 66 | + async with semaphore: |
| 67 | + result = await process_row(r) |
| 68 | + return result |
| 69 | + |
| 70 | + # Create and return tasks for external handling |
| 71 | + tasks = [asyncio.create_task(_sem_wrapper(row)) for row in rows] |
| 72 | + return tasks |
| 73 | + |
| 74 | + async def convert_pyd_message_to_ep_message(self, messages: list[ModelMessage]) -> list[Message]: |
| 75 | + oai_messages: list[ChatCompletionMessageParam] = await self.util._map_messages(messages) |
| 76 | + return [Message(**m) for m in oai_messages] |
| 77 | + |
| 78 | + def convert_ep_message_to_pyd_message(self, message: Message, row: EvaluationRow) -> ModelMessage: |
| 79 | + if message.role == "assistant": |
| 80 | + type_adapter = TypeAdapter(ChatCompletionAssistantMessageParam) |
| 81 | + oai_message = type_adapter.validate_python(message) |
| 82 | + # Fix: Provide required finish_reason and index, and ensure created is int (timestamp) |
| 83 | + return self.util._process_response( |
| 84 | + ChatCompletion( |
| 85 | + choices=[ChatCompletionChoice(message=oai_message, finish_reason="stop", index=0)], |
| 86 | + object="chat.completion", |
| 87 | + model="", |
| 88 | + id="", |
| 89 | + created=( |
| 90 | + int(row.created_at.timestamp()) |
| 91 | + if hasattr(row.created_at, "timestamp") |
| 92 | + else int(row.created_at) |
| 93 | + ), |
| 94 | + ) |
| 95 | + ) |
| 96 | + elif message.role == "user": |
| 97 | + if isinstance(message.content, str): |
| 98 | + return ModelRequest(parts=[UserPromptPart(content=message.content)]) |
| 99 | + elif isinstance(message.content, list): |
| 100 | + return ModelRequest(parts=[UserPromptPart(content=message.content[0].text)]) |
| 101 | + elif message.role == "system": |
| 102 | + if isinstance(message.content, str): |
| 103 | + return ModelRequest(parts=[SystemPromptPart(content=message.content)]) |
| 104 | + elif isinstance(message.content, list): |
| 105 | + return ModelRequest(parts=[SystemPromptPart(content=message.content[0].text)]) |
| 106 | + elif message.role == "tool": |
| 107 | + return ModelRequest( |
| 108 | + parts=[ |
| 109 | + ToolReturnPart( |
| 110 | + content=message.content, |
| 111 | + tool_name="", |
| 112 | + tool_call_id=message.tool_call_id or generate_tool_call_id(), |
| 113 | + ) |
| 114 | + ] |
| 115 | + ) |
| 116 | + else: |
| 117 | + raise ValueError(f"Unknown role: {message.role}") |
0 commit comments