patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLangroid Patterns
Langroid设计模式
Instructions
说明
Below is an INDEX of design patterns organized by category. Each item describes
WHAT you might want to implement, followed by a REFERENCE to a document with
a complete code example.
Scan this index to find patterns matching your needs, then consult the
corresponding document.
以下是按类别整理的设计模式索引。每个条目先描述你可能想要实现的功能,然后提供包含完整代码示例的文档参考。
浏览此索引找到符合你需求的模式,再查阅对应的文档。
Agent & Task Basics
Agent与任务基础
-
Task Returns Tool DirectlyCreate a Langroid Agent equipped with a single Tool (a ToolMessage), and wrap it in a Task so that running the task returns that ToolMessage directly. Use this pattern when you want a simple LLM agent that returns a structured response.
- Reference:
./task-return-tool.md
- Reference:
- 任务直接返回工具
创建一个配备单个Tool(即ToolMessage)的Langroid Agent,并将其封装在Task中,使得运行该任务时直接返回该ToolMessage。当你需要一个能返回结构化响应的简单大语言模型Agent时,可以使用此模式。
- 参考文档:
./task-return-tool.md
Tool Handlers
工具处理器
-
Stateful Handler on AgentDefine a STATEFUL tool handler as a METHOD on the agent (not inside the ToolMessage). Use this pattern when: (a) the tool handler needs to execute external operations (API calls, database queries, file I/O), (b) you need to track state across retries (e.g., failure counter), (c) the handler needs access to agent-level resources (connections, configs), or (d) you want Langroid to automatically loop errors back to the LLM for self-correction. The method name must match thefield of the ToolMessage. Return a string for errors (LLM sees it and can retry), or DoneTool(content=result) to terminate successfully.
request- Reference:
./agent-tool-handler-with-state.md
- Reference:
-
Handler with ValidationValidate tool output against agent state before accepting it. Use this pattern when: (a) the LLM's tool output must preserve certain content from the input (e.g., placeholders, required fields), (b) you want automatic retry if validation fails, (c) you need to compare tool output against context the LLM received. Define a handler method on a custom agent class that stores the input context as state, validates the tool output, and returns an error string for retry or AgentDoneTool for success (note: use AgentDoneTool, NOT DoneTool). Useso the handler runs before task termination.
done_sequences=["T[ToolName], A"]- Reference:
./agent-handler-validation-with-state.md
- Reference:
- Agent上的有状态处理器
将有状态的工具处理器定义为Agent的一个方法(而非在ToolMessage内部)。在以下场景中使用此模式:(a) 工具处理器需要执行外部操作(API调用、数据库查询、文件I/O);(b) 你需要在重试过程中跟踪状态(例如失败计数器);(c) 处理器需要访问Agent级别的资源(连接、配置);(d) 你希望Langroid自动将错误反馈给大语言模型以进行自我修正。方法名称必须与ToolMessage的字段匹配。返回字符串表示错误(大语言模型会看到并可重试),或返回DoneTool(content=result)以成功终止。
request- 参考文档:
./agent-tool-handler-with-state.md
- 带验证的处理器
在接受工具输出前,根据Agent状态对其进行验证。在以下场景中使用此模式:(a) 大语言模型的工具输出必须保留输入中的某些内容(例如占位符、必填字段);(b) 你希望验证失败时自动重试;(c) 你需要将工具输出与大语言模型收到的上下文进行对比。在自定义Agent类上定义一个处理器方法,将输入上下文存储为状态,验证工具输出,返回错误字符串以重试,或返回AgentDoneTool表示成功(注意:使用AgentDoneTool,而非DoneTool)。设置,以便处理器在任务终止前运行。
done_sequences=["T[ToolName], A"]- 参考文档:
./agent-handler-validation-with-state.md
Task Control
任务控制
-
Terminate on Specific ToolTerminate a Task only when a SPECIFIC tool is called. Useto exit immediately when that tool is emitted, or
TaskConfig(done_sequences=["T[ToolName]"])to exit after the tool is emitted AND handled by the agent. Use this when an agent has multiple tools but you only want one specific tool to trigger task termination.TaskConfig(done_sequences=["T[ToolName], A"])- Reference:
./done-sequences-specific-tool.md
- Reference:
-
Batch ProcessingRun the SAME task on MULTIPLE inputs concurrently using. Use this pattern when: (a) you need to process many items with the same agent/task logic, (b) you want parallelism without manual asyncio/threading, (c) you need state isolation between items (each gets a cloned agent with fresh message history), (d) you want to avoid connection exhaustion from creating too many agents manually. Each item gets a cloned task+agent, runs independently, results collected in order. Supports batch_size for concurrency limiting.
run_batch_tasks()- Reference:
./run-batch-tasks.md
- Reference:
- 调用特定工具时终止任务
仅当调用特定工具时才终止任务。使用以在该工具被触发时立即退出,或使用以在工具被触发且被Agent处理后退出。当Agent拥有多个工具,但你仅希望特定工具触发任务终止时,使用此模式。
TaskConfig(done_sequences=["T[ToolName]"])TaskConfig(done_sequences=["T[ToolName], A"])- 参考文档:
./done-sequences-specific-tool.md
- 批量处理
使用对多个输入并发运行同一任务。在以下场景中使用此模式:(a) 你需要用相同的Agent/任务逻辑处理大量条目;(b) 你希望无需手动处理asyncio/线程即可实现并行;(c) 你需要在条目间隔离状态(每个条目都会获得一个带有全新消息历史的克隆Agent);(d) 你希望避免手动创建过多Agent导致连接耗尽。每个条目都会获得一个克隆的任务+Agent,独立运行,结果按顺序收集。支持通过batch_size限制并发数。
run_batch_tasks()- 参考文档:
./run-batch-tasks.md
Integration & Output
集成与输出
-
MCP Tools IntegrationEnable a Langroid agent to use MCP (Model Context Protocol) tools from an external MCP server like Claude Code. Use this pattern when: (a) you want your agent to use file editing tools (Read, Edit, Write) from Claude Code, (b) you need to connect to any MCP server via stdio transport, (c) you want to enable ALL tools from an MCP server or just SPECIFIC tools selectively, (d) you want to customize/post-process MCP tool results before returning to the LLM. Usesdecorator for specific tools or
@mcp_toolfor all tools.get_tools_async()- Reference:
./mcp-tool-integration.md
- Reference:
-
Quiet ModeSuppress verbose Langroid agent output (streaming, tool JSON, intermediate messages) while showing your own custom progress messages. Use this pattern when: (a) you want clean CLI output showing only milestone events, (b) you're running a multi-step workflow and want to show progress without agent noise, (c) you need thread-safe output control. Usecontext manager to wrap agent task.run() calls, then print your own messages outside the context.
quiet_mode()- Reference:
./quiet-mode.md
- Reference:
- MCP工具集成
让Langroid Agent能够使用来自外部MCP(Model Context Protocol)服务器(如Claude Code)的MCP工具。在以下场景中使用此模式:(a) 你希望你的Agent使用Claude Code的文件编辑工具(读取、编辑、写入);(b) 你需要通过stdio传输连接到任何MCP服务器;(c) 你希望启用MCP服务器的所有工具,或选择性地启用特定工具;(d) 你希望在将MCP工具结果返回给大语言模型之前进行自定义/后处理。对特定工具使用装饰器,或使用获取所有工具。
@mcp_toolget_tools_async()- 参考文档:
./mcp-tool-integration.md
- 静默模式
抑制Langroid Agent的冗余输出(流式输出、工具JSON、中间消息),同时显示自定义的进度消息。在以下场景中使用此模式:(a) 你希望获得简洁的CLI输出,仅显示关键事件;(b) 你正在运行多步骤工作流,希望显示进度而不被Agent的冗余输出干扰;(c) 你需要线程安全的输出控制。使用上下文管理器包裹agent task.run()调用,然后在上下文外部打印自定义消息。
quiet_mode()- 参考文档:
./quiet-mode.md