前言¶
在 DeepSeek Harness (DSH) 的開發中,直接集成 LangGraph 需要處理圖的定義、工具註冊以及路由邏輯。dsh-graph-runtime 是一個獨立的 Cordis 插件/Bundle,它將 LangGraph 編譯圖註冊爲 DSH 工具,並提供一個基於圖的驅動路由代理。
這是什麼¶
這是一個爲 DSH 提供圖運行時能力的獨立插件。它由開發者 snail30xx 維護,許可證爲 MIT。主要解決在 DSH 環境下定義圖、自動掛載以及智能路由的問題。
核心功能¶
- 定義與自動掛載:通過
defineGraph定義擴展的 StateGraph,模塊加載即完成註冊。 - 工具註冊:將 LangGraph 編譯圖註冊爲 DSH 工具(
asTool),自動發現工具名稱和描述。 - 圖驅動路由代理:提供一個
GraphRoutingAgent,讓 LLM 從圖工具中選擇一個執行。 - 驗證與擴展:內置工具參數驗證鉤子,並提供
graphTools/pre-execute和graphTools/post-execute兩個擴展點。
安裝與啓用¶
安裝前請確保環境滿足依賴要求:
* Node.js >= 22.5
* 依賴項:@deepseek-ai/cordis、@deepseek-ai/dsh-llm、@langchain/langgraph
執行安裝命令:
npm install dsh-graph-runtime
在 cordis.yml 的根組合中添加條目(插件自帶 cordis.patch.yml,添加包名到配置會自動掛載):
- id: graph-runtime
name: dsh-graph-runtime
典型用法¶
1. 定義圖¶
圖作者只需使用 defineGraph 定義圖,無需手動掛載或調用服務。
// graphs/echo.ts
import { defineGraph } from 'dsh-graph-runtime'
import { Annotation, END, START, StateGraph } from '@langchain/langgraph'
const State = Annotation.Root({
topic: Annotation<string>,
log: Annotation<string[]>({
reducer: (left, right) => [...left, ...right],
default: () => [],
}),
})
export const echoGraph = defineGraph({
name: 'echo_graph',
description: 'Echo the given topic.',
build: () =>
new StateGraph(State)
.addNode('echo', async (state) => ({ log: [`seen:${state.topic}`] }))
.addEdge(START, 'echo')
.addEdge('echo', END),
asTool: true, // 聲明爲模型可見的 DSH 工具
})
2. 使用 GraphRoutingAgent¶
使用 GraphRoutingAgent 初始化路由代理,配置模型、過濾器等參數。
import { GraphRoutingAgent } from 'dsh-graph-runtime'
const router = new GraphRoutingAgent(ctx, {
provider: 'deepseek',
model: 'deepseek-chat',
filter: { allow: ['echo_graph', 'search_graph'] },
maxRetries: 3, // 驗證失敗時的最大重試次數
})
const outcome = await router.route({ input: 'echo hello for me' })
3. 利用擴展點¶
通過 ctx.on 監聽 graphTools/pre-execute 和 graphTools/post-execute 事件,可以在圖執行前後進行審計、策略門控或結果轉換。
// 執行前門控
ctx.on('graphTools/pre-execute', async (execution, next) => {
if (execution.tool === 'restricted_tool') {
return { kind: 'deny', reason: 'Policy disabled' }
}
return next()
})
// 執行後轉換
ctx.on('graphTools/post-execute', async (execution, outcome, next) => {
if (execution.tool === 'sensitive_graph') {
return { kind: 'accept', result: redact(outcome.result) }
}
return next()
})
適用場景與注意¶
這個插件適合需要在 DSH 中通過 LangGraph 構建複雜工作流,並需要統一工具管理和智能路由的場景。
注意事項:
* 插件以當前 DSH 進程的權限運行。
* 使用前建議檢查源碼與許可證(MIT)。
* 需要支持 TypeScript module (type: module)。
總結¶
dsh-graph-runtime 通過 defineGraph 和 GraphRoutingAgent 封裝了 LangGraph 在 DSH 中的集成細節,提供了自動掛載、驗證鉤子和執行擴展點,簡化了圖工具的開發與路由邏輯。