Chat Completions API compatibility
ChatOpenAI is fully compatible with OpenAIās Chat Completions API. If you are looking to connect to other model providers that support the Chat Completions API, you can do so ā see instructions.Overview
Integration details
Model features
Setup
To access OpenAI models youāll need to install thelangchain-openai integration package and acquire an OpenAI Platform API key.
Installation
Credentials
Head to the OpenAI Platform to sign up and generate an API key. Once youāve done this set theOPENAI_API_KEY environment variable in your environment:
Instantiation
Now we can instantiate our model object and generate responses:ChatOpenAI API Reference for the full set of available model parameters.
Token parameter deprecationOpenAI deprecated
max_tokens in favor of max_completion_tokens in September 2024. While max_tokens is still supported for backwards compatibility, itās automatically converted to max_completion_tokens internally.Invocation
Streaming usage metadata
OpenAIās Chat Completions API does not stream token usage statistics by default (see API reference here). To recover token counts when streaming withChatOpenAI or AzureChatOpenAI, set stream_usage=True as an initialization parameter or on invocation:
Using with Azure OpenAI
Azure OpenAI v1 API supportAs of
langchain-openai>=1.0.1, ChatOpenAI can be used directly with Azure OpenAI endpoints using the new v1 API. This provides a unified way to use OpenAI models whether hosted on OpenAI or Azure.For the traditional Azure-specific implementation, continue to use AzureChatOpenAI.Using Azure OpenAI v1 API with API Key
Using Azure OpenAI v1 API with API Key
To use
ChatOpenAI with Azure OpenAI, set the base_url to your Azure endpoint with /openai/v1/ appended:Using Azure OpenAI with Microsoft Entra ID
Using Azure OpenAI with Microsoft Entra ID
The v1 API adds native support for Microsoft Entra ID (formerly Azure AD) authentication with automatic token refresh. Pass a token provider callable to the The token provider is a callable that automatically retrieves and refreshes authentication tokens, eliminating the need to manually manage token expiration.You can also pass a token provider callable to the
api_key parameter:api_key parameter when using
asynchronous functions. You must import DefaultAzureCredential from azure.identity.aio:When using an async callable for the API key, you must use async methods (
ainvoke, astream, etc.). Sync methods will raise an error.Tool calling
OpenAI has a tool calling (we use ātool callingā and āfunction callingā interchangeably here) API that lets you describe tools and their arguments, and have the model return a JSON object with a tool to invoke and the inputs to that tool. tool-calling is extremely useful for building tool-using chains and agents, and for getting structured outputs from models more generally.Bind tools
WithChatOpenAI.bind_tools, we can easily pass in Pydantic classes, dict schemas, LangChain tools, or even functions as tools to the model. Under the hood these are converted to an OpenAI tool schemas, which looks like:
Strict mode
Requires
langchain-openai>=0.1.21strict argument when calling tools that will enforce that the tool argument schema is respected by the model. See more.
If
strict=True the tool definition will also be validated, and a subset of JSON schema are accepted. Crucially, schema cannot have optional args (those with default values).Read the full docs on what types of schema are supported.Tool calls
Notice that the AIMessage has atool_calls attribute. This contains in a standardized ToolCall format that is model-provider agnostic.
Structured output and tool calls
OpenAIās structured output feature can be used simultaneously with tool-calling. The model will either generate tool calls or a response adhering to a desired schema. See example below:Custom tools
Requires
langchain-openai>=0.3.29Context-free grammars
Context-free grammars
OpenAI supports the specification of a context-free grammar for custom tool inputs in
lark or regex format. See OpenAI docs for details. The format parameter can be passed into @custom_tool as shown below:Responses API
Requires
langchain-openai>=0.3.9ChatOpenAI will route to the Responses API if one of these features is used. You can also specify use_responses_api=True when instantiating ChatOpenAI.
Web search
To trigger a web search, pass{"type": "web_search_preview"} to the model as you would another tool.
Image generation
Requires
langchain-openai>=0.3.19{"type": "image_generation"} to the model as you would another tool.

File search
To trigger a file search, pass a file search tool to the model as you would another tool. You will need to populate an OpenAI-managed vector store and include the vector store ID in the tool definition. See OpenAI documentation for more detail.Computer use
ChatOpenAI supports the "computer-use-preview" model, which is a specialized model for the built-in computer use tool. To enable, pass a computer use tool as you would pass another tool.
Currently, tool outputs for computer use are present in the message content field. To reply to the computer use tool call, construct a ToolMessage with {"type": "computer_call_output"} in its additional_kwargs. The content of the message will be a screenshot. Below, we demonstrate a simple example.
First, load two screenshots:
content:
ToolMessage with these properties:
- It has a
tool_call_idmatching thecall_idfrom the computer-call. - It has
{"type": "computer_call_output"}in itsadditional_kwargs. - Its content is either an
image_urlor aninput_imageoutput block (see OpenAI docs for formatting).
previous_response_id:
Code interpreter
OpenAI implements a code interpreter tool to support the sandboxed generation and execution of code.Example use
Remote MCP
OpenAI implements a remote MCP tool that allows for model-generated calls to MCP servers.Example use
MCP Approvals
MCP Approvals
OpenAI will at times request approval before sharing data with a remote MCP server.In the above command, we instructed the model to never require approval. We can also configure the model to always request approval, or to always request approval for specific tools:Responses may then include blocks with type
"mcp_approval_request".To submit approvals for an approval request, structure it into a content block in an input message:Managing conversation state
The Responses API supports management of conversation state.Manually manage state
You can manage the state manually or using LangGraph, as with other chat models:Passing previous_response_id
When using the Responses API, LangChain messages will include an "id" field in its metadata. Passing this ID to subsequent invocations will continue the conversation. Note that this is equivalent to manually passing in messages from a billing perspective.
previous_response_id using the last response in a message sequence:
use_previous_response_id=True, input messages up to the most recent response will be dropped from request payloads, and previous_response_id will be set using the ID of the most recent response.
That is,
Reasoning output
Some OpenAI models will generate separate text content illustrating their reasoning process. See OpenAIās reasoning documentation for details. OpenAI can return a summary of the modelās reasoning (although it doesnāt expose the raw reasoning tokens). To configureChatOpenAI to return this summary, specify the reasoning parameter. ChatOpenAI will automatically route to the Responses API if this parameter is set.
Fine-tuning
You can call fine-tuned OpenAI models by passing in your correspondingmodelName parameter.
This generally takes the form of ft:{OPENAI_MODEL_NAME}:{ORG_NAME}::{MODEL_ID}. For example:
Multimodal Inputs (images, PDFs, audio)
OpenAI has models that support multimodal inputs. You can pass in images, PDFs, or audio to these models. For more information on how to do this in LangChain, head to the multimodal inputs docs. You can see the list of models that support different modalities in OpenAIās documentation. For all modalities, LangChain supports both its cross-provider standard as well as OpenAIās native content-block format. To pass multimodal data intoChatOpenAI, create a content block containing the data and incorporate it into a message, e.g., as below:
Images
Images
PDFs
PDFs
Audio
Audio
See supported models, e.g.,
"gpt-4o-audio-preview".Refer to examples in the how-to guide here.In-line base64 data
Predicted output
Requires
langchain-openai>=0.2.6gpt-4o and gpt-4o-mini series) support Predicted Outputs, which allow you to pass in a known portion of the LLMās expected output ahead of time to reduce latency. This is useful for cases such as editing text or code, where only a small part of the modelās output will change.
Hereās an example:
Note that currently predictions are billed as additional tokens and may increase your usage and costs in exchange for this reduced latency.
Audio Generation (Preview)
Requires
langchain-openai>=0.2.3gpt-4o-audio-preview model.
output_message.additional_kwargs['audio'] will contain a dictionary like
model_kwargs['audio']['format'].
We can also pass this message with audio data back to the model as part of a message history before openai expires_at is reached.
**Output audio is stored under the
audio key in AIMessage.additional_kwargs, but input content blocks are typed with an input_audio type and key in HumanMessage.content lists. **For more information, see OpenAIās audio docs.Prompt caching
OpenAIās prompt caching feature automatically caches prompts longer than 1024 tokens to reduce costs and improve response times. This feature is enabled for all recent models (gpt-4o and newer).
Manual caching
You can use theprompt_cache_key parameter to influence OpenAIās caching and optimize cache hit rates:
Cache key strategies
You can use different cache key strategies based on your applicationās needs:Model-level caching
You can also set a default cache key at the model level usingmodel_kwargs:
Flex processing
OpenAI offers a variety of service tiers. The āflexā tier offers cheaper pricing for requests, with the trade-off that responses may take longer and resources might not always be available. This approach is best suited for non-critical tasks, including model testing, data enhancement, or jobs that can be run asynchronously. To use it, initialize the model withservice_tier="flex":
API reference
For detailed documentation of all features and configuration options, head to theChatOpenAI API reference.