graph-tool-call
graph-tool-call
LLM 智能体无法将数千个工具定义放入上下文。 向量搜索可以找到相似的工具,但会遗漏它们所属的工作流。 graph-tool-call 构建工具图并检索正确的链条——而不仅仅是一个匹配项。
无检索 | graph-tool-call | |
248 个工具 (K8s API) | 12% 准确率 | 82% 准确率 |
1068 个工具 (GitHub 完整 API) | 上下文溢出 | 78% Recall@5 |
Token 使用量 | 8,192 tok | 1,699 tok (减少 79%) |
使用 qwen3:4b (4-bit) 测量 — 完整基准测试
为什么选择它
LLM 智能体需要工具。但随着工具数量的增加,会出现两个问题:
上下文溢出 — 248 个 Kubernetes API 端点 = 8,192 个 Token 的工具定义。LLM 会不堪重负,准确率降至 12%。
向量搜索无法处理工作流 — 搜索 "取消我的订单" 会找到
cancelOrder,但实际流程是listOrders → getOrder → cancelOrder → processRefund。向量搜索只返回一个工具;你需要的是整个链条。
graph-tool-call 同时解决了这两个问题。它将工具关系建模为图,通过混合搜索(BM25 + 图遍历 + 嵌入 + MCP 注解)检索多步工作流,在保持或提高准确率的同时,减少了 64–91% 的 Token 使用量。
场景 | 仅向量搜索 | graph-tool-call |
"取消我的订单" | 返回 |
|
"读取并保存文件" | 返回 |
|
"删除旧记录" | 返回任何匹配 "delete" 的工具 | 通过 MCP 注解优先排序破坏性工具 |
"现在取消它" (在列出订单后) | 历史记录无上下文 | 降低已使用工具的权重,提升下一步工具的权重 |
多个具有重叠工具的 Swagger 规范 | 结果中存在重复工具 | 跨源自动去重 |
1,200 个 API 端点 | 缓慢,结果嘈杂 | 分类 + 图遍历以实现精确检索 |
工作原理
OpenAPI / MCP / Python functions → Ingest → Build tool graph → Hybrid retrieve → Agent示例 — 用户说 "取消我的订单并处理退款"
向量搜索找到 cancelOrder。但实际工作流是:
┌──────────┐
PRECEDES │listOrders│ PRECEDES
┌─────────┤ ├──────────┐
▼ └──────────┘ ▼
┌──────────┐ ┌───────────┐
│ getOrder │ │cancelOrder│
└──────────┘ └─────┬─────┘
│ COMPLEMENTARY
▼
┌──────────────┐
│processRefund │
└──────────────┘graph-tool-call 返回整个链条,而不仅仅是一个工具。检索通过 加权倒数排名融合 (wRRF) 结合了四个信号:
BM25 — 关键词匹配
图遍历 — 基于关系的扩展 (PRECEDES, REQUIRES, COMPLEMENTARY)
嵌入相似度 — 语义搜索 (可选,支持任何提供商)
MCP 注解 — 只读 / 破坏性 / 幂等提示
安装
核心包零依赖 — 仅使用 Python 标准库。按需安装:
pip install graph-tool-call # core (BM25 + graph) — no dependencies
pip install graph-tool-call[embedding] # + embedding, cross-encoder reranker
pip install graph-tool-call[openapi] # + YAML support for OpenAPI specs
pip install graph-tool-call[mcp] # + MCP server / proxy mode
pip install graph-tool-call[all] # everything扩展 | 安装内容 | 使用场景 |
| pyyaml | YAML OpenAPI 规范 |
| numpy | 语义搜索 (连接到 Ollama/OpenAI/vLLM) |
| numpy, sentence-transformers | 本地 sentence-transformers 模型 |
| rapidfuzz | 重复检测 |
| langchain-core | LangChain 集成 |
| pyvis, networkx | HTML 图导出, GraphML |
| dash, dash-cytoscape | 交互式仪表盘 |
| ai-api-lint | 自动修复错误的 API 规范 |
| mcp | MCP 服务器 / 代理模式 |
快速开始
30 秒内尝试 (无需安装)
uvx graph-tool-call search "user authentication" \
--source https://petstore.swagger.io/v2/swagger.jsonQuery: "user authentication"
Source: https://petstore.swagger.io/v2/swagger.json (19 tools)
Results (5):
1. getUserByName — Get user by user name
2. deleteUser — Delete user
3. createUser — Create user
4. loginUser — Logs user into the system
5. updateUser — Updated userPython API
from graph_tool_call import ToolGraph
# Build a tool graph from the official Petstore API
tg = ToolGraph.from_url(
"https://petstore3.swagger.io/api/v3/openapi.json",
cache="petstore.json",
)
print(tg)
# → ToolGraph(tools=19, nodes=22, edges=100)
# Search for tools
tools = tg.retrieve("create a new pet", top_k=5)
for t in tools:
print(f"{t.name}: {t.description}")
# Search with workflow guidance
results = tg.retrieve_with_scores("process an order", top_k=5)
for r in results:
print(f"{r.tool.name} [{r.confidence}]")
for rel in r.relations:
print(f" → {rel.hint}")
# Execute an OpenAPI tool directly
result = tg.execute(
"addPet", {"name": "Buddy", "status": "available"},
base_url="https://petstore3.swagger.io/api/v3",
)工作流规划
plan_workflow() 返回带有先决条件的有序执行链 — 将智能体的往返次数从 3-4 次减少到 1 次。
plan = tg.plan_workflow("process a refund")
for step in plan.steps:
print(f"{step.order}. {step.tool.name} — {step.reason}")
# 1. getOrder — prerequisite for requestRefund
# 2. requestRefund — primary action
plan.save("refund_workflow.json")编辑、参数化和可视化工作流 — 请参阅 Direct API 指南。
其他工具源
# From an MCP server (HTTP JSON-RPC tools/list)
tg.ingest_mcp_server("https://mcp.example.com/mcp")
# From an MCP tool list (annotations preserved)
tg.ingest_mcp_tools(mcp_tools, server_name="filesystem")
# From Python callables (type hints + docstrings)
tg.ingest_functions([read_file, write_file])MCP 注解 (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) 被用作检索信号 — 查询意图会自动分类,读取查询会优先考虑只读工具,而删除查询会优先考虑破坏性工具。
选择你的集成方式
graph-tool-call 提供了几种集成模式。选择最适合你技术栈的一种:
你正在使用... | 模式 | Token 节省 | 指南 |
Claude Code / Cursor / Windsurf | MCP 代理 (聚合 N 个 MCP 服务器 → 3 个元工具) | ~1,200 tok/轮 | |
任何兼容 MCP 的客户端 | MCP 服务器 (作为 MCP 的单一源) | 不等 | |
LangChain / LangGraph (50+ 工具) | 网关工具 (N 个工具 → 2 个元工具) | 92% | |
OpenAI / Anthropic SDK (现有代码) | 中间件 (1 行猴子补丁) | 76–91% | |
对检索的直接控制 | Python API ( | 不等 |
MCP 代理 (最常用)
当你拥有许多 MCP 服务器时,它们的工具名称会在每一轮 LLM 对话中堆积。将它们捆绑在一个服务器后面:172 个工具 → 3 个元工具。
# 1. Create ~/backends.json listing your MCP servers
# 2. Register the proxy with Claude Code
claude mcp add -s user tool-proxy -- \
uvx "graph-tool-call[mcp]" proxy --config ~/backends.json完整设置、透传模式、远程传输 → MCP 代理指南。
LangChain 网关
from graph_tool_call.langchain import create_gateway_tools
# 62 tools from Slack, GitHub, Jira, MS365...
gateway = create_gateway_tools(all_tools, top_k=10)
# → [search_tools, call_tool] — only 2 tools in context
agent = create_react_agent(model=llm, tools=gateway)与绑定所有 62 个工具相比,Token 减少了 92%。请参阅 LangChain 指南 以获取自动过滤和手动模式。
SDK 中间件
from graph_tool_call.middleware import patch_openai
patch_openai(client, graph=tg, top_k=5) # ← add this one line
# Existing code unchanged — 248 tools go in, only 5 relevant ones are sent
response = client.chat.completions.create(
model="gpt-4o",
tools=all_248_tools,
messages=messages,
)也通过 patch_anthropic 支持 Anthropic。请参阅 中间件指南。
基准测试
两个问题:(1) 当只给出检索到的子集时,LLM 是否仍能选择正确的工具?(2) 检索器本身是否将正确的工具排在 Top K 中?
数据集 | 工具数 | 基准准确率 | graph-tool-call | Token 减少 |
Petstore | 19 | 100% | 95% (k=5) | 64% |
GitHub | 50 | 100% | 88% (k=5) | 88% |
混合 MCP | 38 | 97% | 90% (k=5) | 83% |
Kubernetes core/v1 | 248 | 12% | 82% (k=5 + 本体) | 79% |
关键发现 — 在 248 个工具时,基准测试崩溃(上下文溢出)至 12%,而 graph-tool-call 恢复至 82%。在较小规模下,基准测试已经很强,因此 graph-tool-call 的价值在于在不损失准确率的情况下节省 Token。
→ 完整结果(流水线 / 仅检索 / 竞争性 / 1068 规模 / 200 工具 LangChain 智能体,涵盖 GPT 和 Claude):docs/benchmarks.md
# Reproduce
python -m benchmarks.run_benchmark # retrieval only
python -m benchmarks.run_benchmark --mode pipeline -m qwen3:4b # full pipeline高级功能
基于嵌入的混合搜索
在 BM25 + 图的基础上添加语义搜索。无需繁重的依赖 — 连接到任何外部嵌入服务器。
tg.enable_embedding("ollama/qwen3-embedding:0.6b") # Ollama (recommended)
tg.enable_embedding("openai/text-embedding-3-large") # OpenAI
tg.enable_embedding("vllm/Qwen/Qwen3-Embedding-0.6B") # vLLM
tg.enable_embedding("sentence-transformers/all-MiniLM-L6-v2") # local
tg.enable_embedding(lambda texts: my_embed_fn(texts)) # custom callable权重会自动重新平衡。请参阅 API 参考 获取所有提供商格式。
检索调优
tg.enable_reranker() # cross-encoder rerank
tg.enable_diversity(lambda_=0.7) # MMR diversity
tg.set_weights(keyword=0.2, graph=0.5, embedding=0.3, annotation=0.2)历史感知检索
传递之前调用的工具以降低其权重,并提升下一步候选工具的权重。
tools = tg.retrieve("now cancel it", history=["listOrders", "getOrder"])
# → [cancelOrder, processRefund, ...]保存 / 加载 (保留嵌入 + 权重)
tg.save("my_graph.json")
tg = ToolGraph.load("my_graph.json")
# Or use cache= in from_url() for automatic save/load
tg = ToolGraph.from_url(url, cache="my_graph.json")LLM 增强的本体
tg.auto_organize(llm="ollama/qwen2.5:7b")
tg.auto_organize(llm="litellm/claude-sonnet-4-20250514")
tg.auto_organize(llm=openai.OpenAI())构建更丰富的类别、关系和搜索关键词。支持 Ollama、OpenAI 客户端、litellm 和任何可调用对象。请参阅 API 参考。
其他功能
功能 | API | 文档 |
跨规范重复检测 |
| |
冲突检测 |
| |
操作分析 |
| |
交互式仪表盘 |
| |
HTML / GraphML / Cypher 导出 |
| |
自动修复错误的 OpenAPI 规范 |
|
文档
文档 | 描述 |
所有 | |
| |
MCP 服务器 / 代理、LangChain、中间件、直接 API | |
完整流水线 / 检索 / 竞争性 / 规模表格 | |
系统概览、流水线层、数据模型 | |
算法设计 — 规范化、依赖检测、本体 | |
竞争分析、API 规模数据 | |
发布流程、变更日志流程 |
贡献
欢迎贡献。
git clone https://github.com/SonAIengine/graph-tool-call.git
cd graph-tool-call
pip install poetry pre-commit
poetry install --with dev --all-extras
pre-commit install # auto-runs ruff on every commit
# Test, lint, benchmark
poetry run pytest -v
poetry run ruff check . && poetry run ruff format --check .
python -m benchmarks.run_benchmark -v许可证
Latest Blog Posts
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/SonAIengine/graph-tool-call'
If you have feedback or need assistance with the MCP directory API, please join our Discord server