All LangChain chat models implement a common interface:
from langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage, SystemMessage# Initialize a chat modelmodel = ChatOpenAI(model="gpt-4")# Single messageresponse = model.invoke("Tell me a joke")print(response.content)# Multiple messages with system promptmessages = [ SystemMessage(content="You are a helpful coding assistant."), HumanMessage(content="How do I reverse a list in Python?")]response = model.invoke(messages)print(response.content)
from langchain_core.messages import SystemMessage# Set the behavior and context for the AIsystem_msg = SystemMessage( content="You are an expert in Python programming.")
from langchain_openai import ChatOpenAImodel = ChatOpenAI( model="gpt-4", temperature=0.7, # Creativity (0-2, default 1) max_tokens=500, # Maximum response length timeout=30, # Request timeout in seconds max_retries=2, # Number of retries on failure api_key="your-key", # Or set OPENAI_API_KEY env var)
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage# Initialize conversation with system promptmessages = [ SystemMessage(content="You are a helpful assistant.")]# First turnmessages.append(HumanMessage(content="My name is Alice"))response = model.invoke(messages)messages.append(response)# Second turn - model remembers contextmessages.append(HumanMessage(content="What's my name?"))response = model.invoke(messages)print(response.content) # "Your name is Alice"# Continue the conversationmessages.append(response)
Chat models can call functions to access external data:
from langchain_openai import ChatOpenAIfrom langchain_core.tools import tool@tooldef get_current_weather(location: str) -> str: """Get the current weather for a location. Args: location: The city name. """ # Mock implementation return f"Sunny, 72°F in {location}"# Bind tools to modelmodel = ChatOpenAI(model="gpt-4")model_with_tools = model.bind_tools([get_current_weather])# Model will call the tool when appropriateresponse = model_with_tools.invoke( "What's the weather in San Francisco?")if response.tool_calls: tool_call = response.tool_calls[0] print(f"Tool: {tool_call['name']}") print(f"Args: {tool_call['args']}") # Execute the tool and continue conversation
from langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Fieldclass Person(BaseModel): """Information about a person.""" name: str = Field(description="Person's full name") age: int = Field(description="Person's age in years") occupation: str = Field(description="Person's job or profession")model = ChatOpenAI(model="gpt-4")structured_model = model.with_structured_output(Person)# Returns a Pydantic model instanceperson = structured_model.invoke( "John Doe is a 35 year old software engineer.")print(person.name) # "John Doe"print(person.age) # 35print(person.occupation) # "Software Engineer"
from langchain_openai import ChatOpenAImodel = ChatOpenAI(model="gpt-4")json_model = model.with_structured_output(method="json_mode")response = json_model.invoke( "Extract the key entities from: Alice works at Acme Corp in NYC")print(response)# {"person": "Alice", "organization": "Acme Corp", "location": "NYC"}
from langchain_openai import ChatOpenAImodel = ChatOpenAI(model="gpt-4")# Batch invokeinputs = [ "What is 2+2?", "What is the capital of France?", "Who wrote Hamlet?"]responses = model.batch(inputs)for response in responses: print(response.content)
from langchain_openai import ChatOpenAIfrom langchain_anthropic import ChatAnthropic# Primary modelprimary = ChatOpenAI(model="gpt-4")# Fallback model if primary failsfallback = ChatAnthropic(model="claude-3-5-sonnet-20241022")# Create model with fallbackmodel_with_fallback = primary.with_fallbacks([fallback])# Will try primary first, then fallback on errorresponse = model_with_fallback.invoke("Hello!")