Overview

Appendix A. Trying out LangChain

This appendix offers a quick, hands-on introduction to experimenting with LangChain in a Jupyter Notebook. It focuses on getting started fast with OpenAI’s REST API as the default backend, while noting that local, open‑source engines like Ollama can be explored later. The walkthrough centers on simple sentence completions and basic prompt engineering, highlighting how LangChain’s abstractions make it easy to prototype LLM-driven tasks with minimal setup and cost (using a small GPT model for affordability).

Readers are guided through prerequisites—Python 3.11+, an OpenAI API key, and a working Jupyter environment—followed by practical steps to create a virtual environment, install dependencies, and launch a notebook. After importing the necessary LangChain components, the appendix shows how to securely provide an API key (via prompt or environment variable), instantiate a ChatOpenAI client with a budget-friendly model, and issue a simple completion prompt. The immediate result demonstrates how LangChain returns structured messages that capture the LLM’s output and metadata, confirming the end‑to‑end setup is working.

With the basics in place, the appendix illustrates prompt engineering by moving from a direct prompt to a reusable PromptTemplate that parameterizes tone and length, then applies it to a short summarization task. It introduces chains and the LangChain Expression Language (LCEL), composing components with a pipeline operator to create readable, declarative workflows (for example, a prompt template feeding directly into an LLM). By showing how components implement a common runnable interface, the appendix emphasizes how LCEL simplifies building, reusing, and scaling prompt‑driven pipelines for common LLM applications.

FAQ

What are the prerequisites to try LangChain in this appendix?You need: - Python 3.11 or later installed - An OpenAI API key - A working Jupyter Notebook environment (local or online, e.g., Google Colab)
How do I create and activate a Python virtual environment on Windows?
C:\>cd Github\building-llm-applications\ch01
C:\Github\building-llm-applications\ch01>python -m venv env_ch01
C:\Github\building-llm-applications\ch01>.\env_ch01\Scripts\activate
On Linux: ./env_ch01/bin/activate. In PowerShell: .\env_ch01\Scripts\Activate.ps1.
How do I install the required packages?If you cloned/downloaded the repo, run:
(env_ch01) C:\Github\building-llm-applications\ch01>pip install -r requirements.txt
This installs notebook, langchain, and related dependencies.
How do I launch Jupyter and create/open the example notebook?- Start Jupyter:
(env_ch01)> jupyter notebook
- Create via File > New > Notebook, then rename to 01-langchain_examples.ipynb, or open directly:
(env_ch01)> jupyter notebook 01-langchain_examples.ipynb
How do I obtain and set my OpenAI API key?- Get a key at https://platform.openai.com/ under Profile > Your profile > User API key. - Create and save the secret key, and consider setting a spending limit (Settings > Limits). - In the notebook, prompt securely:
import getpass
OPENAI_API_KEY = getpass.getpass("Enter your OPENAI_API_KEY")
Alternatively, set an env var before launching:
set OPENAI_API_KEY=your_key
Then in Python:
import os
api_key = os.getenv("OPENAI_API_KEY")
What is the minimal LangChain code to do a sentence completion?
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, model_name="gpt-5-nano")
llm.invoke("It's a hot day, I would like to go to the…")
The response is an AIMessage; use response.content to read the text.
What is prompt engineering and how do I try a simple prompt?Prompt engineering is crafting instructions that guide the model to better answers. Example:
prompt_input = "Write a short message to remind users to be vigilant about phishing attacks."
response = llm.invoke(prompt_input)
print(response.content)
What is a PromptTemplate and how do I use it?PromptTemplate lets you parameterize prompts. Example:
from langchain_core.prompts import PromptTemplate
prompt_template = PromptTemplate.from_template(
    "You are an experienced copywriter. Write a {num_words} words summary "
    "of the following text, using a {tone} tone: {text}"
)
prompt_input = prompt_template.format(text=some_text, num_words=20, tone="knowledgeable and engaging")
print(llm.invoke(prompt_input).content)
What are chains and LCEL, and how do I execute a chain?LCEL lets you pipe components. Build a chain by composing a template and an LLM:
chain = prompt_template | llm
response = chain.invoke({"text": some_text, "num_words": 20, "tone": "knowledgeable and engaging"})
print(response.content)
This works because components implement a common Runnable interface.
How can I control costs and choose a model?Use gpt-5-nano for low cost, and switch to gpt-5-mini or gpt-5 for higher quality as needed. You can also set account spending limits in the OpenAI dashboard.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • AI Agents and Applications ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • AI Agents and Applications ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • AI Agents and Applications ebook for free