Use langchain_core.messages.ai helper methods or the to_openai_format utility to convert LangChain messages to OpenAI's raw dictionary format, and convert_to_messages to go back. You need this when integrating with low-level OpenAI clients or when serializing/deserializing for storage.
LangChain messages are designed to be provider-agnostic, but sometimes you need to interact directly with the OpenAI API client (not the LangChain wrapper), or you want to store messages in a database and later reconstruct them. The conversion functions to_openai_format and convert_to_messages handle the mapping between LangChain's BaseMessage objects and the raw JSON that OpenAI expects. This is especially useful when you are using OpenAI's streaming APIs directly or need to pass messages to a function that expects the raw format.
You might also need this conversion when using openai's native streaming API (openai.ChatCompletion.create(stream=True)), where you receive chunks in raw OpenAI format and want to turn them into AIMessageChunk objects for aggregation.