liveBook · Manning

ChatOpenAI

As explained in Build Python Web Apps with Streamlit

ChatOpenAI is a LangChain class that provides an interface to OpenAI chat language models.

ChatOpenAI is a LangChain class for connecting an application to OpenAI chat models. It provides an interface similar to an OpenAI API client and can be used as the language model in a LangGraph chatbot. section 10.2.3

Import ChatOpenAI from langchain_openai and initialize it with a model name and an OpenAI API key. In a graph node, call the model’s invoke method with the conversation messages; the returned AI message can then be added to the graph state. section 10.2.3

Listing 10.1 An example of a graph
from langgraph.graph import START, END, StateGraph
from langchain_core.messages import AnyMessage, HumanMessage
from langchain_openai import ChatOpenAI
from typing import TypedDict

llm = ChatOpenAI(model_name="gpt-5.1", openai_api_key="sk-proj-...")

class MyGraphState(TypedDict):
  messages: list[AnyMessage]

builder = StateGraph(MyGraphState)

def assistant_node(state):
  messages = state["messages"]
  ai_response_message = llm.invoke(messages)
  return {"messages": messages + [ai_response_message]}

builder.add_node("assistant", assistant_node)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile()

input_message = input("Talk to the bot: ")
initial_state = {"messages": [HumanMessage(content=input_message)]}
final_state = graph.invoke(initial_state)

print("Bot:\n" + final_state["messages"][-1].content)

This Python example connects ChatOpenAI to a one-node graph, sends a user message, and prints the response. Replace the placeholder with an actual API key. section 10.2.3

A chatbot can also configure max_tokens when creating ChatOpenAI and retrieve its API key from application secrets rather than placing it directly in the model initialization. section 10.2.3

How Build Python Web Apps with Streamlit covers it

How deep it goes
Demonstrates initialization and message invocation in a graph without explaining the client’s internals.
Examples
Illustrates a command-line haiku chatbot and a Streamlit chatbot with an API key in secrets.
What you can do after
Apply it via LangChain to initialize a chat model and invoke it from a graph node.
How it connects
Connects LangChain, LangGraph, graph state, and conversation messages.

Also explained in

Compare how 2 books explain ChatOpenAI →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.