LangChain for AI-Driven Apps: Installation and Initial LLM Integration Examples

Input/Output for Language Models

LangChain interacts with language models via three core types:

  • Large Language Models (LLMs): Take text strings and return text strings.
  • Chat Models: Take chat message lists and return chat messages.
  • Text Embedding Models: Convert text to floating-point arrays for semantic analysis.

Data & Processing Components

  1. Data Retrieval: Connect with app-specific data sources.
  2. Chains: Build sequential model call pipelines.
  3. Agents: Let pipelines select tools dynamically based on high-level instructions.
  4. Memory: Maintain application state during pipeline runs.
  5. Callbacks: Log and stream intermediate pipeline steps.

Installation

  1. Set Up Domestic pip Mirror (Permanent)
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple
  1. Install LangChain
pip install langchain
  1. Install OpenAI SDK (API Integration)
pip install openai

API Key Management

  1. Terminal Environment Variable
export OPENAI_API_KEY="sk-..."
  1. Python Script/Notebook Environment Variable
import os
os.environ["OPENAI_API_KEY"] = "sk-..."
  1. Direct Initialization Parameter
from langchain_community.llms import OpenAI
my_llm = OpenAI(openai_api_key="sk-...")

OpenAI LLM Integration Example

Create a tool that generates brand names for products. Let’s modify variable names and use a generate_names helper-like flow.

import os
from langchain_community.llms import OpenAI

os.environ["OPENAI_API_KEY"] = "sk-..."

creative_llm = OpenAI(temperature=0.9, max_tokens=128)

product_description = "Create three distinct, fun company names for a brand that sells vibrant, eco-friendly wool socks."
name_list = creative_llm(product_description).strip().split("\n")
for idx, name in enumerate(name_list, start=1):
    print(f"Name {idx}: {name.strip()}")

Alternative with predict Method

LangChain’s predict method is optimized for direct text-to-text generation.

import os
from langchain_community.llms import OpenAI

os.environ["OPENAI_API_KEY"] = "sk-..."

standard_llm = OpenAI()

product_prompt = "Suggest a professional company name for a business that provides custom, hand-painted ceramic mugs."
final_name = standard_llm.predict(product_prompt, temperature=0.75)
print(f"Recommended Company Name: {final_name.strip()}")

Tags: LangChain LLM OpenAI API python AI Application Development

Posted on Sun, 04 Oct 2026 16:22:30 +0000 by montyauto