Direct API vs LangChain: Master Every LLM Invocation Method in One Day
This article compares raw API calls with LangChain's abstractions, explains when to use ChatModel versus LLM interfaces, demonstrates model selection across providers, shows how to build prompt templates and output parsers, and provides a complete Python example with error‑handling best practices.
Direct API calls and LangChain differ in three main ways: template reuse, low model‑switching cost, and built‑in error handling.
1. Choosing between ChatModel and LLM
LangChain wraps large models into two interface types.
ChatModel : input is a list of messages, output is an AI reply message. Representative models include GPT‑4.1, Claude‑sonnet‑4‑6, Gemini, 文心一言, 通义千问.
LLM : input is a plain string, output is a plain string. Representative models include GPT‑4.1‑mini and the Claude official API.
Use ChatModel for the most common domestic models. Use LLM only when the provider offers a pure text‑completion endpoint.
2. Supported models
# OpenAI
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", api_key="sk-...")
# Anthropic
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-sonnet-4-6")
# Zhipu AI (GLM series)
from langchain_community.chat_models import ChatZhipuAI
llm = ChatZhipuAI(model="glm-4", api_key="...")
# Alibaba Tongyi Qwen
from langchain_community.chat_models import ChatTongyi
llm = ChatTongyi(model="qwen-turbo", dashscope_api_key="...")
# Local model via Ollama
from langchain_ollama import ChatOllama
llm = ChatOllama(model="qwen2.5:7b", base_url="http://localhost:11434")Selection advice:
Production projects: GPT‑4.1 or Claude‑sonnet‑4‑6.
Cost‑sensitive projects: GPT‑4.1‑mini or 文心一言 3.5.
Local deployment: Ollama + Qwen2.5 or Llama3.
3. Prompt templates
3.1 ChatPromptTemplate (message‑based)
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You are a professional {topic} assistant"),
("human", "Please answer the following {question_count} questions: {questions}")
])
chain = prompt | llm | StrOutputParser()
result = chain.invoke({
"topic": "Python programming",
"question_count": 2,
"questions": "1. What is a decorator? 2. What does __init__ do?"
})3.2 PromptTemplate (string‑based)
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template(
"Translate the following Chinese into {target_language}: {text}"
)
chain = prompt | llm | StrOutputParser()
result = chain.invoke({"target_language": "Japanese", "text": "LangChain makes LLM app development easy"})3.3 Combining templates
# System prompt
system_prompt = ChatPromptTemplate.from_messages([
("system", "You are a code review assistant focusing on {bug_type} issues")
])
# User prompt
user_prompt = ChatPromptTemplate.from_messages([
("human", "Please review the following code: ```{language}
{code}
```")
])
combined = system_prompt + user_prompt
chain = combined | llm | StrOutputParser()4. Output parsers
4.1 JsonOutputParser with a Pydantic model
from langchain_core.output_parsers import JsonOutputParser
from pydantic import BaseModel
class Recipe(BaseModel):
name: str
ingredients: list[str]
steps: list[str]
parser = JsonOutputParser(pydantic_object=Recipe)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a recipe‑generation assistant"),
("human", "Generate a {cuisine} dessert recipe")
])
chain = prompt | llm | parser
result = chain.invoke({"cuisine": "French"})
print(result) # {'name': 'Caramel Pudding', 'ingredients': [...], 'steps': [...]}4.2 PydanticOutputParser
from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
class MeetingAction(BaseModel):
action: str = Field(description="Action to perform")
owner: str = Field(description="Person responsible")
deadline: str = Field(description="Deadline in YYYY‑MM‑DD")
parser = PydanticOutputParser(pydantic_object=MeetingAction)
chain = prompt | llm | parser4.3 CommaSeparatedListOutputParser
from langchain_core.output_parsers import CommaSeparatedListOutputParser
parser = CommaSeparatedListOutputParser()
prompt = PromptTemplate.from_template(
"List 5 applications of {topic}, separated by commas",
partial_variables={"format_instructions": parser.get_format_instructions()}
)
chain = prompt | llm | parser
result = chain.invoke({"topic": "RAG"})
# result: ["Intelligent客服", "Knowledge‑base QA", "Document summarization", ...]5. Full end‑to‑end example
# pip install langchain==1.2.15 langchain-openai==1.1.14
import os
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 1. Initialise model (API key via environment variable)
os.environ["OPENAI_API_KEY"] = "your-api-key"
llm = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", temperature=0.7)
# 2. Build prompt template
prompt = ChatPromptTemplate.from_messages([
("system", "You are a technical documentation assistant"),
("human", "Explain {concept} in one paragraph, covering: 1) what it is 2) problem it solves 3) typical use cases")
])
# 3. Assemble chain (LCEL syntax)
chain = prompt | llm | StrOutputParser()
# 4. Invoke
result = chain.invoke({"concept": "LangChain Expression Language (LCEL)"})
print(result)6. Error handling
from langchain_openai import ChatOpenAI
from langchain_core.exceptions import LangChainException
llm = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", max_retries=3)
try:
response = llm.invoke("你好")
except Exception as e:
print(f"Call failed: {type(e).__name__}: {e}")
# Common error types:
# - AuthenticationError: API key wrong or expired
# - RateLimitError: Too many requests, auto‑retry after 1‑2 s
# - TimeoutError: Request timed out, check network or lower max_retries
# - InvalidRequestError: Invalid parameters, e.g., nonexistent modelTypical settings:
Store API keys in environment variables.
Configure retry count (default 3, often increased to 5).
Set request timeout (default 60 s, often reduced to 30 s).
Use streaming output for long texts.
7. Day 2 recap
ChatModel : ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5") PromptTemplate : ChatPromptTemplate.from_messages() OutputParser : JsonOutputParser / PydanticOutputParser LCEL assembly : prompt | llm | StrOutputParser() Error handling : max_retries /
request_timeoutRelated links
LangChain Model I/O documentation: https://python.langchain.com/docs/concepts/
OpenAI API reference: https://platform.openai.com/docs/api-reference
LangChain output parsers: https://python.langchain.com/docs/concepts/output_parsers/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Ocean
Focused on AI programming, sharing ready-to-use development efficiency solutions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
