LangChain Message Conversion with tool_example_to_messages
Posted: Nov 23, 2024.
When working with LLMs and chat models in LangChain, you might need to convert examples containing tool calls into a format that the model can understand. The tool_example_to_messages
utility helps you transform tool examples into a sequence of chat messages that can be used for training or fine-tuning chat models.
What is tool_example_to_messages?
tool_example_to_messages
is a utility function that converts a single example containing user input and tool calls into a structured sequence of chat messages. This is particularly useful when you need to:
- Convert extraction examples into chat format
- Prepare training data for chat models
- Create sequences of interactions involving tool calls
Reference
Here are the key parameters and return values for tool_example_to_messages
:
Parameter | Type | Description |
---|---|---|
input | str | The user input text |
tool_calls | List[BaseModel] | List of tool calls represented as Pydantic models |
tool_outputs | Optional[List[str]] | Optional list of tool call outputs. If not provided, placeholder values will be used |
Returns a list of BaseMessage objects containing:
- HumanMessage with the original input
- AIMessage with the extracted information
- ToolMessage confirming the tool request
How to use tool_example_to_messages
Let's look at some practical examples of using this utility.
Basic Example with Person Information Extraction
Here's how to convert examples that extract person information into chat messages:
Batch Processing Multiple Examples
You can also process multiple examples in batch:
Including Tool Outputs
You can optionally provide tool outputs when converting examples:
Use Cases and Best Practices
-
Training Data Preparation
- Use this utility when preparing examples for fine-tuning chat models
- Ensure your Pydantic models accurately represent the information you want to extract
-
Information Extraction
- Useful for converting structured extraction tasks into chat format
- Helps maintain consistency in message format across your application
-
Tool Call Processing
- When working with tools or functions that need to be called by the model
- Useful for creating examples of successful tool interactions
Remember that this utility is particularly helpful when working with chat models that are optimized for agent-like interactions, as it maintains the expected message structure these models expect.
An alternative to LangSmith
Open-source LangChain monitoring, prompt management, and magic. Get started in 2 minutes.
LangChain DocsJoin 10,000+ subscribers
Every 2 weeks, latest model releases and industry news.
An alternative to LangSmith
Open-source LangChain monitoring, prompt management, and magic. Get started in 2 minutes.