diff --git a/package/agents/teacherAgents/__tests__/agent.json b/package/agent/__tests__/agent.json similarity index 100% rename from package/agents/teacherAgents/__tests__/agent.json rename to package/agent/__tests__/agent.json diff --git a/package/agents/teacherAgents/__tests__/agent.test.ts b/package/agent/__tests__/agent.test.ts similarity index 100% rename from package/agents/teacherAgents/__tests__/agent.test.ts rename to package/agent/__tests__/agent.test.ts diff --git a/package/agents/teacherAgents/agent.ts b/package/agent/agent.ts similarity index 100% rename from package/agents/teacherAgents/agent.ts rename to package/agent/agent.ts diff --git a/package/agents/teacherAgents/agents.ts b/package/agent/agents.ts similarity index 100% rename from package/agents/teacherAgents/agents.ts rename to package/agent/agents.ts diff --git a/package/agents/teacherAgents/index.ts b/package/agent/index.ts similarity index 100% rename from package/agents/teacherAgents/index.ts rename to package/agent/index.ts diff --git a/package/agents/index.ts b/package/agents/index.ts deleted file mode 100644 index 05b6413..0000000 --- a/package/agents/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./teacherAgents"; diff --git a/package/motion/chain/__tests__/function.test.ts b/package/chain/__tests__/function.test.ts similarity index 100% rename from package/motion/chain/__tests__/function.test.ts rename to package/chain/__tests__/function.test.ts diff --git a/package/motion/chain/__tests__/sentiment.test.ts b/package/chain/__tests__/sentiment.test.ts similarity index 100% rename from package/motion/chain/__tests__/sentiment.test.ts rename to package/chain/__tests__/sentiment.test.ts diff --git a/package/motion/chain/chain.ts b/package/chain/chain.ts similarity index 100% rename from package/motion/chain/chain.ts rename to package/chain/chain.ts diff --git a/package/motion/chain/function.ts b/package/chain/function.ts similarity index 100% rename from package/motion/chain/function.ts rename to package/chain/function.ts diff --git a/package/motion/chain/index.ts b/package/chain/index.ts similarity index 100% rename from package/motion/chain/index.ts rename to package/chain/index.ts diff --git a/package/motion/chain/typechat.ts b/package/chain/typechat.ts similarity index 100% rename from package/motion/chain/typechat.ts rename to package/chain/typechat.ts diff --git a/package/motion/chain/validate.ts b/package/chain/validate.ts similarity index 100% rename from package/motion/chain/validate.ts rename to package/chain/validate.ts diff --git a/package/collaboration/batch/__tests__/batch.test.ts b/package/collaboration/batch/__tests__/batch.test.ts deleted file mode 100644 index ed30585..0000000 --- a/package/collaboration/batch/__tests__/batch.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { batchDecorator, BaseAgent } from "@idealeap/gwt"; -test("batchDecorator", async () => { - // 使用示例 - - const asyncMultiplyByTwo = async (x: number): Promise => { - return new Promise((resolve) => { - setTimeout(() => { - resolve(x * 2); - }, 100); - }); - }; - - const asyncAddThree = async (x: number): Promise => { - return new Promise((resolve) => { - setTimeout(() => { - resolve(x + 3); - }, 100); - }); - }; - - const batchedFunctions = batchDecorator([asyncMultiplyByTwo, asyncAddThree], { - onData: (x: number) => x + 1, - onResult: (x: number) => x * 10, - onProgress: (completed, total) => { - console.log(`Completed: ${completed}, Total: ${total}`); - }, - }); - - await (async () => { - const results = await batchedFunctions([1, 2, 3]); - console.log("Final Results:", results); - //jest test equal - expect(results).toEqual([40, 60, 80, 50, 60, 70]); - })(); -}); - -test("更简单的batchDecorator使用", async () => { - const fn = (x: string) => { - return `_-${x}-_`; - }; - const res = await batchDecorator(fn, { - onResult: (x: string) => { - return `*${x}*`; - }, - })(["a", "b", "c"]); - console.log(res); -}); - -test("onBatchResult", async () => { - const fn = (x: string) => { - return `_-${x}-_`; - }; - const res = await batchDecorator(fn, { - onBatchResult: (x: string[]) => { - return `*${JSON.stringify(x)}*`; - }, - })(["a", "b", "c"]); - console.log(res); - expect(res).toEqual(`*["_-a-_","_-b-_","_-c-_"]*`); -}); - -test("onBatchResult with Prompt", async () => { - const data = (await ( - await fetch("https://cos.idealeap.cn/Other/agent.json") - ).json()) as { agents: any[] }; - const fn = async (data: Record) => { - const agent = new BaseAgent(data.agents[0].params); - const res = await agent.call({ - request: `你好,非常欢迎你来到我身边~我是xxx,我会把最美好的一面呈现给你!`, - prompts: data.agents[0].params.prompts, - struct: data.agents[0].params.struct, - }); - if (!res.success) { - return res.message; - } else { - return res.data; - } - }; - const res = await batchDecorator(fn, {})(Array(3).fill(data)); - console.log(res); -}); diff --git a/package/collaboration/batch/batch.ts b/package/collaboration/batch/batch.ts deleted file mode 100644 index 0a8bdda..0000000 --- a/package/collaboration/batch/batch.ts +++ /dev/null @@ -1,71 +0,0 @@ -export type Awaited = T extends PromiseLike ? U : T; -// 批处理选项 -export interface BatchOptions { - onData?: (input: T) => T; - onBatchData?: (inputs: T[]) => T[] | T; - onResult?: (result: Awaited) => Awaited; - onBatchResult?: (results: Awaited[]) => Awaited[] | Awaited; - onProgress?: (completed: number, total: number) => void; - onError?: (error: any) => void; -} - -export function batchDecorator( - fn: ((input: T) => Promise | R) | ((input: T) => Promise | R)[], - options?: BatchOptions, -): (input: T | T[]) => Promise | Awaited[]> { - return async (input: T | T[]): Promise | Awaited[]> => { - const { onBatchData, onBatchResult } = options || {}; - const total = Array.isArray(input) ? input.length : 1; - const isMultipleFns = Array.isArray(fn); - const functions = isMultipleFns - ? (fn as ((input: T) => Promise | R)[]) - : [fn as (input: T) => Promise | R]; - - let inputs = Array.isArray(input) ? input : [input]; - - if (onBatchData) { - const processedBatch = onBatchData(inputs); - inputs = Array.isArray(processedBatch) - ? processedBatch - : Array(total).fill(processedBatch); - } - - let allResults: Awaited[] = []; - let completedCount = 0; - async function runSingle( - data: T, - f: (input: T) => Promise | R, - options: BatchOptions, - ): Promise | null> { - const { onData, onResult, onProgress, onError } = options; - try { - const processedData = onData ? onData(data) : data; - const result = await Promise.resolve(f(processedData)); - const finalResult = onResult ? onResult(result as Awaited) : result; // 类型断言 - onProgress?.(++completedCount, total * functions.length); - return finalResult as Awaited; // 类型断言 - } catch (error) { - onError?.(error); - return null; - } - } - - for (const singleFn of functions) { - const results: Promise | null>[] = []; - for (const data of inputs) { - results.push(runSingle(data, singleFn, options || {})); - } - const resultBatch = await Promise.all(results); - allResults = allResults.concat( - resultBatch.filter(Boolean) as Awaited[], - ); - } - - if (onBatchResult) { - const finalBatchResult = onBatchResult(allResults); - return finalBatchResult; - } - - return allResults; - }; -} diff --git a/package/collaboration/batch/index.ts b/package/collaboration/batch/index.ts deleted file mode 100644 index 1bd268c..0000000 --- a/package/collaboration/batch/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./batch"; diff --git a/package/collaboration/index.ts b/package/collaboration/index.ts deleted file mode 100644 index ce5ff8f..0000000 --- a/package/collaboration/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./batch"; -export * from "./pipe"; diff --git a/package/collaboration/pipe/__tests__/pipe.test.ts b/package/collaboration/pipe/__tests__/pipe.test.ts deleted file mode 100644 index 8d31bb7..0000000 --- a/package/collaboration/pipe/__tests__/pipe.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { - Pipe, - Pipeline, - SerializablePipelineOptions, - PipeRegistry, -} from "@idealeap/gwt"; // 请替换成你的模块导入方式 - -test("Pipe", async () => { - const pipe1 = new Pipe( - (input) => { - return input + 1; - }, - { - id: "pipe1", - }, - ); - - const pipe2 = new Pipe( - (input) => { - return input * 2; - }, - { - id: "pipe2", - }, - ); - - const pipeline = new Pipeline([pipe1], { - onProgress: (completed, total) => { - console.log(`Progress: ${completed}/${total}`); - }, - }); - - // 动态添加管道 - pipeline.addPipe(pipe2); - - // 执行管道 - await pipeline.execute(1).then((results) => { - console.log("Final results:", results); - }); -}); - -test("Pipeline with JSON", async () => { - // 示例 - const jsonConfig: SerializablePipelineOptions = { - pipes: [{ id: "step1" }, { id: "step2", timeout: 1000 }], - }; - - const fnMap = { - step1: (input: string) => `${input}-step1`, - step2: (input: string) => `${input}-step2`, - }; - - const pipeline = Pipeline.fromJSON(jsonConfig, fnMap); - - // 执行 Pipeline - await pipeline.execute("我饿").then(console.log); -}); - -test("Pipeline with 链式调用", async () => { - // 示例代码 - // 示例 - const pipeline = Pipeline.create() - .addPipe( - Pipe.create((input: number) => input + 1, { - id: "step1", - }).setDescription("Increment by 1"), - ) - .addPipe( - Pipe.create((input: number) => input * 2, { - id: "step2", - }).setDescription("Multiply by 2"), - ) - .setOnProgress((completed, total) => { - console.log(`Progress: ${completed}/${total}`); - }); - - // 执行 - await pipeline.execute(1).then((result) => { - console.log("Final result:", result); - }); - - // 序列化为 JSON - const jsonConfig = JSON.stringify(pipeline.toJSON()); - console.log("Serialized config:", jsonConfig); -}); - -test("pipeRegistry", async () => { - const pipeRegistry = PipeRegistry.init(); - // 注册预定义的 Pipe 类型 - pipeRegistry.register("FetchData", async () => { - // 这里用一个简单的 setTimeout 来模拟异步数据获取 - return new Promise((resolve) => - setTimeout(() => resolve("fetched data"), 1000), - ); - }); - - pipeRegistry.register("TransformData", () => { - // 这里只是简单地返回一个字符串,实际情况可能涉及到更复杂的数据转换 - // console.log(input, context); - return "transformed data"; - }); - - const pipelineJson = { - pipes: [ - { - id: "FetchData", - type: "FetchData", - }, - { - id: "TransformData", - type: "TransformData", - }, - ], - }; - - const pipeline = Pipeline.fromJSON(pipelineJson, {}, pipeRegistry); - await pipeline.execute(undefined).then((result) => { - console.log("Final result:", result); - }); - - // 序列化为 JSON - const jsonConfig = JSON.stringify(pipeline.toJSON()); - console.log("Serialized config:", jsonConfig); -}); diff --git a/package/collaboration/pipe/__tests__/utils.test.ts b/package/collaboration/pipe/__tests__/utils.test.ts deleted file mode 100644 index 4b48399..0000000 --- a/package/collaboration/pipe/__tests__/utils.test.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { PipeRegistry } from "@idealeap/gwt"; - -test("PipeRegistry", () => { - const pipeRegistry = PipeRegistry.init(); - console.log(pipeRegistry); - debugger; -}); diff --git a/package/collaboration/pipe/index.ts b/package/collaboration/pipe/index.ts deleted file mode 100644 index a1a3aaf..0000000 --- a/package/collaboration/pipe/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./pipe"; -export * from "./utils"; diff --git a/package/collaboration/pipe/pipe.ts b/package/collaboration/pipe/pipe.ts deleted file mode 100644 index 32b6c7a..0000000 --- a/package/collaboration/pipe/pipe.ts +++ /dev/null @@ -1,353 +0,0 @@ -// 本代码由GPT4生成,具体可见https://pandora.idealeap.cn/share/33072598-a95f-4188-9003-76ccc5d964cb -import { batchDecorator, BatchOptions, PipeRegistryType } from "@idealeap/gwt"; -// 类型和接口定义 -export type MaybePromise = T | Promise; - -// 简单的 EventEmitter 实现 -export class EventEmitter { - private events: Record void)[]> = {}; - - on(event: string, listener: (...args: any[]) => void) { - if (!this.events[event]) { - this.events[event] = []; - } - this.events[event].push(listener); - } - - emit(event: string, ...args: any[]) { - this.events[event]?.forEach((listener) => listener(...args)); - } -} - -export interface PipeOptions extends BatchOptions { - id: string; - description?: string; - dependencies?: string[]; - retries?: number; - timeout?: number; - preProcess?: (input: T, context: PipelineContext) => MaybePromise; - postProcess?: (result: R, context: PipelineContext) => MaybePromise; - errProcess?: (error: any, context: PipelineContext) => MaybePromise; - destroyProcess?: () => void; - batch?: boolean; - type?: string; -} - -export interface PipelineContext { - stepResults: Map; - emitter: EventEmitter; - abortController: AbortController; -} - -export interface PipelineOptions { - onProgress?: (completed: number, total: number) => void; - emitter?: EventEmitter; - destroyProcess?: () => void; - errProcess?: (error: any, context: PipelineContext) => MaybePromise; -} - -export type SerializablePipeOptions = Omit< - PipeOptions, - "preProcess" | "postProcess" | "errProcess" ->; - -export interface SerializablePipelineOptions - extends Omit { - pipes: SerializablePipeOptions[]; -} - -const maybeAwait = async (input: MaybePromise) => - await Promise.resolve(input); - -// 用于处理超时的函数 -const withTimeout = ( - promise: MaybePromise, - timeout: number, -): Promise => { - const timer = new Promise((_, reject) => { - setTimeout(() => reject(new Error("Timeout")), timeout); - }); - return Promise.race([promise, timer]); -}; - -// Pipe 类定义 -export class Pipe { - constructor( - private callback: (input: T, context: PipelineContext) => MaybePromise, - public options: PipeOptions, - ) {} - - private async handlePreProcess( - input: T, - context: PipelineContext, - ): Promise { - return this.options.preProcess - ? await maybeAwait(this.options.preProcess(input, context)) - : input; - } - - private async handlePostProcess( - result: R, - context: PipelineContext, - ): Promise { - return this.options.postProcess - ? await maybeAwait(this.options.postProcess(result, context)) - : result; - } - - async execute(input: T | T[], context: PipelineContext): Promise { - if (this.options.batch) { - const batchedFunction = batchDecorator( - (input: T) => this.handleExecution(input, context), - this.options, - ) as (input: T | T[]) => Promise; - return await batchedFunction(input); - } else { - if (Array.isArray(input)) { - throw new Error("Batch mode is not enabled for this pipe."); - } - return await this.handleExecution(input, context); - } - } - - private async handleExecution( - input: T, - context: PipelineContext, - ): Promise { - let retries = this.options.retries || 0; - while (true) { - try { - if (context.abortController.signal.aborted) { - throw new Error("Operation cancelled"); - } - - // 处理依赖项 - if (this.options.dependencies) { - for (const dep of this.options.dependencies) { - if (!context.stepResults.has(dep)) { - throw new Error(`Dependency ${dep} not found`); - } - } - } - - let promise = this.callback( - await this.handlePreProcess(input, context), - context, - ); - if (this.options.timeout) { - promise = withTimeout(promise, this.options.timeout); - } - - const result = await maybeAwait(promise); - const postProcessedResult = await this.handlePostProcess( - result, - context, - ); - - context.stepResults.set(this.options.id, postProcessedResult); - - return postProcessedResult; - } catch (error) { - retries--; - if (this.options.errProcess) { - const skip = await maybeAwait( - this.options.errProcess(error, context), - ); - if (skip) return input as unknown as R; - } - if (retries < 0) { - throw error; - } - } - } - } - - // 从一个 SerializablePipeOptions 对象创建一个 Pipe 实例 - static fromJSON( - json: SerializablePipeOptions, - callback: (input: T, context: PipelineContext) => MaybePromise, - predefinedTypes?: PipeRegistryType, - ): Pipe { - if (json.type && predefinedTypes) { - const predefinedCallback = predefinedTypes.get(json.type); - if (predefinedCallback) { - return new Pipe(predefinedCallback, json as PipeOptions); - } - } - - if (!json.id) { - throw new Error("JSON configuration for Pipe must contain an 'id' field"); - } - - return new Pipe(callback, json as PipeOptions); - } - - // 新增一个 static 方法用于创建新实例,并支持链式调用 - static create( - callback: (input: T, context: PipelineContext) => MaybePromise, - options?: Partial>, - ): Pipe { - return new Pipe(callback, options as PipeOptions); - } - - setId(id: string): this { - this.options.id = id; - return this; - } - - setDescription(description: string): this { - this.options.description = description; - return this; - } - - setDependencies(deps: string[]): this { - this.options.dependencies = deps; - return this; - } - - enableBatching(): this { - this.options.batch = true; - return this; - } - - setRetries(retries: number): this { - this.options.retries = retries; - return this; - } - - // 添加一个动态依赖检查函数,返回一个布尔值以确定是否应执行该 Pipe - // eslint-disable-next-line @typescript-eslint/no-unused-vars - shouldExecute(context: PipelineContext): boolean { - // 自定义逻辑,例如: - // return context.stepResults.get('someDependency') !== 'someValue'; - return true; - } -} - -// 主函数 -export class Pipeline { - private pipes: Pipe[] = []; - private options: PipelineOptions; - - constructor(pipes: Pipe[], options: PipelineOptions = {}) { - this.pipes = pipes; - this.options = options; - } - - // 预处理步骤,用于在实际执行前验证所有依赖关系 - verifyDependencies(): boolean { - const existingPipeIds = new Set(this.pipes.map((pipe) => pipe.options.id)); - for (const pipe of this.pipes) { - if (pipe.options.dependencies) { - for (const dep of pipe.options.dependencies) { - if (!existingPipeIds.has(dep)) { - throw new Error( - `Dependency ${dep} for pipe ${pipe.options.id} not found.`, - ); - } - } - } - } - return true; - } - - // 删除 Pipe - removePipe(id: string): this { - this.pipes = this.pipes.filter((pipe) => pipe.options.id !== id); - return this; - } - - async execute(input: any): Promise | Map[]> { - this.verifyDependencies(); // 在执行前验证依赖关系 - const emitter = this.options.emitter || new EventEmitter(); - const abortController = new AbortController(); - const context: PipelineContext = { - stepResults: new Map(), - emitter, - abortController, - }; - - let lastOutput: any = input; - - try { - for (let i = 0; i < this.pipes.length; i++) { - const pipe = this.pipes[i]; - - if (!pipe.shouldExecute(context)) { - continue; - } - - lastOutput = await pipe.execute(lastOutput, context); - emitter.emit("stepComplete", i + 1, this.pipes.length, lastOutput); - this.options.onProgress?.(i + 1, this.pipes.length); - } - } finally { - this.pipes.forEach((pipe) => pipe.options.destroyProcess?.()); - this.options.destroyProcess?.(); - } - - return context.stepResults; - } - // 从一个 SerializablePipelineOptions 和函数映射创建一个 Pipeline - static fromJSON( - json: SerializablePipelineOptions, - fnMap: Record< - string, - (input: any, context: PipelineContext) => MaybePromise - >, - predefinedTypes?: PipeRegistryType, - ): Pipeline { - if (!Array.isArray(json.pipes)) { - throw new Error("Invalid JSON configuration: 'pipes' must be an array"); - } - - const pipes = json.pipes.map((pipeJson: SerializablePipeOptions) => { - const fn = - fnMap[pipeJson.id] || - (predefinedTypes && pipeJson.type - ? predefinedTypes.get(pipeJson.type) - : undefined); - if (!fn) { - throw new Error(`Function not found for id: ${pipeJson.id}`); - } - return Pipe.fromJSON(pipeJson, fn, predefinedTypes); - }); - - return new Pipeline(pipes, json); - } - - // 新增一个 static 方法用于创建新实例,并支持链式调用 - static create(options?: PipelineOptions): Pipeline { - return new Pipeline([], options); - } - - // 添加 Pipe 并返回 this,以支持链式调用 - addPipe(pipe: Pipe): this { - this.pipes.push(pipe); - return this; - } - - // 设置进度回调并返回 this,以支持链式调用 - setOnProgress(callback: (completed: number, total: number) => void): this { - this.options.onProgress = callback; - return this; - } - - // 序列化为 JSON 的方法 - toJSON(): SerializablePipelineOptions { - return { - pipes: this.pipes.map((pipe) => ({ - id: pipe.options.id, - description: pipe.options.description, - dependencies: pipe.options.dependencies, - retries: pipe.options.retries, - timeout: pipe.options.timeout, - batch: pipe.options.batch, - })), - }; - } -} - -// 请进一步完善上述代码的功能,例如 - -// 请给出完整的Ts代码和示例,没有变化的代码可以省略,但是不要函数中间省略。 diff --git a/package/collaboration/pipe/utils.ts b/package/collaboration/pipe/utils.ts deleted file mode 100644 index 7eb5659..0000000 --- a/package/collaboration/pipe/utils.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { MaybePromise, PipelineContext } from "@idealeap/gwt"; - -export type PipeRegistryType = PipeRegistry; - -export type Registry = Record< - string, - (input: any, context: PipelineContext) => MaybePromise ->; - -export class PipeRegistry { - private registry: Registry = {}; - - register( - type: string, - callback: (input: any, context: PipelineContext) => MaybePromise, - ) { - this.registry[type] = callback; - } - - get(type: string) { - return this.registry[type]; - } - - static commonPreProcess = { - validateData: (input: any, context: PipelineContext) => { - // 数据验证逻辑 - console.log("validateData", input, context); - return input; - }, - }; - - static commonPostProcess = { - logData: (result: any, context: PipelineContext) => { - console.log(result, context); - return result; - }, - }; - static init() { - const pipeRegistry = new PipeRegistry(); - //遍历commonPreProcess进行pipeRegistry.register注册 - Object.entries(PipeRegistry.commonPreProcess).forEach(([type, fn]) => { - pipeRegistry.register(type, fn); - }); - //遍历commonPostProcess进行pipeRegistry.register注册 - Object.entries(PipeRegistry.commonPostProcess).forEach(([type, fn]) => { - pipeRegistry.register(type, fn); - }); - return pipeRegistry; - } -} diff --git a/package/competition/index.ts b/package/competition/index.ts deleted file mode 100644 index 87a2c18..0000000 --- a/package/competition/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface competitionSchema { - bound?: boolean; - verbose?: boolean; -} diff --git a/package/memory/__tests__/milvus.test.ts b/package/db/__tests__/milvus.test.ts similarity index 100% rename from package/memory/__tests__/milvus.test.ts rename to package/db/__tests__/milvus.test.ts diff --git a/package/memory/index.ts b/package/db/index.ts similarity index 100% rename from package/memory/index.ts rename to package/db/index.ts diff --git a/package/memory/milvus.ts b/package/db/milvus.ts similarity index 100% rename from package/memory/milvus.ts rename to package/db/milvus.ts diff --git a/package/evaluation/index.ts b/package/evaluation/index.ts deleted file mode 100644 index a38c11a..0000000 --- a/package/evaluation/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface evaluationSchema { - bound?: boolean; - verbose?: boolean; -} diff --git a/package/index.ts b/package/index.ts index 4056395..3cbcf52 100644 --- a/package/index.ts +++ b/package/index.ts @@ -1,9 +1,6 @@ -export * from "./motion"; -export * from "./attention"; +export * from "./agent"; +export * from "./chain"; +export * from "./db"; +export * from "./llm"; +export * from "./prompt"; export * from "./utils"; -export * from "./agents"; -export * from "./collaboration"; -export * from "./competition"; -export * from "./evaluation"; -export * from "./memory"; -export * from "./perceptual"; diff --git a/package/utils/openai/__tests__/embedding.test.ts b/package/llm/__tests__/embedding.test.ts similarity index 100% rename from package/utils/openai/__tests__/embedding.test.ts rename to package/llm/__tests__/embedding.test.ts diff --git a/package/utils/openai/__tests__/index.test.ts b/package/llm/__tests__/index.test.ts similarity index 100% rename from package/utils/openai/__tests__/index.test.ts rename to package/llm/__tests__/index.test.ts diff --git a/package/utils/openai/index.ts b/package/llm/index.ts similarity index 100% rename from package/utils/openai/index.ts rename to package/llm/index.ts diff --git a/package/motion/executor/__tests__/executor.test.ts b/package/motion/executor/__tests__/executor.test.ts deleted file mode 100644 index 0d89baa..0000000 --- a/package/motion/executor/__tests__/executor.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { DynamicExecutor, batchDecorator } from "@idealeap/gwt"; - -test("DynamicExecutor", async () => { - // 使用示例 - const executor = new DynamicExecutor({ - logging: true, - timeout: 5000, - environment: { customVar: "Hello, world!" }, - // allowedBuiltins: ["fetch"], - }); - - await (async () => { - const result = await executor.execute( - ` - if (fetch) { - try { - const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); - const data = await response.json(); - return data.id; - } catch (e) { - return 'Fetch failed'; - } - } else { - return customVar.length + args[0] + args[1]; - } - `, - 1, - 2, - ); - expect(result).toEqual(16); - console.log(result); - })(); -}); - -test("DynamicExecutor with batchDecorator", async () => { - const fn = async (x: number) => { - const executor = new DynamicExecutor({ - logging: true, - timeout: 5000, - environment: { customVar: "Hello, world!" }, - allowedBuiltins: ["fetch"], - }); - - return await executor.execute( - ` - if (fetch) { - try { - const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); - const data = await response.json(); - return data.id; - } catch (e) { - return 'Fetch failed'; - } - } else { - return customVar.length + args[0]; - } - `, - x, - ); - }; - const res = await batchDecorator(fn)([1, 2, 3]); - console.log(res); - expect(res).toEqual([1, 1, 1]); -}); diff --git a/package/motion/executor/executor.ts b/package/motion/executor/executor.ts deleted file mode 100644 index 72ab967..0000000 --- a/package/motion/executor/executor.ts +++ /dev/null @@ -1,91 +0,0 @@ -// 本代码由GPT4生成,具体可见https://pandora.idealeap.cn/share/07ee53fc-e074-46f6-b808-b4f159bb3468 - -export interface ExecutorConfig { - timeout?: number; - logging?: boolean; - environment?: Record; - allowedBuiltins?: string[]; - beforeExecute?: (code: string) => void; - afterExecute?: (result: any, code: string, error?: Error) => void; - validateCode?: (code: string) => boolean; -} - -export class DynamicExecutor { - private config: ExecutorConfig; - - constructor(config?: ExecutorConfig) { - this.config = config || {}; - } - - private log(message: string) { - if (this.config.logging) { - console.log(`[DynamicExecutor]: ${message}`); - } - } - - public async execute( - code: string, - ...args: any[] - ): Promise { - let result: T | null = null; - let executionError: Error | undefined = undefined; - - if ( - typeof code !== "string" || - (this.config.validateCode && !this.config.validateCode(code)) - ) { - throw new Error("Invalid or unsafe code"); - } - - // Call the beforeExecute hook if provided - this.config.beforeExecute?.(code); - - this.log(`Executing code: ${code}`); - - try { - const sandbox: Record = { - fetch: this.config.allowedBuiltins?.includes("fetch") - ? fetch - : undefined, - ...this.config.environment, - }; - sandbox.args = args; - - const envKeys = Object.keys(sandbox).join(","); - const envValues = Object.values(sandbox); - - // eslint-disable-next-line @typescript-eslint/no-implied-eval - const func = new Function( - envKeys, - ` - "use strict"; - return (async () => { - ${code}; - })(); - `, - ).bind(null, ...envValues); - - if (this.config.timeout) { - const promise = func(); - result = (await Promise.race([ - promise, - new Promise((_, reject) => - setTimeout(() => reject(new Error("Timeout")), this.config.timeout), - ), - ])) as T; - } else { - result = (await func()) as T; - } - } catch (error: unknown) { - executionError = error as Error; - this.log(`Error occurred: ${String(executionError)}`); - result = null; - } - - // Call the afterExecute hook if provided - this.config.afterExecute?.(result, code, executionError); - - this.log(`Execution result: ${String(result)}`); - return result; - } -} diff --git a/package/motion/executor/index.ts b/package/motion/executor/index.ts deleted file mode 100644 index 8ed01fa..0000000 --- a/package/motion/executor/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./executor"; diff --git a/package/motion/index.ts b/package/motion/index.ts deleted file mode 100644 index b5b15c9..0000000 --- a/package/motion/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./chain"; -export * from "./executor"; diff --git a/package/perceptual/index.ts b/package/perceptual/index.ts deleted file mode 100644 index f3995c5..0000000 --- a/package/perceptual/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface perceptualSchema { - bound?: boolean; - verbose?: boolean; -} diff --git a/package/attention/__tests__/agentPromptTemplate.test.ts b/package/prompt/__tests__/agentPromptTemplate.test.ts similarity index 100% rename from package/attention/__tests__/agentPromptTemplate.test.ts rename to package/prompt/__tests__/agentPromptTemplate.test.ts diff --git a/package/attention/__tests__/basePromptTemplate.test.ts b/package/prompt/__tests__/basePromptTemplate.test.ts similarity index 100% rename from package/attention/__tests__/basePromptTemplate.test.ts rename to package/prompt/__tests__/basePromptTemplate.test.ts diff --git a/package/attention/__tests__/polishPromptTemplate.test.ts b/package/prompt/__tests__/polishPromptTemplate.test.ts similarity index 100% rename from package/attention/__tests__/polishPromptTemplate.test.ts rename to package/prompt/__tests__/polishPromptTemplate.test.ts diff --git a/package/attention/__tests__/promptTemplate.test.ts b/package/prompt/__tests__/promptTemplate.test.ts similarity index 100% rename from package/attention/__tests__/promptTemplate.test.ts rename to package/prompt/__tests__/promptTemplate.test.ts diff --git a/package/attention/agentPromptTemplate.ts b/package/prompt/agentPromptTemplate.ts similarity index 98% rename from package/attention/agentPromptTemplate.ts rename to package/prompt/agentPromptTemplate.ts index 756363d..bac2fd9 100644 --- a/package/attention/agentPromptTemplate.ts +++ b/package/prompt/agentPromptTemplate.ts @@ -1,5 +1,4 @@ -import { messagesType } from "../utils/index.js"; -import { createMessage, BasePromptTemplate } from "./basePromptTemplate.js"; +import { messagesType, createMessage, BasePromptTemplate } from "@idealeap/gwt"; export type InputValues = Record; export type toneStyleType = diff --git a/package/attention/basePromptTemplate.ts b/package/prompt/basePromptTemplate.ts similarity index 100% rename from package/attention/basePromptTemplate.ts rename to package/prompt/basePromptTemplate.ts diff --git a/package/attention/index.ts b/package/prompt/index.ts similarity index 100% rename from package/attention/index.ts rename to package/prompt/index.ts diff --git a/package/attention/polishPromptTemplate.ts b/package/prompt/polishPromptTemplate.ts similarity index 94% rename from package/attention/polishPromptTemplate.ts rename to package/prompt/polishPromptTemplate.ts index c3fa6c2..4906d47 100644 --- a/package/attention/polishPromptTemplate.ts +++ b/package/prompt/polishPromptTemplate.ts @@ -1,5 +1,4 @@ -import { createMessage, BasePromptTemplate } from "./basePromptTemplate.js"; -import { messagesType } from "../utils/index.js"; +import { createMessage, BasePromptTemplate, messagesType } from "@idealeap/gwt"; type languageType = "English" | "Chinese"; export interface polishPromptTemplateSchema { toneStyle?: string; diff --git a/package/attention/promptTemplate.ts b/package/prompt/promptTemplate.ts similarity index 100% rename from package/attention/promptTemplate.ts rename to package/prompt/promptTemplate.ts diff --git a/package/utils/index.ts b/package/utils/index.ts index 60fbac8..fbef262 100644 --- a/package/utils/index.ts +++ b/package/utils/index.ts @@ -1,3 +1,2 @@ -export * from "./openai/index.js"; export * from "./config.js"; export * from "./result.js";