匠人学院 JR Academy
Skip to article
Learning guide
LangChain Guide

Build LLM apps with LangChain using chains, agents, memory, RAG, and orchestration patterns.

3 chapters·9 guides·Access varies by chapter
Model I/O
On this page

LangChain Model I/O: Prompts, Messages and Parsing

Keep prompt construction, provider calls and output validation separate. That makes failures easier to diagnose than one function that builds strings, calls an API and parses a result at once.

#Build messages explicitly

This local example formats a prompt without contacting a model:

python
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder prompt = ChatPromptTemplate.from_messages([ ("system", "Extract only information present in the supplied text."), MessagesPlaceholder("history"), ("human", "{text}"), ]) messages = prompt.invoke({"history": [], "text": "Alex uses Python and SQL."}) print(messages.to_messages())

MessagesPlaceholder expects message history, not an arbitrary string. Keep template variables consistent with invocation keys. Use partial() when a value is intentionally fixed, and version the prompt alongside its tests.

#Select an output contract

StrOutputParser produces text. JSON parsing produces data but does not prove its truth. When using Pydantic, validate the parsed result explicitly or use a documented structured-output interface for the selected integration.

python
from pydantic import BaseModel, Field class ExtractedSkills(BaseModel): name: str | None = None skills: list[str] = Field(default_factory=list) example = ExtractedSkills.model_validate({"name": "Alex", "skills": ["Python", "SQL"]}) print(example.model_dump())

This is local validation of illustrative data, not a model extraction result. An optional field should remain absent or null when the source does not supply it.

#Test adapters, not just imports

A common chat interface does not guarantee identical provider behavior. Check tool support, content block shape, image support and structured-output constraints. Low temperature can reduce variation when supported; it does not guarantee deterministic or factual output.

Fallbacks must respect the same data-processing policy and permissions. Do not silently send private documents to another provider after a timeout.

Model documentation↗ · Chains

Published by
JR Academy
Learning resources

Individual authors and reviewers are credited where recorded.

System Design

Core system design concepts and practical case studies

Learn the trade-offs and patterns that matter in technical interviews.

Open System Design →

Related Roadmaps

Done reading? Next steps