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
- Data Retrieval: Connect with app-specific data sources.
- Chains: Build sequential model call pipelines.
- Agents: Let pipelines select tools dynamically based on high-level instructions.
- Memory: Maintain application state during pipeline runs.
- Callbacks: Log and stream intermediate pipeline steps.
Installation
- Set Up Domestic pip Mirror (Permanent)
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple
- Install LangChain
pip install langchain
- Install OpenAI SDK (API Integration)
pip install openai
API Key Management
- Terminal Environment Variable
export OPENAI_API_KEY="sk-..."
- Python Script/Notebook Environment Variable
import os
os.environ["OPENAI_API_KEY"] = "sk-..."
- 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()}")