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:
base_url. Resolution order (first match wins):
- Explicit
base_url(oropenai_api_base) kwarg. OPENAI_API_BASE— read by LangChain at init.OPENAI_BASE_URL— read by the underlyingopenaiSDK client. LangChain also inspects this to decide whether to default-enablestream_usage; when set, the default is left off because many non-OpenAI endpoints don’t support streaming token usage.
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 the OpenAI API reference for stream options). 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.
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:Structured output
OpenAI supports a native structured output feature, which guarantees that its responses adhere to a given schema. You can access this feature in individual model calls, or by specifying the response format of a LangChain agent. See below for examples.Individual model calls
Individual model calls
Use the
with_structured_output method to generate a structured model response. Specify method="json_schema" to enable OpenAI’s native structured output feature; otherwise the method defaults to using function calling.Agent response format
Agent response format
Specify
response_format with ProviderStrategy to engage OpenAI’s structured output feature when generating its final response.Structured output with 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: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"} 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.Tool search
Requires
langchain-openai>=1.1.11@tool(extras={"defer_loading": True}) and add OpenAI’s search tool to available tools. See below for examples.
Server-side tool search
Server-side tool search
OpenAI can search across available tools and return the loaded tool (together with a tool call if appropriate) in the same response:
Client-executed tool search
Client-executed tool search
For full control of the underlying tool search process, you can specify
"execution": "client" in the search tool definition. If the model elects to search for a tool, it will include a tool_search_call block in its response. You can then supply a tool_search_output block that includes the tool definition.The following example shows how you can orchestrate this using custom middleware. The example implements a callable defining the search logic. The middleware then includes:- An
after_modelhook to check fortool_search_callblocks and invoke our callable - A
wrap_tool_callhook for runtime tool registration
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
Apply patch
Requires
langchain-openai>=1.3.0{"type": "apply_patch"} to the model as you would another tool. No input schema is required — the model knows how to construct the operation object.
apply_patch_call content blocks, each describing a single file operation (create_file, update_file, or delete_file):
apply_patch_call_output block keyed by the same call_id. Set status to "completed" on success, or "failed" with a descriptive output so the model can adjust and retry:
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,
Context management
The Responses API supports automatic server-side context compaction. This reduces conversation size when it reaches a token threshold, allowing for support of long-running interactions:AIMessage responses may contain blocks with "type": "compaction" in content. These should be retained in the conversation history, and can be appended to the message sequence in the usual way. Messages prior to the most recent compaction item can be kept, or discarded to improve latency.
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
Note: OpenAI requires file-names be specified for PDF inputs. When using LangChain’s format, include the
filename key.Read more about OpenAI file names for multimodal messages.Refer to examples in the PDF documents how-to guide.In-line base64 data
Audio
Audio
See supported models, e.g.,
"gpt-4o-audio-preview".Refer to examples in the audio how-to guide.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:
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:
Explicit caching with breakpoints
Requires
langchain-openai>=1.3.5. Supported on both the Chat Completions API and the Responses API."prompt_cache_breakpoint": {"mode": "explicit"} to the block. Explicit breakpoints require GPT-5.6 or later model families.
- Chat Completions
- Responses API
prompt_cache_breakpoint inside an extras dict if you prefer to keep the LangChain content block structure clean:
Request-level cache options
Requires
langchain-openai>=1.3.5. prompt_cache_options applies to GPT-5.6 and later model families.prompt_cache_options parameter on the model or per invocation:
mode:"implicit"(default) or"explicit". In"implicit"mode, OpenAI places a cache breakpoint on the latest message and also uses any explicit breakpoints you provide. In"explicit"mode, only your breakpoints are used for cache reads and writes. If the request has no explicit breakpoints, it does not use prompt caching.ttl: Minimum cache lifetime for breakpoints written by the request. The only supported value is"30m", which is also the default.
prompt_cache_retention instead ("in_memory" or "24h"). That field is separate from prompt_cache_options and is deprecated on GPT-5.6 and later model families.
Cache write tokens
When OpenAI writes new content to the prompt cache, it reportscache_write_tokens in the response. ChatOpenAI surfaces this as cache_creation in input_token_details:
"priority" and "flex" service tiers, these keys are prefixed with the tier name — for example, "priority_cache_read" and "priority_cache_creation".
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.
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

