A First LangChain Application
A useful first chain has three explicit stages: format a prompt, call a chat model and turn the response into the output your application needs.
#Start with one text chain
Requires langchain-openai, python-dotenv, OPENAI_API_KEY and an available OPENAI_MODEL. Running this example makes a provider request and may incur charges.
pythonimport os from dotenv import load_dotenv from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_openai import ChatOpenAI load_dotenv() prompt = ChatPromptTemplate.from_messages([ ("system", "Explain {topic} with one short Python example."), ("human", "{question}"), ]) chain = prompt | ChatOpenAI(model=os.environ["OPENAI_MODEL"]) | StrOutputParser() print(chain.invoke({"topic": "iterators", "question": "What does next() do?"}))
The output is model-generated, not a fixed expected answer. Review the explanation and test the code separately.
#Change execution mode deliberately
The same runnable can use invoke, ainvoke, stream or batch. Stream support depends on the components in the pipeline; a blocking preprocessing step can delay the first visible output. Limit batch concurrency to respect provider limits rather than assuming a batch is as cheap or fast as one call.
#Choose the next extension
For structured extraction, define a schema and validate the result. For conversation, provide bounded history associated with the authenticated user. For document questions, retrieve authorized source passages before generation. For actions, define narrow tools and enforce permissions outside the model.
Changing a model adapter preserves much of the composition code, but tool schemas, image support, sampling options and structured output can differ. Re-run task-specific tests after a provider change.