Token导航 LogoToken导航TokenDH.com
MCP Tool Code Interpreter Generator logo
开发工具stdio官方级别未说明来源级核验

MCP Tool Code Interpreter Generator

MCP Server

一个基于LangGraph和多模型LLM的自主代码生成管道,能够从自然语言查询生成、验证和执行Python数据分析工具。

工具数

0

提示词数

0

GitHub Stars

1

资源数

0
代码生成机器学习Python数据分析自然语言处理

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

SwetaAIS2024

提供方

SwetaAIS2024

最后核验

2026/5/17 20:20

运行时

Python

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

python -m venv venv

详细介绍

LangGraph工具代码生成器和解释器

自主代码生成管道 使用LangGraph编排和多模型LLM方法

一个可重用的LangGraph工作流,可以从自然语言查询中自动生成、验证和执行Python数据分析工具。设计为可组合的子图,用于集成到更大的代理系统中。采用LangGraph状态机编排构建,并由专门的LLM提供支持,用于推理和代码生成。

______________________________________________________________________

概述

它的作用:

  1. 进行自然语言数据分析查询
  2. 使用推理模型提取结构化意图(DeepSeek-R1)
  3. 生成正式的工具规格
  4. 使用专门的编码模型(Qwen 2.5-Coder)生成Python代码
  5. 在隔离的Docker/subprocess沙箱中验证代码
  6. 执行并捕获分析结果
  7. 将经过验证的工具推广到活动注册表
  8. 将所有输出打包成 projected_* 用于无缝父图集成的字段

用作子图: 该管道旨在作为可重用的LangGraph子图集成到更大的代理系统中。使用 build_graph() 获取编译后的图并将其集成到父工作流中。

示例查询:

"Run ANOVA across groups, then perform Tukey HSD post-hoc test with p-values and effect sizes"

结果:

  • 生成的工具: anova_tukeyhsd_traffic_injuries_.py
  • 具有验证输出的统计分析
  • 自动添加到活动工具注册表(tools/active/)

______________________________________________________________________

建筑

技术栈

  • LangGraph -StateGraph工作流编排和可组合性
  • DeepSeek-R1 70B -用于意图提取和规范生成的推理模型
  • Qwen 2.5编码器32B -代码生成和修复
  • 奥拉玛 -本地LLM推理服务器
  • Pydantic v2.5+ -数据验证
  • Python 3.10+ -核心运行时
  • 码头工人 -沙盒隔离(可选子流程模式可用)

管道流量

User Query 
    ↓
Intent Extraction (DeepSeek-R1)
    ↓
Spec Generation (DeepSeek-R1)
    ↓
Code Generation (Qwen 2.5-Coder)
    ↓
Validation (syntax + schema + sandbox)
    ├─→ PASS → Executor
    └─→ FAIL → Repair (Qwen 2.5-Coder, max 5 attempts)
              ↓
         Validator
    ↓
Executor (run on actual data)
    ├─→ SUCCESS → Promoter
    └─→ FAIL → END (with error report)
    ↓
Promoter (save to active registry)
    ↓
Projection (package outputs into projected_* fields for parent graph)
    ↓
END

LangGraph节点

管道由以下节点组成:

  • intent_node -使用推理模型从自然语言中提取结构化意图
  • 规范生成器节点 -使用I/O模式创建正式的工具规范
  • 代码生成器节点 -生成实现规范的Python代码
  • 验证器节点 -验证语法、模式合规性和沙盒执行
  • 修复节点 -根据验证错误修复代码(最多5次尝试)
  • 执行者节点 -对实际用户数据执行工具
  • promoter_node -将成功的工具推广到活动注册表
  • 项目节点 -终端节点;将所有子输出打包到 projected_* 与父图兼容的字段(状态模式: AnalysisPipelineState)

有关详细的体系结构和模块描述,请参阅 module_prs/README.md

______________________________________________________________________

项目结构

MCP_Tool_Code_Interpreter_Generator/
├── src/                         # Core modules
│   ├── models.py               # Pydantic models and LangGraph state
│   ├── llm_client.py           # Multi-model LLM client
│   ├── intent_extraction.py    # Intent extraction node
│   ├── intent_validator.py     # Intent validation logic
│   ├── spec_generator.py       # Specification generation node
│   ├── code_generator.py       # Code generation + repair nodes
│   ├── validator.py            # Validation node  
│   ├── executor.py             # Execution node
│   ├── promoter.py             # Registry promotion node
│   ├── sandbox.py              # Sandboxed code execution
│   ├── pipeline.py             # LangGraph orchestrator & graph builder
│   └── logger_config.py        # Logging configuration
│
├── tools/                       # Generated tools
│   ├── draft/                  # Initial generated code
│   ├── active/                 # Promoted, production-ready tools
│   ├── sandbox/                # Sandbox workspace for execution
│   └── registry.json          # Active tool metadata (written by promoter)
│
├── output/                      # Execution results
│   ├── active/                 # Successful execution outputs (JSON)
│   ├── draft/                  # Failed/debug outputs
│   └── plots/                  # Generated visualisation PNGs
│
├── config/                      # Configuration files
│   ├── config.yaml             # Main configuration
│   ├── sandbox_policy.yaml     # Sandbox security policy
│   └── prompts/                # LLM prompt templates
│       ├── intent_extraction_v2.txt
│       ├── spec_generation.txt
│       ├── code_generation.txt
│       └── code_repair.txt
│
├── docker/                      # Docker sandbox
│   ├── Dockerfile.sandbox
│   └── docker-compose.sandbox.yml
│
├── integration/                 # Parent-graph integration adapter
│   ├── __init__.py             # Exports build_child_input, apply_child_output
│   └── mapper.py               # Input mapper + output projector implementation
│
├── tests/                       # Test suite
├── docs/                        # Documentation
└── test.py                      # Interactive pipeline testing

______________________________________________________________________

快速开始

1.先决条件

  • Python 3.10或更高版本
  • 奥拉玛 已安装并正在运行
  • Docker(可选,用于Docker沙盒模式)

2.设置Olama模型

# Pull the reasoning model (for intent extraction & spec generation)
ollama pull deepseek-r1:70b

# Pull the coding model (for code generation & repair)
ollama pull qwen2.5-coder:32b

# Verify models are available
ollama list

3.设置环境

# Clone the repository (if applicable)
cd MCP_Tool_Code_Interpreter_Generator

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt
pip install -r requirements-dev.txt

4.配置系统

中的默认配置 config/config.yaml 应该与Ollama合作:

llm:
  base_url: "http://localhost:11434/v1"  # Ollama default endpoint
  
  models:
    reasoning: "deepseek-r1:70b"         # Intent + spec generation
    coding: "qwen2.5-coder:32b"          # Code generation + repair
    
  
  temperature: 0.4

sandbox:
  mode: "docker"  # or "docker" for stronger isolation (Linux only)
  timeout_seconds: 300
  memory_limit_mb: 512

5.测试管道

# Run interactive test with a sample query
python test.py "Calculate average values by group"

# Run with specific query
python test.py "Run ANOVA across groups with Tukey HSD post-hoc test"

# Adjust verbosity
python test.py -v "your query here"
python test.py -d "your query here"

______________________________________________________________________

多模型配置

系统使用 两种特殊型号 为了获得最佳性能:

推理模型(DeepSeek-R1 70B)

  • 用于: 意图提取、规范生成
  • 为什么? 更好地理解复杂的需求和规划
  • 行为: 可包括 `` 推理过程中的标签(自动剥离)

编码型号(Qwen 2.5编码器32B)

  • 用于: 代码生成、代码修复
  • 为什么? 专门用于生成干净、高效的Python代码
  • 行为: 无元评论的专注输出

LLM客户内部(src/llm_client.py)

  • model_override 参数打开 QwenLLMClient.__init__ 按别名选择模型("reasoning""coding")
  • 温度固定在 0.0 用于确定性结构化输出
  • ` 标签剥离:所有内容之间 ...` 在JSON解析之前删除
  • 智能支架边界检测:找到最外层 {...} 处理包裹或填充输出的响应中的块
  • Markdown代码围栏提取:在JSON解析之前剥离三重回溯块

快速设计(配置/提示/)

每次推理模型调用时都会发送严格的JSON强制指令:

CRITICAL INSTRUCTIONS:
- Return ONLY valid JSON conforming to the schema below
- DO NOT include any explanatory text, thinking process, or commentary
- DO NOT use  tags or similar meta-text
- DO NOT add markdown code fences around the JSON
- Output must be pure JSON starting with { and ending with }

意图提取提示中嵌入的操作选择指南:

OPERATION SELECTION GUIDE:
- "top N X by Y" or "most common X"  -> use "groupby_aggregate"
- "filter by X"                      -> use "filter"
- "summary statistics"               -> use "describe_summary"
- "ANOVA / statistical test"         -> use "statistical_test"

______________________________________________________________________

集成和使用

独立测试

对于开发和测试,请使用交互式测试脚本:

# Test with a specific query
python test.py "your analysis query"

# Adjust verbosity
python test.py -d "query here"

______________________________________________________________________

与父级LangGraph集成(AnalysisPipelineState)

子图(由构建 build_graph(),状态架构: ToolGeneratorState)被设计为 黑盒节点 从父图(状态模式: AnalysisPipelineState,由 ModularAnalysisPipelineAgent._build_graph()).因为家长使用 extra='forbid', 子模式是这样调整的 不需要更改父架构 超越单一 保护字段和新节点。

触发器:子图何时运行?

子图由父图触发 reflect 节点通过 missing_info 路径:

  1. interpret_results 生产 coverage.missing_info --现有工具无法满足的分析差距列表。
  2. reflect 读取 missing_info 并根据可用工具对其进行过滤。当 现有的工具无法满足剩余的缺失项目, reflect 电话 _diagnose_tool_gap() 和设置 capability_gap.
  3. 而不是路由到 synthesis (当前行为),设置的两个分支 capability_gap 路线到 tool_generator_node.
  4. tool_generator_node 使用以下命令调用子图 missing_info 作为查询 (不是全部 instruction).孩子生成、验证并执行一个新工具,该工具直接回答现有工具无法回答的问题。
  5. apply_child_output 将子结果合并到父状态,然后节点路由到 interpret_results --上面写着新 tool_transcript 从推广工具的输出中输入和提取见解,并将其折叠到最终报告中。
interpret_results
    ↓ (coverage.missing_info set)
reflect
    ├─ existing tools can answer → replan / synthesize (unchanged)
    └─ no tool can satisfy missing_info → capability_gap set
            ↓
    tool_generator_node   ← child graph runs here
    (user_query = missing_info items; data_path = state.dataset_path)
            ↓
    interpret_results     ← reads new tool_transcript entries from promoted tool
            ↓
    reflect → synthesis → persist_cleanup → END

状态兼容性

问题如何解决
家长 extra='forbid'子输出仅投影到现有的父通道中
messages 类型不匹配子项 messagesList[BaseMessage] + add_messages,与父母完全匹配
子内部字段(tool_spec, generated_code, draft_path等)从未给父母写信;保持儿童状态
生成的工具源代码从未发送给父母。 tool_generator_node 不包括 messagesCommand(update=...),因此孩子的AIMessage(包含代码块)被丢弃。父级仅接收文件路径。
所有子结果打包者 projection_node (终端子节点)转换为6 projected_* 字段

输出投影图

之后 child_graph.invoke() 完成, projection_node 已预先打包所有结果 在返回的子状态中输入以下字段:

子字段父频道内容——包括和不包括什么
projected_tool_transcripttool_transcript仅元数据:5个事件(意图、规范、验证器、执行器、发起人)。 没有源代码。
projected_artifact_logartifact_log仅文件路径:活动工具 .py,主动输出 .json,情节 .png. 没有文件内容。
projected_capability_gapcapability_gapNone 当工具成功推广时;无None 如果生成失败,则执行dict
projected_errorserrors列表扩展
projected_warningswarnings列表扩展
projected_final_artifactsfinal_artifacts{"promoted_tool": {name, path, registry_path, output_path}} --仅路径, 无代码
生成的工具源代码永远不会到达父图。 父级只接收指向的文件路径 tools/active/output/active/。如果父级需要读取代码,它可以从打开路径 final_artifacts["promoted_tool"]["path"].

集成适配器(integration/)

integration/ 项目根目录下的包提供了两个实现 完整的集成合同。 父图所有者只需要这两个调用。

integration/
├── __init__.py   # exports build_child_input, apply_child_output
└── mapper.py     # full implementation with docstrings

输入映射 (build_child_input + missing_info 以(权力)否决

来源子字段注释
state.coverage["missing_info"] (已加入)user_query现有工具无法弥补的具体差距——覆盖 state.instruction
state.dataset_pathdata_path父级正在分析的数据集相同

父端需要更改

1. pipeline/state.py --向添加一个保护字段 AnalysisPipelineState:

tool_gen_attempted: bool = Field(
    default=False,
    description="Prevents re-triggering the child graph if it fails to clear the capability gap"
)

2. pipeline/runner.py --进口:

import sys
sys.path.insert(0, "/path/to/MCP_Tool_Code_Interpreter_Generator")

from integration import build_child_input, apply_child_output
from src.pipeline import build_graph as build_child_graph

3. ModularAnalysisPipelineAgent.__init__ --一次构建子图:

self._child_graph = build_child_graph()

4.上的新节点方法 ModularAnalysisPipelineAgent:

import uuid  # add to runner.py imports if not already present

async def tool_generator_node(self, state: AnalysisPipelineState) -> Command:
    """Invoke child tool-generator pipeline to fill a detected capability gap.

    Uses missing_info (what existing tools could not answer) as the child query,
    not the full instruction. This targets generation precisely at the gap.

    IMPORTANT: Do NOT call apply_child_output(child_result, state) here.
    apply_child_output uses setattr/dict mutation which LangGraph does not
    persist — all state changes must flow through Command(update=...).
    """
    child_init = build_child_input(state)  # baseline: instruction -> user_query, dataset_path -> data_path

    # Override user_query with the specific missing items — more precise than full instruction
    missing = []
    try:
        missing = (state.coverage or {}).get("missing_info") or []
    except Exception:
        pass
    if missing:
        child_init["user_query"] = "; ".join(str(m) for m in missing if m)

    child_result = self._child_graph.invoke(
        child_init,
        {"configurable": {"thread_id": str(uuid.uuid4())}}
    )

    # Build LangGraph-safe updates dict.
    # - Extend-reducer fields (tool_transcript, artifact_log, errors, warnings):
    #   return ONLY the new delta items — the reducer merges them into existing state.
    #   Returning the full merged list would cause the reducer to double-apply, creating duplicates.
    # - Replace-reducer fields (capability_gap, final_artifacts):
    #   return the final intended value directly.
    updates: Dict[str, Any] = {"tool_gen_attempted": True}

    # Extend-reducer fields — delta only
    new_transcript = child_result.get("projected_tool_transcript") or []
    if new_transcript:
        updates["tool_transcript"] = new_transcript  # _merge_tool_transcript reducer extends

    new_artifact_log = child_result.get("projected_artifact_log") or []
    if new_artifact_log:
        updates["artifact_log"] = new_artifact_log  # ARTIFACT_LOG_REDUCER extends + dedupes

    new_errors = child_result.get("projected_errors") or []
    if new_errors:
        updates["errors"] = new_errors  # ERRORS_REDUCER extends

    new_warnings = child_result.get("projected_warnings") or []
    if new_warnings:
        updates["warnings"] = new_warnings  # WARNINGS_REDUCER extends

    # Replace-reducer fields — final value
    updates["capability_gap"] = child_result.get("projected_capability_gap")  # None = gap filled

    new_fa = child_result.get("projected_final_artifacts")
    if new_fa:
        # _replace_latest_dict replaces entirely — merge with existing first to avoid data loss
        existing_fa = dict(state.final_artifacts or {})
        existing_fa.update(new_fa)
        updates["final_artifacts"] = existing_fa

    return Command(update=updates, goto="interpret_results")
关于 apply_child_output: 此函数是普通Python/非LangGraph调用者(A2A服务器、测试脚本)的正确集成契约。在LangGraph节点内,所有状态更改都必须经过 Command(update=...)setattr 状态对象上的突变不会被检查指针持久化。

5.在中注册节点和线边缘 _build_graph() (父级的图形生成器方法):

graph.add_node("tool_generator_node", self.tool_generator_node)
graph.add_edge("tool_generator_node", "interpret_results")

# Update reflect's ends list:
graph.add_node("reflect", self.reflect,
    ends=["planner", "execute_step", "interpret_results", "synthesis", "tool_generator_node", END])

6.更新 _route_reflect --在最终规划师/综合决策之前添加:

# Trigger child graph if capability gap detected and not yet attempted
gap = getattr(state, "capability_gap", None)
already_attempted = getattr(state, "tool_gen_attempted", False)
if isinstance(gap, dict) and not already_attempted:
    return "tool_generator_node"

7.在 reflect 节点主体--更改两个 goto="synthesis" 分支设置 capability_gap:

确实有 地方在 reflect 哪里 capability_gap 已设置,代码路由到 synthesis。两者都必须更改为路由 tool_generator_node 相反(由 tool_gen_attempted):

_分支机构1_ (~第2992行)--在以下情况下触发 filtered 为空(没有可操作的缺失项映射到现有工具):

# Add guard before the return:
if not getattr(state, "tool_gen_attempted", False):
    return Command(update=updates, goto="tool_generator_node")
return Command(update=updates, goto="synthesis")

_分支机构2_ (~第3088行)--在以下情况下触发 current_round >= max_refinements (已达到重新规划的上限):

# Add guard before the return:
if not getattr(state, "tool_gen_attempted", False) and updates.get("capability_gap"):
    return Command(update=updates, goto="tool_generator_node")
return Command(update=updates, goto="synthesis")
所有其他 goto="synthesis" 路径在 reflect 保持 未改变的.

什么 capability_gap 指孩子跑完之后

capability_gap value含义
None工具生成并推广成功——填补空白
Dict子图未能推广工具——差距持续存在,综合会注意到
注: 间隙检测器仅考虑磁盘上存在活动文件的工具(tools/active/).指向已删除文件的过时注册表项将被自动排除。

升级的工具元数据始终在中可用 final_artifacts["promoted_tool"] 关于成功。

注: server.py 代理集成不需要。使用 build_graph() 直接 src/pipeline.py.

______________________________________________________________________

工具生命周期

DRAFT → Validation → Execution → PROMOTED
  ↓          ↓            ↓
  └─ (repair loop) ─────────→ REJECTED

工具状态

工具根据其状态存储在不同的目录中:

  • 草稿 (tools/draft/)-新生成的代码,可能有错误
  • 活跃的 (tools/active/)-验证并成功执行,生产就绪
  • 输出 (output/active/)-成功运行工具的执行结果为JSON
  • 情节 (output/plots/)-通过视觉查询生成的可视化PNG
  • 注册表 (tools/registry.json)-所有推广工具的元数据

输出组织

生成的输出遵循命名模式:

___output.json

例子:

output/active/anova_tukeyhsd_traffic_injuries_20260210_171102_output.json

每个输出包括:

  • 原始查询和参数
  • 生成的代码
  • 执行结果
  • 验证报告
  • 时间戳和元数据

______________________________________________________________________

测试

# Run all tests
pytest tests/

# Run specific module tests
pytest tests/test_intent_extraction.py -v
pytest tests/test_validator.py -v

# Run with coverage
pytest --cov=src tests/

# Integration tests
pytest tests/test_integration.py

# Interactive pipeline test
python test.py "your analysis query"

测试详细程度

# Quiet - minimal output
python test.py -q "query"

# Normal - standard progress (default)
python test.py "query"

# Verbose - detailed step information
python test.py -v "query"

# Debug - full LLM prompts and responses
python test.py -d "query"

______________________________________________________________________

安全

沙箱隔离

所有生成的代码都在一个隔离的沙箱中运行,其中包含:

  • 无网络访问 -防止数据泄露
  • 受限文件系统 -仅对数据文件进行只读访问
  • 资源限制 -CPU、内存和超时限制
  • 进口限制 -只允许使用已分配的库
  • 子流程限制 -没有shell命令或外部进程

沙盒模式

1.Docker模式(推荐用于生产环境)

sandbox:
  mode: "docker"
  timeout_seconds: 120
  memory_limit_mb: 512
  • 全容器隔离
  • 完整的环境控制
  • 更高的安全保障
  • 启动时间变慢

2.子流程模式(开发)

sandbox:
  mode: "subprocess"
  timeout_seconds: 30
  memory_limit_mb: 512
  • 执行速度更快
  • 共享主机环境
  • 较低的隔离保证
  • 有利于快速迭代

安全策略

在中配置允许/阻止的导入 config/sandbox_policy.yaml:

allowed_libraries:
  - pandas
  - numpy
  - scipy
  - statsmodels
  - matplotlib
  - seaborn

blocked_imports:
  - os
  - subprocess
  - sys
  - requests
  - urllib

docs/SANDBOX_SECURITY.md 获取全面的安全文档。

______________________________________________________________________

配置

主要配置: config/config.yaml

# LLM Configuration
llm:
  base_url: "http://localhost:11434/v1"
  
  models:
    reasoning: "deepseek-r1:70b"    # Intent extraction & spec generation
    coding: "qwen2.5-coder:32b"     # Code generation & repair
    
  temperature: 0.4

# Directory paths
paths:
  draft_dir: "./tools/draft"
  staged_dir: "./tools/staged"
  active_dir: "./tools/active"
  registry: "./tools/registry.json"
  sandbox_workspace: "./tools/sandbox"

# Validation settings
validation:
  max_repair_attempts: 5            # Code repair retry limit
  sandbox_timeout_seconds: 300

# Sandbox configuration
sandbox:
  mode: "subprocess"                # "docker" or "subprocess"
  timeout_seconds: 300              # Execution timeout
  memory_limit_mb: 512              # Memory limit

# Logging
logging:
  level: "INFO"                     # DEBUG, INFO, WARNING, ERROR
  file: "./logs/pipeline.log"

提示模板: config/prompts/

  • intent_extraction_v2.txt -从查询中提取结构化意图
  • spec_generation.txt -生成工具规格
  • code_generation.txt -生成Python实现代码
  • code_repair.txt -基于验证错误的修复代码

沙盒策略: config/sandbox_policy.yaml

控制代码执行的安全限制:

  • 允许/阻止Python导入
  • 资源限制(CPU、内存、超时)
  • 文件系统访问限制
  • 网络策略

______________________________________________________________________

实施状态

已完成的功能

  • 多模型LLM集成(DeepSeek-R1+Qwen 2.5编码器)
  • LangGraph管道编排
  • 结构化输出的意图提取
  • 使用I/O模式生成规范
  • 使用FastMCP装饰器生成代码
  • 多阶段验证(语法、模式、沙盒)
  • 自动代码修复(最多5次尝试)
  • 沙盒执行(Docker+子流程模式)
  • 工具注册与推广系统
  • 全面的日志记录和调试
  • 统计分析支持(方差分析、Tukey HSD等)
  • 图形可视化(美人鱼图+自动保存的PNG)
  • projection_node --终端节点将所有输出打包成 projected_* 领域
  • ToolGeneratorState 已更新架构以实现父图兼容性(messages, errors, 6 projected_* 字段)
  • 父图集成适配器(integration/build_child_input, apply_child_output)
  • 可视化查询(趋势、图表、分布关键字)的自动绘图生成-保存到 output/plots/
  • Groupby回退:模糊的“按组”查询会自动选择一个带有澄清注释的分类列
  • 间隙检测器过滤过时的注册表项(活动文件已被删除的工具除外)

积极开发

  • 增强的错误恢复策略
  • 其他统计操作
  • 性能优化
  • 扩展测试覆盖范围

有关详细的实施规范,请参阅 module_prs/README.md

______________________________________________________________________

发展

设置开发环境

# Install dev dependencies
pip install -r requirements-dev.txt

# Run linter
ruff check src/

# Format code
black src/ tests/

# Type checking
mypy src/

实用脚本

# Clean sandbox temporary files
python scripts/clean_sandbox.py

# Generate graph visualization
python visualize_graph.py

图形可视化

管道自动生成美人鱼图(pipeline_graph.mmd)展示了LangGraph的工作流程。查看它在 美人鱼直播.

______________________________________________________________________

Ollama服务器配置

在上设置这些环境变量 GPU机器 开始前 ollama serve 以最大限度地提高多GPU设置的性能。

alt text

# Windows — set persistently for the current user (no admin rights required)
[System.Environment]::SetEnvironmentVariable("OLLAMA_HOST",             "0.0.0.0:11434", "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_FLASH_ATTENTION",  "1",             "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_KEEP_ALIVE",       "-1",            "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_KV_CACHE_TYPE",    "q8_0",          "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_MAX_LOADED_MODELS","2",             "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_MAX_QUEUE",        "512",           "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_NUM_PARALLEL",     "2",             "User")
[System.Environment]::SetEnvironmentVariable("OLLAMA_SCHED_SPREAD",     "1",             "User")
# Linux / macOS — add to ~/.bashrc or ~/.zshrc
export OLLAMA_HOST=0.0.0.0:11434
export OLLAMA_FLASH_ATTENTION=1
export OLLAMA_KEEP_ALIVE=-1
export OLLAMA_KV_CACHE_TYPE=q8_0
export OLLAMA_MAX_LOADED_MODELS=2
export OLLAMA_MAX_QUEUE=512
export OLLAMA_NUM_PARALLEL=2
export OLLAMA_SCHED_SPREAD=1

变量引用

变量目的
OLLAMA_HOST0.0.0.0:11434绑定所有接口,以便客户端机器可以通过网络到达Ollama
OLLAMA_FLASH_ATTENTION1启用Flash Attention--减少内存使用并加快注意力计算
OLLAMA_KEEP_ALIVE-1无限期地将模型加载到VRAM中(空闲超时后不会自动卸载)
OLLAMA_KV_CACHE_TYPEq8_0将KV缓存量化为8位——将KV缓存VRAM从~40 GB削减到~5 GB
OLLAMA_MAX_LOADED_MODELS2允许两者 deepseek-r1:70bqwen2.5-coder:32b 同时保持负载
OLLAMA_MAX_QUEUE512Ollama返回503之前可以排队的最大请求数
OLLAMA_NUM_PARALLEL2每个模型的并行推理请求数(匹配 max_concurrent_pipelines)
OLLAMA_SCHED_SPREAD1在所有可用GPU上均匀分布模型层(对于2×A6000设置很重要)
设置这些变量后,重新启动Ollama: ``powershell Get-Process | Where-Object { $_.Name -like "*ollama*" } | Stop-Process -Force Start-Sleep -Seconds 3 ollama serve ` 验证服务器是否正在侦听所有接口: `powershell netstat -an | findstr 11434 # Must show: 0.0.0.0:11434 ``

______________________________________________________________________

故障排除

常见问题

1.Ollama连接失败

# Check if Ollama is running
ollama list

# Check API endpoint
curl http://localhost:11434/v1/models

# Restart Ollama if needed
# (OS-specific restart command)

2.未找到型号

# Pull required models
ollama pull deepseek-r1:70b
ollama pull qwen2.5-coder:32b

# Verify models are available
ollama list

3.验证失败

  • 审查 ValidationReport.errors 在输出
  • 检查生成的代码 tools/draft/
  • 检查日志中的验证详细信息
  • 查看沙盒执行日志

4.Docker沙盒问题

# Check Docker is running
docker ps

# Build sandbox image
cd docker
docker-compose -f docker-compose.sandbox.yml build

# Check sandbox logs
docker logs 

5.沙盒中的导入错误

  • 验证库是否列在 config/sandbox_policy.yaml
  • 检查库是否安装在沙盒环境中
  • 对于Docker模式:添加库后重建沙盒映像

6.内存/超时错误

调整限制 config/config.yaml:

sandbox:
  timeout_seconds: 120      # Increase timeout
  memory_limit_mb: 1024     # Increase memory

调试模式

启用详细日志记录以排除问题:

# Set debug verbosity
python test.py -d "query"

或者在代码中配置:

import logging
logging.basicConfig(level=logging.DEBUG)

检查登录 logs/pipeline.log 查看详细的执行跟踪。

输出检查

# Check draft tools
ls -la tools/draft/

# Check active tools
ls -la tools/active/

# Check execution outputs
ls -la output/active/

# View specific output
cat output/active/anova_tukeyhsd_traffic_injuries__output.json

______________________________________________________________________

文档

对于用户

对于开发者

______________________________________________________________________

开源工具-确认

  • LangGraph -工作流编排和图形组合
  • 奥拉玛 -本地LLM推理
  • 深度求索 -推理模型
  • 通义千问 -代码生成模型

______________________________________________________________________

最后更新2026年2月25日

有关详细的模块文档和实现规范,请参阅 module_prs/README.md.

目录标签

目录标签

代码生成机器学习Python数据分析自然语言处理本地部署自动化工具

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

none

运行时(runtime,运行环境)

Python

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdionone部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP