factory

factory is an agent for coding agents from xt765/LangChain-Chinese-Comment. It costs 0 tokens per session (992 once invoked), scanned A, original, MIT.

An agent factory for LangChain v1, the Python framework for building applications that use language models. It combines a model, tools, instructions, middleware, output formats, and saved state into an executable agent graph.

In plain words
What is it for?
It helps create agents that choose between replying and calling tools, enforce structured outputs, customize execution state, inspect runs, and resume saved work.
Why use it?
It removes the need to assemble the agent's decision and tool-execution flow by hand, while allowing pauses, debugging, and state saving.

Agent

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add agents/xt765/langchain-chinese-comment/factory
Clone the repo
git clone --depth 1 https://github.com/xt765/LangChain-Chinese-Comment

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for factory

README.md
[![agentmods](https://agentmods.dev/badge/agents/xt765/langchain-chinese-comment/factory.svg)](https://agentmods.dev/agents/xt765/langchain-chinese-comment/factory)
Your own site
<a href="https://agentmods.dev/agents/xt765/langchain-chinese-comment/factory"><img src="https://agentmods.dev/badge/agents/xt765/langchain-chinese-comment/factory.svg" alt="Measured on agentmods" height="20"></a>
Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 992 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.00992
Opus 5 $0.00000 $0.00496
Sonnet 5 $0.00000 $0.00198
Haiku 4.5 $0.00000 $0.00099

Measured 4d ago against content hash 985130491dde, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

factory scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

code_comment/libs/langchain_v1/langchain/agents/factory.md · 72 lines

How it starts

The opening of the file, as written. The whole thing — 72 lines — stays where its author put it; the contents beside it link to each section on GitHub.

libs\langchain_v1\langchain\agents\factory.py

factory.py 是 LangChain v1 中创建代理的核心工厂模块。它引入了基于 LangGraph 的现代化代理构建方式,支持 Middleware (中间件) 系统和 Structured Output (结构化输出)

核心函数:create_agent

create_agent 是创建代理图(Agent Graph)的统一入口。它将模型、工具和中间件组合成一个可编译的 LangGraph 状态图。

参数说明

参数 类型 描述
model str | BaseChatModel 代理使用的语言模型。如果是字符串,将通过 init_chat_model 初始化。
tools Sequence[BaseTool | Callable] 代理可以调用的工具列表。
system_prompt str | SystemMessage 代理的系统提示词,定义其角色和行为。
middleware Sequence[AgentMiddleware] 中间件序列,用于拦截和修改代理、模型或工具的调用过程。
response_format ResponseFormat | type[ResponseT] 指定代理的输出格式(如 Pydantic 模型或 JSON Schema)。
state_schema type[AgentState] 自定义代理的状态模式。默认为 AgentState
checkpointer Checkpointer 用于持久化代理状态的检查点。
interrupt_before list[str] 在进入指定节点前中断执行。
interrupt_after list[str] 在退出指定节点后中断执行。
debug bool 是否开启调试模式,输出详细执行日志。

执行逻辑

  1. 中间件链初始化: 将传入的 middleware 序列组合成嵌套的调用栈(Middleware Stack)。第一个中间件处于最外层。
  2. 状态图构建:
    • 使用 StateGraph 定义代理的执行流程。
    • 核心节点包括 agent(决策节点)和 tools(执行节点)。
  3. 循环迭代:
    • 代理根据当前 messages 决定调用工具或直接回复。
    • 如果调用工具,则进入 tools 节点,执行后将 ToolMessage 返回给代理。
    • 如果满足停止条件(如生成了最终回复或达到了最大调用次数),则结束流程。

核心机制

1. 中间件组合 (_chain_model_call_handlers)

该模块内部使用递归方式将多个中间件的 wrap_model_call 处理器组合在一起。

  • 外层优先: 序列中前面的中间件会包裹后面的中间件。
  • 请求/响应拦截: 中间件可以在模型调用前后修改 ModelRequestModelResponse

2. 动态工具支持

如果在中间件中动态添加了工具(即不在 create_agent 初始列表中的工具),需要注意:

  • 必须在 wrap_tool_call 中手动处理这些动态工具的执行。
  • 否则,代理会因为找不到对应的工具执行器而报错。

3. 错误恢复模板

模块定义了 STRUCTURED_OUTPUT_ERROR_TEMPLATE,当结构化输出解析失败时,会自动将错误信息反馈给模型,引导其修正输出。

使用示例

from langchain.agents import create_agent
from langchain.agents.middleware import ModelRetryMiddleware

# 定义一个带重试机制的代理
agent = create_agent(
    model="gpt-4o",
    tools=[my_tool],
    middleware=[ModelRetryMiddleware(max_attempts=3)],
    system_prompt="你是一个专业的助手。"
)

# 编译并运行
app = agent.compile()
result = app.invoke({"messages": [("user", "执行任务")]})

Read the full file on GitHub · 72 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 72 lines · 0 tokens per session scan A 985130491dde

Subscribe to this mod's changes

factory is an agent published in the GitHub repository xt765/LangChain-Chinese-Comment (20 stars, last pushed 1mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 992 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other agents, from other repositories

strategic-advisor

Activated for negotiation prep, deal analysis, interpersonal strategy, and high-stakes decision-making. Combines game theory with psychological awareness.

winstonkoh87/Athena-Public · 31 tokens

integration-reviewer

Runtime integration validator — read-only. Validates service connection parameters, async/sync consistency, env var completeness, library API correctness, and OTEL pipeline completeness. Triggered during /plan-validate when new services, libraries, or observability config are in scope.

FlorianBruniaux/claude-code-ultimate-guide · 57 tokens

roadmap

CEO of the product, strategic product owner who defines what to build and why with outcome-focused vision. Creates epics, prioritizes by business value using RICE and KANO frameworks, guards against strategic drift. Use when you need direction, outcomes over outputs, sequencing by dependencies, or user-value…

rjmurillo/ai-agents · 64 tokens

code-reviewer

Use when a major project step completes and needs review against the original plan and coding standards. Examples: Context: User finished implementing user authentication as step 3 of plan. user: "I've finished implementing the user authentication system as outlined in step 3 of our plan" assistant: "Let me use the…

axiomantic/spellbook · 190 tokens

agent-registry-auditor

Audits agents for DIP-0016 compliance and registry alignment. Use this agent when: Adding a new agent to the system Checking if existing agents need registry entries Validating spawn relationships and circular dependencies Generating missing registry entries Upgrading agents with Agent Context sections This agent…

datacore-one/datacore · 84 tokens

gan-harness

You are a GAN-style adversarial multi-agent harness coordinator. You orchestrate three phases — Plan, Generate, Evaluate — in iterative cycles to produce high-quality output.

datacore-one/datacore · 0 tokens