توسعه عاملهای هوشمند (Agentic Ai) با Langchain و Langgraph
این دوره مسیر عملی ساخت سیستمهای هوش مصنوعی مولد را با زبان پایتون و کتابخانههای LangChain و LangGraph آموزش میدهد. شروع کار از فراخوانی ساده مدلهای زبانی و طراحی پرامپت است، سپس به ساخت سیستمهای RAG (Retrieval-Augmented Generation) روی اسناد محلی میرسد، حافظه کوتاهمدت و بلندمدت به گفتگوها اضافه میشود، و در نهایت با LangGraph عاملهایی طراحی میشوند که میتوانند تصمیم بگیرند، از ابزار استفاده کنند، مسیر اجرا را مشروط کنند و در برابر خطا مقاوم باشند.
دوره با یک مقدمه مشخص میکند که یادگیری قدم به قدم چه مسیری را طی خواهد کرد: از تنظیم محیط پایتون و مدیریت کلیدهای API، تا مفاهیم پیام و توکن، طراحی اسکیمای Pydantic برای خروجی ساختیافته، چانکبندی و embedding اسناد، ساخت گرافهای LangGraph با state و reducer، مسیریابی شرطی، چکپوینتگذاری، و در نهایت یک عامل RAG کامل با حلقههای تأیید و تعمیر. هر مفهوم بهصورت یک گام کوچک و مستقل توسط تیوتور هوش مصنوعی آموزش داده و آزمون گرفته میشود، پیش از آنکه به گام بعدی برسید.
این دوره برای کسانی مناسب است که پایتون مینویسند و میخواهند از تئوری مدلهای زبانی به ساخت واقعی محصولات هوش مصنوعی مانند دستیارهای اسناد، رباتهای پرسشوپاسخ و عاملهای خودمختار برسند. پروژه نهایی دوره یک عامل پاسخدهنده به اسناد محلی است که ایندکسسازی، حافظه، ابزار، مسیریابی و تأیید انسانی را در کنار هم ترکیب میکند.
Estimated effort: 27 hours
What you will learn
- فراخوانی مدلهای زبانی با LangChain و مدیریت پیامها، پرامپت و خروجی ساختیافته با Pydantic
- ساخت خط لوله کامل RAG شامل بارگذاری اسناد، چانکبندی، embedding، ایندکسسازی برداری و بازیابی با ذکر منبع
- افزودن حافظه کوتاهمدت و بلندمدت به گفتگوها با مدیریت context window و خلاصهسازی
- طراحی ابزار (Tool) برای مدل و ساخت حلقههای فراخوانی ابزار با تأیید انسانی برای اقدامات حساس
- ساخت گرافهای حالتمحور با LangGraph شامل مسیریابی شرطی، ToolNode و چکپوینتگذاری
- طراحی یک عامل Agentic RAG کامل با حلقه ، زیرگرافها، اجرای موازی و ارزیابی رگرسیون
Course syllabus
- Course Roadmap and Agentic AI Systems
- Identify the progressive path from model calls to RAG and multi-step agents.
- Distinguish a chat application, workflow, RAG system, and autonomous agent.
- Describe the final local file-question-answering system and its major components.
- Python Environment and Dependency Management
- Create an isolated Python project environment with uv or virtualenv.
- Install LangChain, LangGraph, provider integrations, and document-processing packages.
- Use a requirements file or pyproject file to reproduce an environment.
- Configuration and API Key Handling
- Load configuration from environment variables and a local .env file.
- Separate secrets, model names, and application settings from source code.
- Validate missing configuration without exposing secret values.
- LangChain and LangGraph Version Compatibility
- Inspect installed package versions programmatically.
- Interpret compatibility constraints among LangChain, LangGraph, and provider packages.
- Upgrade dependencies deliberately and diagnose import changes.
- Language Model Inputs and Outputs
- Explain messages, roles, prompts, completions, tokens, and context windows.
- Construct system and user messages for a bounded task.
- Inspect model response content and metadata.
- Invoking Chat Models with LangChain
- Initialize a provider-backed LangChain chat model.
- Use invoke, batch, and asynchronous invocation appropriately.
- Handle model invocation failures and timeouts.
- Prompt Design for Reliable Tasks
- Specify task, context, constraints, output format, and fallback behavior.
- Use examples only when they improve task reliability.
- Design prompts that constrain answers to supplied evidence.
- Structured Outputs with Pydantic
- Define Pydantic schemas for model outputs.
- Request structured outputs from a compatible model.
- Validate, repair, and handle invalid structured responses.
- Model Selection, Cost, and Latency
- Compare model capability, context capacity, token pricing, latency, and tool support.
- Estimate per-request cost from input and output token counts.
- Select model tiers for routing, retrieval, generation, and evaluation tasks.
- LangChain Documents and Metadata
- Create Document objects with page content and metadata.
- Use metadata for source tracking, filtering, and citation display.
- Preserve document identity through a processing pipeline.
- Document Loading and Text Extraction
- Load text, markdown, PDF, and tabular files through appropriate loaders.
- Inspect extraction quality and identify malformed or empty content.
- Create a normalized file-ingestion interface.
- Text Chunking Strategies
- Explain chunk size, overlap, separators, and semantic boundaries.
- Apply recursive text splitting to files of varying structure.
- Evaluate chunk boundaries for retrieval quality and citation precision.
- Embeddings and Vector Similarity
- Explain embeddings as vector representations for semantic comparison.
- Compare cosine similarity, lexical matching, and semantic retrieval.
- Select an embedding model based on language, dimension, cost, and retrieval needs.
- Vector Stores and Retrieval
- Index chunks into an in-memory or persistent vector store.
- Run similarity search and retrieve top-k documents.
- Apply metadata filters and inspect retrieved provenance.
- Basic Retrieval-Augmented Generation
- Connect query input, retrieval, context formatting, and answer generation.
- Instruct the model to answer only from retrieved evidence.
- Return an abstention when evidence is insufficient.
- Citation and Provenance Generation
- Map answer claims to retrieved source chunks.
- Format citations with file names, locations, and chunk identifiers.
- Avoid citations that do not support the associated claim.
- Retrieval Quality Improvement
- Diagnose retrieval failure caused by chunking, embeddings, query wording, and top-k selection.
- Use query rewriting, metadata filtering, and reranking when appropriate.
- Compare retrieval configurations using representative queries.
- RAG Evaluation Metrics and Test Sets
- Create a representative question-answer-source dataset.
- Measure retrieval recall, citation correctness, answer groundedness, latency, and cost.
- Interpret tradeoffs among quality, latency, and cost.
- Conversation State and Short-Term Memory
- Represent conversation history as ordered messages.
- Explain thread-scoped short-term memory.
- Use a checkpointer to persist state across turns.
- Context Window Management
- Measure the growth of message history and token use.
- Apply message trimming while preserving required message order.
- Choose trimming thresholds based on model limits and task needs.
- Conversation Summarization Memory
- Generate and update a running conversation summary.
- Combine a summary with recent messages for model context.
- Identify facts that should remain verbatim rather than summarized.
- Long-Term Memory Stores
- Distinguish thread memory from cross-thread long-term memory.
- Store, namespace, retrieve, and update durable user facts.
- Use semantic search to retrieve relevant memories without leaking unrelated records.
- Tool Design and Tool Schemas
- Define LangChain tools with clear descriptions, typed arguments, and predictable return values.
- Design read-only file search and calculator tools.
- Validate tool inputs and return actionable errors.
- Tool Calling and Agent Loops
- Bind tools to a model and inspect generated tool calls.
- Execute tool calls and append tool results as messages.
- Implement the model-tool loop until a final response is produced.
- Tool Safety and Human Approval
- Classify tools by read-only, reversible, and consequential behavior.
- Add approval interrupts before selected actions.
- Resume interrupted execution with approval, rejection, or edited arguments.
- LangGraph State and Reducers
- Define typed graph state schemas.
- Explain state updates, channels, and reducers.
- Implement append semantics for message lists and safe aggregation for parallel outputs.
- LangGraph Nodes Edges and Compilation
- Create node functions that return valid state updates.
- Connect START, nodes, edges, and END in a StateGraph.
- Compile, visualize, invoke, and inspect a graph.
- Conditional Routing with Structured Decisions
- Use structured model output for route decisions.
- Define conditional edges and explicit path maps.
- Validate and handle unsupported routing labels.
- Agent Graph with ToolNode
- Use MessagesState for an agent workflow.
- Connect an LLM node, ToolNode, conditional continuation, and terminal response.
- Enforce a bounded recursion limit and diagnose unintended loops.
- Checkpointing and Durable Execution
- Explain checkpoints, thread identifiers, snapshots, and state history.
- Configure in-memory checkpointing for development and persistent checkpointing for local durability.
- Resume a workflow after an interrupt or recoverable failure.
- Agentic RAG Graph Architecture
- Design a graph that classifies a request, retrieves file evidence, optionally uses supporting tools, and generates cited output.
- Define state fields for question, rewritten query, retrieved documents, tool results, citations, and answer.
- Separate deterministic orchestration from model-based decisions.
- Query Planning and Retrieval Routing
- Classify questions as direct answer, file retrieval, calculation, or clarification.
- Rewrite retrieval queries for document search.
- Route requests to the minimum necessary set of tools and graph nodes.
- Answer Verification and Repair Loops
- Define verification criteria for evidence coverage, citation support, and answer completeness.
- Use a bounded evaluator-generator loop to request targeted repairs.
- Set explicit stopping conditions and failure fallbacks.
- Subgraphs and Specialized Subagents
- Identify when decomposition into subgraphs improves clarity or isolation.
- Integrate subgraphs with shared or transformed state schemas.
- Choose checkpoint behavior for stateless and durable subgraphs.
- Parallel Work and Result Aggregation
- Identify independent tasks suitable for concurrent execution.
- Use parallel graph branches or Send-based workers.
- Aggregate outputs deterministically with reducers and account for latency and cost.
- Tracing and Execution Debugging
- Capture traces for model calls, retrieval, tools, graph nodes, and latency.
- Inspect state updates and streamed graph events.
- Locate failures in prompts, routing, retrieval, tools, and state transitions.
- Agent Evaluation and Regression Testing
- Build datasets containing questions, expected evidence, expected tools, and expected outcomes.
- Evaluate final answer quality, retrieval, citation support, tool selection, and trajectory.
- Create regression checks for known failures after architecture changes.
- Reliability Patterns for Agent Workflows
- Apply retries, timeouts, fallbacks, idempotent task design, and recursion limits.
- Separate side effects into checkpointable tasks.
- Design failure states that preserve diagnostic information.
- Local LangGraph Project and Development Server
- Organize a Python LangGraph project into graph, state, node, tool, and configuration modules.
- Create langgraph.json with dependencies, environment file, and compiled graph entry point.
- Run a local development server and connect a local client or Studio.
- Capstone Local Document Answering Agent
- Integrate local document ingestion, indexing, retrieval, citations, short-term memory, long-term memory, and mixed tools.
- Orchestrate a multi-step agent with routing, verification, bounded repair, and human approval for consequential actions.
- Run, trace, evaluate, and debug the complete system locally.
Open this course in Teachme