LangChain 1 cheatsheet

LangChain 1: Chat models

6 common LangChain 1 tasks.

Create a chat model

Create a model from a provider:model string, so switching providers is a one-line change.

from langchain.chat_models import init_chat_model

model = init_chat_model("anthropic:claude-sonnet-5-5")

Call a model

Send a prompt and get a message back. Read the text with .content.

response = model.invoke("Explain recursion in one sentence.")
print(response.content)

Send a conversation

Pass a list of messages, including a system message, instead of a single string.

model.invoke([
    {"role": "system", "content": "You are a concise assistant."},
    {"role": "user", "content": "What is a closure?"},
])

Stream the response

Print the answer as it is generated.

for chunk in model.stream("Write a haiku about Python."):
    print(chunk.text, end="", flush=True)

Run several prompts in parallel

Process a list of inputs concurrently.

responses = model.batch(["Define API.", "Define SDK."])

Set model parameters

Pass settings such as temperature and a token limit when you create the model.

model = init_chat_model("anthropic:claude-sonnet-5-5", temperature=0, max_tokens=1024)

Was this page helpful?