출력 파서와 콜백
파서를 사용해 LLM 출력을 효과적으로 구조화하고 콜백으로 LangChain 애플리케이션을 모니터링하고 디버깅하는 방법을 학습합니다.
출력 파서와 콜백은(는) CoddyKit의 무료 LangChain / RAG / Vector DBs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 LangChain / RAG / Vector DBs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Unstructured LLM Outputs
Large Language Models (LLMs) are amazing, but their raw text outputs can often be messy and inconsistent. Imagine asking an LLM for a list of items, and sometimes it gives you a comma-separated string, other times a bullet list, or even a full paragraph!
This lack of structure makes it hard for your applications to reliably process and use the information. How can we make LLMs deliver predictable data?
What are Output Parsers?
Output Parsers are tools in LangChain designed to convert the unstructured, free-form text responses from LLMs into a structured, usable format.
They act as a bridge, transforming raw text into Python objects like lists, dictionaries, or Pydantic models. This ensures your application always receives data in the expected shape, making your code more robust and easier to manage.
Parsing Lists: CommaSeparatedListOutputParser
One of the simplest output parsers is the CommaSeparatedListOutputParser. It's perfect when you expect the LLM to return a list of items separated by commas.
LangChain will automatically inject instructions into your prompt, guiding the LLM to produce output in the correct format. Try running this example:
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import CommaSeparatedListOutputParser
# Mock LLM for demonstration without actual API calls
class MockLLM:
def invoke(self, prompt, config=None):
if "list 3 programming languages" in prompt:
return "Python, Java, C++"
return "Default response"
def main():
parser = CommaSeparatedListOutputParser()
prompt = PromptTemplate(
template="List 3 programming languages.\n{format_instructions}",
input_variables=[],
partial_variables={
"format_instructions": parser.get_format_instructions()
},
)
llm = MockLLM() # In a real app, replace with ChatOpenAI, etc.
chain = prompt | llm | parser
result = chain.invoke({})
print(f"Parsed result: {result}")
print(f"Type: {type(result)}")
if __name__ == "__main__":
main()Structured Output with Pydantic
For more complex data, like extracting a person's name, age, and city, LangChain integrates beautifully with Pydantic. Pydantic allows you to define data schemas using Python classes with type hints.
The PydanticOutputParser uses your Pydantic model to generate detailed instructions for the LLM, guiding it to output a JSON string that perfectly matches your desired structure.
PydanticOutputParser in Action
Here, we define a Person Pydantic model. The parser then ensures the LLM's output can be directly converted into an instance of this class, giving you strongly typed, structured data.
Notice how the parser.get_format_instructions() guides the LLM.
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
# Mock LLM for demonstration
class MockLLM:
def invoke(self, prompt, config=None):
if "extract information about a person" in prompt:
# LLM would output JSON matching Pydantic schema
return '{"name": "Alice", "age": 30, "city": "New York"}'
return "Default response"
class Person(BaseModel):
name: str = Field(description="The person's name")
age: int = Field(description="The person's age")
city: str = Field(description="The city the person lives in")
def main():
parser = PydanticOutputParser(pydantic_object=Person)
prompt = PromptTemplate(
template="Extract information about a person from the text 'Alice is 30 years old and lives in New York'.\n{format_instructions}",
input_variables=[],
partial_variables={
"format_instructions": parser.get_format_instructions()
},
)
llm = MockLLM() # In a real app, replace with ChatOpenAI, etc.
chain = prompt | llm | parser
result = chain.invoke({})
print(f"Parsed result: {result}")
print(f"Type: {type(result)}")
print(f"Name: {result.name}, Age: {result.age}")
if __name__ == "__main__":
main()Monitoring with Callbacks
Beyond just getting structured output, you often need to understand what's happening *inside* your LangChain application. This is where Callbacks come in.
Callbacks allow you to hook into various events that occur during a chain's execution, such as when an LLM call starts or ends, when a tool is used, or when a chain completes.
- Logging: See detailed steps.
- Debugging: Pinpoint issues quickly.
- Monitoring: Track performance and usage.
- Streaming: Display intermediate LLM thoughts.
Basic Monitoring: StdOutCallbackHandler
LangChain provides several built-in callback handlers. The StdOutCallbackHandler is a great starting point, as it simply prints all significant events directly to your console.
This gives you a real-time view of the chain's execution flow, including LLM inputs, outputs, and any errors. Add it to your chain's configuration:
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain.callbacks import StdOutCallbackHandler
from langchain_core.runnables import RunnablePassthrough
from langchain_core.messages import AIMessage, HumanMessage
# Mock Chat Model for demonstration purposes
class MockChatModel:
def invoke(self, messages, config=None):
callbacks = config.get("callbacks", []) if config else []
# Extract input text from messages
input_text = ""
if isinstance(messages, list) and messages:
input_text = messages[0].content if isinstance(messages[0], HumanMessage) else str(messages[0])
else:
input_text = str(messages)
# Simulate on_llm_start event
for handler in callbacks:
if hasattr(handler, 'on_llm_start'):
handler.on_llm_start({"name": "MockChatModel"}, [input_text])
# Simulate LLM processing and response
response_content = f"Mock response for: '{input_text[:50]}...'"
# Simulate on_llm_end event
for handler in callbacks:
if hasattr(handler, 'on_llm_end'):
handler.on_llm_end(response_content)
return AIMessage(content=response_content)
def main():
handler = StdOutCallbackHandler()
llm = MockChatModel() # Replace with actual LLM like ChatOpenAI
prompt = PromptTemplate.from_template("Tell me a short fact about {topic}.")
chain = (
{"topic": RunnablePassthrough()} # Input for the prompt
| prompt
| llm
| StrOutputParser()
)
print("--- Running chain with StdOutCallbackHandler ---")
# Pass the handler to the chain's invoke method via config
result = chain.invoke("Python programming language", config={"callbacks": [handler]})
print(f"\nFinal Result: {result}")
if __name__ == "__main__":
main()Customizing Callbacks
For advanced scenarios, you can create your own custom callback handlers. By inheriting from BaseCallbackHandler, you can override specific methods to react to events exactly how you need.
This allows for highly tailored logging, integrating with external monitoring systems, or building interactive UI elements that update in real-time. Key methods to override include:
on_llm_start: Before an LLM call.on_chain_end: After a chain finishes.on_tool_start: Before an agent uses a tool.on_agent_action: When an agent decides on an action.
Output Parsers & Callbacks Check
Output Parsers and Callbacks are fundamental for building robust, observable, and reliable LangChain applications. Let's test your understanding.
Lesson Summary
Great job! Today, you've mastered two essential LangChain concepts:
- Output Parsers: These tools bring order to LLM responses, transforming unstructured text into predictable Python objects like lists or Pydantic models. They are crucial for making your LLM applications reliable.
- Callbacks: You learned how callbacks provide deep insights into your chain's execution. They are invaluable for logging, debugging, monitoring, and even streaming real-time updates from your LangChain applications.
These building blocks are vital for creating sophisticated and observable LLM-powered solutions!
AI 튜터와 함께 LangChain / RAG / Vector DBs을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“출력 파서와 콜백” 강의는 무료인가요?
네 — “출력 파서와 콜백” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 LangChain / RAG / Vector DBs 강의 전체를 잠금 해제할 수 있습니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.
“출력 파서와 콜백”에서 뭘 배우나요?
파서를 사용해 LLM 출력을 효과적으로 구조화하고 콜백으로 LangChain 애플리케이션을 모니터링하고 디버깅하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 LangChain / RAG / Vector DBs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
LangChain / RAG / Vector DBs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 LangChain / RAG / Vector DBs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“출력 파서와 콜백” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 LangChain / RAG / Vector DBs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 LangChain / RAG / Vector DBs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.