To convert an array of dicts representing messages in OpenAI style into Pydantic models that can be used with Agent.run as message_history, you will first need to define a Pydantic model that matches the structure of your messages. Then, you can convert your dicts into instances of this model.
Let's assume you are working with a structure similar to the one you've described, where each message is a dict with 'role' and 'content' keys. Here's a step-by-step guide on how to achieve this conversion:
Step 1: Define Your Pydantic Model
First, define a Pydantic model that represents a message. This model should have fields corresponding to the keys in your dicts.
from pydantic import BaseModel
class Message(BaseModel):
role: str
content: str
Step 2: Convert Dicts to Pydantic Models
You have an array (list in Python) of dicts representing messages. You can convert these into Message objects using a list comprehension or a loop.
Using List Comprehension
messages_dict = [{'role': 'user', 'content': 'Hi.'}, {'role': 'assistant', 'content': 'Hello!'}]
# Convert dicts to Message objects
messages_pydantic = [Message(**msg) for msg in messages_dict]
Using a Loop
messages_dict = [{'role': 'user', 'content': 'Hi.'}, {'role': 'assistant', 'content': 'Hello!'}]
messages_pydantic = []
for msg in messages_dict:
messages_pydantic.append(Message(**msg))
Both methods achieve the same result: they create a list of Message objects from your original list of dicts.
Step 3: Pass to Agent.run
Now that you have a list of Pydantic Message objects, you can pass this list as the message_history argument to Agent.run, assuming Agent.run is designed to accept a list of such Pydantic models.
agent = Agent() # Initialize your agent
result = agent.run(message_history=messages_pydantic)
Notes
- Ensure that the Pydantic model (
Message in this example) accurately represents the structure of the data you're working with. You might need to adjust the model if your messages have additional fields or more complex structures (e.g., nested models).
- The
Agent class and its run method should be designed to handle a list of Pydantic models. If Agent is from a third-party library, refer to its documentation to confirm the expected format for message_history.
By following these steps, you can convert your OpenAI-style message dicts into Pydantic objects suitable for use with Agent.run.