Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ run
.DS_Store
.tmp
.vscode
.claude

package-lock.json
yarn.lock
Expand Down
4 changes: 4 additions & 0 deletions core/common-util/src/ModuleConfigs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ export class ModuleConfigs {
get(moduleName: string): ModuleConfig | undefined {
return this.inner[moduleName]?.config;
}

* [Symbol.iterator](): Iterator<[string, ModuleConfigHolder]> {
yield* Object.entries(this.inner);
}
}
41 changes: 41 additions & 0 deletions core/common-util/test/ModuleConfig.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { strict as assert } from 'node:assert';
import path from 'node:path';
import { ModuleConfigUtil } from '../src/ModuleConfig';
import { ModuleConfigs } from '../src/ModuleConfigs';
import type { ModuleReference } from '@eggjs/tegg-types';

describe('test/ModuleConfig.test.ts', () => {
Expand Down Expand Up @@ -140,6 +141,45 @@ describe('test/ModuleConfig.test.ts', () => {
}]);
});
});

it('should iterate over all module configs', () => {
const mockInner = {
module1: {
name: 'module1',
reference: { path: '/path/to/module1', name: 'module1' },
config: { foo: 'bar' },
},
module2: {
name: 'module2',
reference: { path: '/path/to/module2', name: 'module2' },
config: { baz: 'qux' },
},
};

const moduleConfigs = new ModuleConfigs(mockInner);
const result: Array<[string, any]> = [];

for (const [ name, holder ] of moduleConfigs) {
result.push([ name, holder ]);
}

assert.strictEqual(result.length, 2);
assert.strictEqual(result[0][0], 'module1');
assert.deepStrictEqual(result[0][1], mockInner.module1);
assert.strictEqual(result[1][0], 'module2');
assert.deepStrictEqual(result[1][1], mockInner.module2);
});

it('should work with empty configs', () => {
const moduleConfigs = new ModuleConfigs({});
const result: Array<[string, any]> = [];

for (const [ name, holder ] of moduleConfigs) {
result.push([ name, holder ]);
}

assert.strictEqual(result.length, 0);
});
});

describe('ModuleConfigUtil.deduplicateModules', () => {
Expand Down Expand Up @@ -323,3 +363,4 @@ describe('ModuleConfigUtil.deduplicateModules', () => {
});
});
});

9 changes: 9 additions & 0 deletions core/langchain-decorator/src/util/GraphInfoUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ export class GraphInfoUtil {
return MetadataUtil.getMetaData(GRAPH_GRAPH_METADATA, clazz);
}

static getGraphByName(graphName: string): { clazz: EggProtoImplClass; metadata: IGraphMetadata } | undefined {
for (const [ clazz, metadata ] of GraphInfoUtil.graphMap.entries()) {
if (metadata.name === graphName) {
return { clazz, metadata };
}
}
return undefined;
}

static getAllGraphMetadata(): Map<EggProtoImplClass, IGraphMetadata> {
return GraphInfoUtil.graphMap;
}
Expand Down
145 changes: 145 additions & 0 deletions plugin/langchain/app/controller/RunsController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import {
HTTPController,
HTTPMethod,
HTTPMethodEnum,
HTTPBody,
Context,
Middleware,
Inject,
} from '@eggjs/tegg';
import type { EggContext } from '@eggjs/tegg';
import type { RunCreateDTO } from './types';
import { streamSSE } from '../../lib/sse';
import { RunCreate } from './schemas';
import { ZodErrorMiddleware } from '../middleware/ZodErrorMiddleware';
import { RunsService } from '../../lib/runs/RunsService';

/**
* LangGraph Runs Controller
* 处理 Run 相关的 HTTP 请求
*/
@HTTPController({
path: '/api',
})
@Middleware(ZodErrorMiddleware)
export class RunsController {
@Inject()
runsService: RunsService;
/**
* POST /api/runs/stream
* 流式创建无状态 Run (SSE)
*
* 对应 LangGraph runs.mts 的 api.post("/runs/stream", ...) 端点
*/
@HTTPMethod({
method: HTTPMethodEnum.POST,
path: '/runs/stream',
})
async streamStatelessRun(@Context() ctx: EggContext, @HTTPBody() payload: RunCreateDTO) {
const validated = RunCreate.parse(payload);

// 使用 RunsService 创建并验证 run
const run = await this.runsService.createValidRun(
undefined, // threadId (无状态 run)
validated,
{
// auth: ctx.auth, // TODO: 集成认证系统
headers: ctx.headers,
},
);

console.log('streamStatelessRun', {
run,
agentConfigs: this.runsService.getAllAgentConfigs(),
});

// 设置 Content-Location header
ctx.set('Content-Location', `/runs/${run.run_id}`);

// 类型断言帮助访问 input 中的 messages
const inputData = validated.input as { messages?: Array<{ role: string; content: string }> } | undefined;

// 使用 SSE 流式返回
return streamSSE(ctx, async stream => {
// 如果需要在断开连接时取消,创建 AbortSignal
// const cancelOnDisconnect = validated.on_disconnect === 'cancel'
// ? getDisconnectAbortSignal(ctx, stream)
// : undefined;

try {
// TODO: 调用 runs service 的 stream.join 方法获取运行结果
// for await (const { event, data } of runs().stream.join(
// runId,
// undefined,
// {
// cancelOnDisconnect,
// lastEventId: validated.stream_resumable ? "-1" : undefined,
// ignore404: true,
// },
// auth
// )) {
// await stream.writeSSE({ data: JSON.stringify(data), event });
// }

// Mock 实现:模拟 SSE 流式响应
// 1. 发送 metadata 事件
await stream.writeSSE({
event: 'metadata',
data: JSON.stringify({
run_id: run.run_id,
assistant_id: validated.assistant_id || 'mock_assistant',
}),
});

await stream.sleep(100);

// 2. 发送 values 事件 - 模拟开始处理
await stream.writeSSE({
event: 'values',
data: JSON.stringify({
messages: [
{
role: 'user',
content: inputData?.messages?.[0]?.content || 'Hello',
},
],
}),
});

await stream.sleep(500);

// 3. 发送 values 事件 - 模拟 AI 响应
await stream.writeSSE({
event: 'values',
data: JSON.stringify({
messages: [
{
role: 'user',
content: inputData?.messages?.[0]?.content || 'Hello',
},
{
role: 'assistant',
content: `Mock response to: ${inputData?.messages?.[0]?.content || 'Hello'}`,
},
],
}),
});

await stream.sleep(200);

// 4. 发送 end 事件
await stream.writeSSE({
event: 'end',
data: JSON.stringify({
run_id: run.run_id,
status: 'completed',
}),
});
} catch (error) {
console.error('Error streaming run:', error);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

建议使用 ctx.logger.error 代替 console.error 来记录错误。这样可以利用应用统一的日志配置,方便后续的日志收集和分析。

Suggested change
console.error('Error streaming run:', error);
ctx.logger.error('Error streaming run:', error);

throw error;
}
});
}

}
Loading
Loading