How to Use OpenAI with LangChain: ChatOpenAI, Agents and Structured Output

LangChain is the most widely used Python framework for building applications on top of language models, and OpenAI is the provider most people connect to it first. The pairing has changed noticeably with LangChain 1.0: agents are now built with a single create_agent function, models are created with a unified interface, and the OpenAI integration can talk to either the Chat Completions API or the newer Responses API. This guide shows how to use OpenAI with current LangChain, from installation through structured output, tools, streaming, embeddings, and debugging, and it flags the old patterns that no longer apply.

What Changed in LangChain 1.0

If you learned LangChain a couple of years ago, you probably remember chains, an expanding set of agent classes, and a large package that included everything. LangChain 1.0 simplified that. The core langchain package now focuses on a small set of building blocks: create_agent for agents, init_chat_model for provider-agnostic model creation, messages, tools, and embeddings. Older building blocks such as the classic chain classes, retrievers, the indexing API, and the hub moved into a separate langchain-classic package, so legacy code still runs if you install it. Provider integrations live in their own packages, and the OpenAI one is langchain-openai. Agent execution is built on LangGraph underneath, which gives you persistence, streaming, and human-in-the-loop control when you need them.

Figure 1 — Which LangChain package does what

Package What you use it for langchaincreate_agent, init_chat_model, messages, tools langchain-openaiChatOpenAI, OpenAIEmbeddings, OpenAI-specific features langgraphStateful graphs, persistence, custom agent flows langchain-classicLegacy chains, retrievers, hub, indexing API

Installing and Authenticating

Install the core package and the OpenAI integration, then set your API key as an environment variable. The integration reads OPENAI_API_KEY automatically, so you never need to put the key in your source code.

pip install -U langchain langchain-openai
export OPENAI_API_KEY="your-api-key"

Use a virtual environment, keep the key in a .env file or a secrets manager, and make sure the file is excluded from version control.

Your First Call with ChatOpenAI

ChatOpenAI is the class that wraps OpenAI’s chat models. Create it with a model name and call invoke with a prompt. In current LangChain the reply is an AIMessage object whose text property holds the answer.

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.4-mini")
reply = llm.invoke("Explain vector embeddings in two sentences.")
print(reply.text)

The model name above follows the style used in LangChain’s documentation, so replace it with whichever model you have chosen from OpenAI’s current models page. Be careful with sampling parameters: reasoning models often do not accept settings such as temperature, and you may need a reasoning effort setting instead. If a parameter you pass is rejected, check the model’s documentation before assuming a LangChain bug.

Chat Completions or Responses API

OpenAI now has two main ways to generate text. Chat Completions is the long-standing stateless interface, and the Responses API is the newer one oriented toward agents, with built-in tools, reasoning summaries, and server-side conversation state. ChatOpenAI supports both. It routes to the Responses API automatically when you use a feature that only exists there, such as a built-in web search tool or reasoning output, and you can opt in explicitly with use_responses_api set to true. For a simple chatbot the default is fine. For agents that use OpenAI’s hosted tools, opt in to the Responses API. Note that when using it, the response content can include richer blocks such as reasoning summaries and tool invocations, which LangChain stores in the message content, so read the text through the text property rather than assuming the content is a plain string.

Getting Structured Output

For programs that consume model output, ask for structured data instead of parsing prose. Define a Pydantic model for the shape you want and wrap the model with with_structured_output. For OpenAI, set the method to json_schema to use OpenAI’s native structured output feature, which constrains generation to your schema. Without that setting LangChain falls back to function calling, which also works but offers weaker guarantees.

from pydantic import BaseModel
from langchain_openai import ChatOpenAI

class Review(BaseModel):
    summary: str
    sentiment: str

llm = ChatOpenAI(model="gpt-5.4-mini")
structured = llm.with_structured_output(Review, method="json_schema")
result = structured.invoke("The battery lasts all day but the screen scratches easily.")
print(result.sentiment)

Building an Agent with Tools

Agents are where LangChain 1.0 changed the most. A tool is a normal Python function with type hints and a docstring, and the docstring tells the model when to use it. You pass your model and tools to create_agent, which builds a loop that calls the model, runs any tools it requests, feeds the results back, and stops when the model produces a final answer.

from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"It is sunny in {city}."

agent = create_agent(
    model=ChatOpenAI(model="gpt-5.4-mini"),
    tools=[get_weather],
    system_prompt="You are a concise assistant.",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What is the weather in Paris?"}]}
)
print(result["messages"][-1].text)

You can also pass a model string such as a provider and model name, and LangChain creates the chat model for you through init_chat_model, which makes it easy to switch providers later. Write tool docstrings carefully, keep each tool narrow, validate arguments inside the function, and make any tool with side effects safe to call twice, because models occasionally repeat a call.

Streaming Responses

For interactive applications, stream tokens as they are generated instead of waiting for the full reply. Every chat model has a stream method that yields chunks, and each chunk has a text property you can print or send to the browser. When using the Chat Completions API, token usage statistics are not included in streams by default, so set stream_usage to true if you need token counts for cost tracking. Agents stream too, and can emit updates for each step, which lets a user interface show that a tool is running instead of appearing frozen.

Guardrails with Middleware

Middleware is described as the defining feature of create_agent. It lets you hook into the agent loop at defined points: before the model is called, around each model call, and after each response. Use it to add input checks, redact sensitive data, trim long conversations, enforce limits on the number of tool calls, require human approval before a risky tool runs, or validate output before returning it. Because middleware sits outside your prompts and tools, it is a clean place to put safety and cost controls that must apply to every request.

Embeddings and Retrieval

For retrieval-augmented generation, the same package provides OpenAIEmbeddings. Create it with an embedding model such as text-embedding-3-small, then use it with the vector store of your choice, for example pgvector, Chroma, or Qdrant. The usual pipeline is to load and chunk documents, embed and store them, retrieve relevant chunks for a question, and pass them to the model as context. In LangChain 1.0 you can expose retrieval to an agent as a tool, so the agent decides when to look something up. Keep one embedding model and dimension setting per index.

Using Compatible Endpoints

ChatOpenAI accepts a base_url, which means the same class can talk to any OpenAI-compatible server: Azure OpenAI’s v1 endpoint, a local Ollama server, vLLM, or a gateway. This is convenient for development and for self-hosting. Be aware that compatible servers may not implement every feature, so structured output, tool calling, and Responses API behaviour can differ. LangChain’s documentation notes that when you use a non-OpenAI endpoint with the Responses API and agent loops fail after tool calls, enabling the previous-response-id option can fix it.

Migrating Older Code

If you are updating a project written for earlier LangChain, make three changes. Replace the old agent constructors and prebuilt react agent helpers with create_agent. Replace imports of classic chains, retrievers, and the hub with imports from langchain-classic, installing it if you still need them, and plan to move off them gradually. Check how you read model output, because messages now expose a text property and the Responses API can return richer content blocks. Pin your package versions in a lock file, run your tests after each upgrade, and read the migration guide for breaking changes.

Debugging and Observability

Agents are hard to debug by reading final answers alone, so turn on tracing. LangSmith, LangChain’s tracing platform, records every model call, tool call, and intermediate step. Enable it by setting the tracing and API key environment variables, run your agent, and inspect the trace to see exactly what the model saw and decided. Tracing also helps you measure latency and token usage per step, which is essential for cost control. If you prefer not to send data to a hosted service, you can log messages yourself or use an open-source tracing tool.

Common Mistakes

  • Using outdated tutorials. Many still show chains and agent classes that have been replaced by create_agent.
  • Passing unsupported parameters. Reasoning models may reject temperature and similar settings.
  • Treating content as a plain string. Use the text property, since content may contain blocks.
  • Vague tool docstrings. The model relies on them to choose tools correctly.
  • No step limit. Cap the number of tool calls so a confused agent cannot loop.
  • Skipping tracing. Without traces, agent failures are very difficult to diagnose.

Frequently Asked Questions

Which package do I install for OpenAI?
Install langchain-openai alongside langchain. It provides ChatOpenAI and OpenAIEmbeddings and reads your key from the OPENAI_API_KEY environment variable.
Do I need LangChain to use OpenAI?
No. The official OpenAI library is enough for many applications. LangChain adds value when you want agents, middleware, a unified interface across providers, or integrations with vector stores and tracing.
Does LangChain support the Responses API?
Yes. ChatOpenAI can use it, either automatically when you use a Responses-only feature or explicitly with use_responses_api set to true.
Can I switch to another provider later?
Yes. Creating models with init_chat_model and keeping provider-specific settings in configuration makes it straightforward to try another provider.

Last updated: November 2026. LangChain and OpenAI release frequently, so confirm APIs and model names in LangChain’s current documentation.

Leave a Comment