@librechat/agents 2.4.49 → 2.4.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +11 -7
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/run.cjs +4 -3
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +1 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +11 -7
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/run.mjs +4 -3
- package/dist/esm/run.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +1 -1
- package/dist/types/llm/google/utils/common.d.ts +2 -2
- package/dist/types/types/graph.d.ts +8 -5
- package/dist/types/types/tools.d.ts +1 -1
- package/package.json +1 -1
- package/src/graphs/Graph.ts +2 -2
- package/src/llm/google/index.ts +1 -1
- package/src/llm/google/utils/common.ts +26 -18
- package/src/run.ts +7 -4
- package/src/types/graph.ts +119 -89
- package/src/types/tools.ts +16 -10
package/dist/esm/run.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
2
2
|
import { PromptTemplate } from '@langchain/core/prompts';
|
|
3
|
-
import { ChatOpenAI as ChatOpenAI$1, AzureChatOpenAI as AzureChatOpenAI$1 } from '@langchain/openai';
|
|
4
3
|
import { SystemMessage } from '@langchain/core/messages';
|
|
4
|
+
import { ChatOpenAI as ChatOpenAI$1, AzureChatOpenAI as AzureChatOpenAI$1 } from '@langchain/openai';
|
|
5
5
|
import { GraphEvents, Callback } from './common/enum.mjs';
|
|
6
6
|
import { manualToolStreamProviders } from './llm/providers.mjs';
|
|
7
7
|
import { shiftIndexTokenCountMap } from './messages/format.mjs';
|
|
@@ -102,12 +102,13 @@ class Run {
|
|
|
102
102
|
(streamOptions?.indexTokenCountMap
|
|
103
103
|
? await createTokenCounter()
|
|
104
104
|
: undefined);
|
|
105
|
+
const tools = this.Graph.tools;
|
|
105
106
|
const toolTokens = tokenCounter
|
|
106
|
-
? (
|
|
107
|
+
? (tools?.reduce((acc, tool) => {
|
|
107
108
|
if (!tool.schema) {
|
|
108
109
|
return acc;
|
|
109
110
|
}
|
|
110
|
-
const jsonSchema = zodToJsonSchema(tool
|
|
111
|
+
const jsonSchema = zodToJsonSchema((tool?.schema).describe(tool?.description ?? ''), tool?.name ?? '');
|
|
111
112
|
return (acc + tokenCounter(new SystemMessage(JSON.stringify(jsonSchema))));
|
|
112
113
|
}, 0) ?? 0)
|
|
113
114
|
: 0;
|
package/dist/esm/run.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.mjs","sources":["../../src/run.ts"],"sourcesContent":["// src/run.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';\nimport { SystemMessage } from '@langchain/core/messages';\nimport type {\n BaseMessage,\n MessageContentComplex,\n} from '@langchain/core/messages';\nimport type { ClientCallbacks, SystemCallbacks } from '@/graphs/Graph';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport { GraphEvents, Providers, Callback } from '@/common';\nimport { manualToolStreamProviders } from '@/llm/providers';\nimport { shiftIndexTokenCountMap } from '@/messages/format';\nimport { createTitleRunnable } from '@/utils/title';\nimport { createTokenCounter } from '@/utils/tokens';\nimport { StandardGraph } from '@/graphs/Graph';\nimport { HandlerRegistry } from '@/events';\nimport { isOpenAILike } from '@/utils/llm';\n\nexport const defaultOmitOptions = new Set([\n 'stream',\n 'thinking',\n 'streaming',\n 'maxTokens',\n 'clientOptions',\n 'thinkingConfig',\n 'thinkingBudget',\n 'includeThoughts',\n 'maxOutputTokens',\n 'additionalModelRequestFields',\n]);\n\nexport class Run<T extends t.BaseGraphState> {\n graphRunnable?: t.CompiledWorkflow<T, Partial<T>, string>;\n // private collab!: CollabGraph;\n // private taskManager!: TaskManager;\n private handlerRegistry: HandlerRegistry;\n id: string;\n Graph: StandardGraph | undefined;\n provider: Providers | undefined;\n returnContent: boolean = false;\n\n private constructor(config: Partial<t.RunConfig>) {\n const runId = config.runId ?? '';\n if (!runId) {\n throw new Error('Run ID not provided');\n }\n\n this.id = runId;\n\n const handlerRegistry = new HandlerRegistry();\n\n if (config.customHandlers) {\n for (const [eventType, handler] of Object.entries(\n config.customHandlers\n )) {\n handlerRegistry.register(eventType, handler);\n }\n }\n\n this.handlerRegistry = handlerRegistry;\n\n if (!config.graphConfig) {\n throw new Error('Graph config not provided');\n }\n\n if (config.graphConfig.type === 'standard' || !config.graphConfig.type) {\n this.provider = config.graphConfig.llmConfig.provider;\n this.graphRunnable = this.createStandardGraph(\n config.graphConfig\n ) as unknown as t.CompiledWorkflow<T, Partial<T>, string>;\n if (this.Graph) {\n this.Graph.handlerRegistry = handlerRegistry;\n }\n }\n\n this.returnContent = config.returnContent ?? false;\n }\n\n private createStandardGraph(\n config: t.StandardGraphConfig\n ): t.CompiledWorkflow<t.IState, Partial<t.IState>, string> {\n const { llmConfig, tools = [], ...graphInput } = config;\n const { provider, ...clientOptions } = llmConfig;\n\n const standardGraph = new StandardGraph({\n tools,\n provider,\n clientOptions,\n ...graphInput,\n runId: this.id,\n });\n this.Graph = standardGraph;\n return standardGraph.createWorkflow();\n }\n\n static async create<T extends t.BaseGraphState>(\n config: t.RunConfig\n ): Promise<Run<T>> {\n return new Run<T>(config);\n }\n\n getRunMessages(): BaseMessage[] | undefined {\n if (!this.Graph) {\n throw new Error(\n 'Graph not initialized. Make sure to use Run.create() to instantiate the Run.'\n );\n }\n return this.Graph.getRunMessages();\n }\n\n async processStream(\n inputs: t.IState,\n config: Partial<RunnableConfig> & { version: 'v1' | 'v2'; run_id?: string },\n streamOptions?: t.EventStreamOptions\n ): Promise<MessageContentComplex[] | undefined> {\n if (!this.graphRunnable) {\n throw new Error(\n 'Run not initialized. Make sure to use Run.create() to instantiate the Run.'\n );\n }\n if (!this.Graph) {\n throw new Error(\n 'Graph not initialized. Make sure to use Run.create() to instantiate the Run.'\n );\n }\n\n this.Graph.resetValues(streamOptions?.keepContent);\n const provider = this.Graph.provider;\n const hasTools = this.Graph.tools ? this.Graph.tools.length > 0 : false;\n if (streamOptions?.callbacks) {\n /* TODO: conflicts with callback manager */\n const callbacks = (config.callbacks as t.ProvidedCallbacks) ?? [];\n config.callbacks = callbacks.concat(\n this.getCallbacks(streamOptions.callbacks)\n );\n }\n\n if (!this.id) {\n throw new Error('Run ID not provided');\n }\n\n const tokenCounter =\n streamOptions?.tokenCounter ??\n (streamOptions?.indexTokenCountMap\n ? await createTokenCounter()\n : undefined);\n const toolTokens = tokenCounter\n ? (this.Graph.tools?.reduce((acc, tool) => {\n if (!(tool as Partial<t.GenericTool>).schema) {\n return acc;\n }\n\n const jsonSchema = zodToJsonSchema(\n (tool.schema as t.ZodObjectAny).describe(tool.description ?? ''),\n tool.name\n );\n return (\n acc + tokenCounter(new SystemMessage(JSON.stringify(jsonSchema)))\n );\n }, 0) ?? 0)\n : 0;\n let instructionTokens = toolTokens;\n if (this.Graph.systemMessage && tokenCounter) {\n instructionTokens += tokenCounter(this.Graph.systemMessage);\n }\n const tokenMap = streamOptions?.indexTokenCountMap ?? {};\n if (this.Graph.systemMessage && instructionTokens > 0) {\n this.Graph.indexTokenCountMap = shiftIndexTokenCountMap(\n tokenMap,\n instructionTokens\n );\n } else if (instructionTokens > 0) {\n tokenMap[0] = tokenMap[0] + instructionTokens;\n this.Graph.indexTokenCountMap = tokenMap;\n } else {\n this.Graph.indexTokenCountMap = tokenMap;\n }\n\n this.Graph.maxContextTokens = streamOptions?.maxContextTokens;\n this.Graph.tokenCounter = tokenCounter;\n\n config.run_id = this.id;\n config.configurable = Object.assign(config.configurable ?? {}, {\n run_id: this.id,\n provider: this.provider,\n });\n\n const stream = this.graphRunnable.streamEvents(inputs, config);\n\n for await (const event of stream) {\n const { data, name, metadata, ...info } = event;\n\n let eventName: t.EventName = info.event;\n if (\n hasTools &&\n manualToolStreamProviders.has(provider) &&\n eventName === GraphEvents.CHAT_MODEL_STREAM\n ) {\n /* Skipping CHAT_MODEL_STREAM event due to double-call edge case */\n continue;\n }\n\n if (eventName && eventName === GraphEvents.ON_CUSTOM_EVENT) {\n eventName = name;\n }\n\n const handler = this.handlerRegistry.getHandler(eventName);\n if (handler) {\n handler.handle(eventName, data, metadata, this.Graph);\n }\n }\n\n if (this.returnContent) {\n return this.Graph.getContentParts();\n }\n }\n\n private createSystemCallback<K extends keyof ClientCallbacks>(\n clientCallbacks: ClientCallbacks,\n key: K\n ): SystemCallbacks[K] {\n return ((...args: unknown[]) => {\n const clientCallback = clientCallbacks[key];\n if (clientCallback && this.Graph) {\n (clientCallback as (...args: unknown[]) => void)(this.Graph, ...args);\n }\n }) as SystemCallbacks[K];\n }\n\n getCallbacks(clientCallbacks: ClientCallbacks): SystemCallbacks {\n return {\n [Callback.TOOL_ERROR]: this.createSystemCallback(\n clientCallbacks,\n Callback.TOOL_ERROR\n ),\n [Callback.TOOL_START]: this.createSystemCallback(\n clientCallbacks,\n Callback.TOOL_START\n ),\n [Callback.TOOL_END]: this.createSystemCallback(\n clientCallbacks,\n Callback.TOOL_END\n ),\n };\n }\n\n async generateTitle({\n provider,\n inputText,\n contentParts,\n titlePrompt,\n clientOptions,\n chainOptions,\n skipLanguage,\n omitOptions = defaultOmitOptions,\n }: t.RunTitleOptions): Promise<{ language: string; title: string }> {\n const convoTemplate = PromptTemplate.fromTemplate(\n 'User: {input}\\nAI: {output}'\n );\n const response = contentParts\n .map((part) => {\n if (part?.type === 'text') return part.text;\n return '';\n })\n .join('\\n');\n const convo = (\n await convoTemplate.invoke({ input: inputText, output: response })\n ).value;\n const model = this.Graph?.getNewModel({\n provider,\n omitOptions,\n clientOptions,\n });\n if (!model) {\n return { language: '', title: '' };\n }\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions | undefined)\n ?.temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions | undefined)\n ?.topP as number;\n model.frequencyPenalty = (\n clientOptions as t.OpenAIClientOptions | undefined\n )?.frequencyPenalty as number;\n model.presencePenalty = (\n clientOptions as t.OpenAIClientOptions | undefined\n )?.presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions | undefined)\n ?.n as number;\n }\n const chain = await createTitleRunnable(model, titlePrompt);\n return (await chain.invoke(\n { convo, inputText, skipLanguage },\n chainOptions\n )) as { language: string; title: string };\n }\n}\n"],"names":["ChatOpenAI","AzureChatOpenAI"],"mappings":";;;;;;;;;;;;;AAAA;AAqBa,MAAA,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACxC,QAAQ;IACR,UAAU;IACV,WAAW;IACX,WAAW;IACX,eAAe;IACf,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,8BAA8B;AAC/B,CAAA;MAEY,GAAG,CAAA;AACd,IAAA,aAAa;;;AAGL,IAAA,eAAe;AACvB,IAAA,EAAE;AACF,IAAA,KAAK;AACL,IAAA,QAAQ;IACR,aAAa,GAAY,KAAK;AAE9B,IAAA,WAAA,CAAoB,MAA4B,EAAA;AAC9C,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE;QAChC,IAAI,CAAC,KAAK,EAAE;AACV,YAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC;;AAGxC,QAAA,IAAI,CAAC,EAAE,GAAG,KAAK;AAEf,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE;AAE7C,QAAA,IAAI,M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QAEpC,IACE,YAAY,CAAC,QAAQ,CAAC;aACrB,KAAK,YAAYA,YAAU,IAAI,KAAK,YAAYC,iBAAe,CAAC,EACjE;YACA,KAAK,CAAC,WAAW,GAAI;AACnB,kBAAE,WAAqB;YACzB,KAAK,CAAC,IAAI,GAAI;AACZ,kBAAE,IAAc;AAClB,YAAA,KAAK,CAAC,gBAAgB,GACpB,aACD,EAAE,gBAA0B;AAC7B,YAAA,KAAK,CAAC,eAAe,GACnB,aACD,EAAE,eAAyB;YAC5B,KAAK,CAAC,CAAC,GAAI;AACT,kBAAE,CAAW;;QAEjB,MAAM,KAAK,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3D,QAAA,QAAQ,MAAM,KAAK,CAAC,MAAM,CACxB,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAClC,YAAY,CACb;;AAEJ;;;;"}
|
|
1
|
+
{"version":3,"file":"run.mjs","sources":["../../src/run.ts"],"sourcesContent":["// src/run.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';\nimport type {\n BaseMessage,\n MessageContentComplex,\n} from '@langchain/core/messages';\nimport type { ClientCallbacks, SystemCallbacks } from '@/graphs/Graph';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport { GraphEvents, Providers, Callback } from '@/common';\nimport { manualToolStreamProviders } from '@/llm/providers';\nimport { shiftIndexTokenCountMap } from '@/messages/format';\nimport { createTitleRunnable } from '@/utils/title';\nimport { createTokenCounter } from '@/utils/tokens';\nimport { StandardGraph } from '@/graphs/Graph';\nimport { HandlerRegistry } from '@/events';\nimport { isOpenAILike } from '@/utils/llm';\n\nexport const defaultOmitOptions = new Set([\n 'stream',\n 'thinking',\n 'streaming',\n 'maxTokens',\n 'clientOptions',\n 'thinkingConfig',\n 'thinkingBudget',\n 'includeThoughts',\n 'maxOutputTokens',\n 'additionalModelRequestFields',\n]);\n\nexport class Run<T extends t.BaseGraphState> {\n graphRunnable?: t.CompiledWorkflow<T, Partial<T>, string>;\n // private collab!: CollabGraph;\n // private taskManager!: TaskManager;\n private handlerRegistry: HandlerRegistry;\n id: string;\n Graph: StandardGraph | undefined;\n provider: Providers | undefined;\n returnContent: boolean = false;\n\n private constructor(config: Partial<t.RunConfig>) {\n const runId = config.runId ?? '';\n if (!runId) {\n throw new Error('Run ID not provided');\n }\n\n this.id = runId;\n\n const handlerRegistry = new HandlerRegistry();\n\n if (config.customHandlers) {\n for (const [eventType, handler] of Object.entries(\n config.customHandlers\n )) {\n handlerRegistry.register(eventType, handler);\n }\n }\n\n this.handlerRegistry = handlerRegistry;\n\n if (!config.graphConfig) {\n throw new Error('Graph config not provided');\n }\n\n if (config.graphConfig.type === 'standard' || !config.graphConfig.type) {\n this.provider = config.graphConfig.llmConfig.provider;\n this.graphRunnable = this.createStandardGraph(\n config.graphConfig\n ) as unknown as t.CompiledWorkflow<T, Partial<T>, string>;\n if (this.Graph) {\n this.Graph.handlerRegistry = handlerRegistry;\n }\n }\n\n this.returnContent = config.returnContent ?? false;\n }\n\n private createStandardGraph(\n config: t.StandardGraphConfig\n ): t.CompiledWorkflow<t.IState, Partial<t.IState>, string> {\n const { llmConfig, tools = [], ...graphInput } = config;\n const { provider, ...clientOptions } = llmConfig;\n\n const standardGraph = new StandardGraph({\n tools,\n provider,\n clientOptions,\n ...graphInput,\n runId: this.id,\n });\n this.Graph = standardGraph;\n return standardGraph.createWorkflow();\n }\n\n static async create<T extends t.BaseGraphState>(\n config: t.RunConfig\n ): Promise<Run<T>> {\n return new Run<T>(config);\n }\n\n getRunMessages(): BaseMessage[] | undefined {\n if (!this.Graph) {\n throw new Error(\n 'Graph not initialized. Make sure to use Run.create() to instantiate the Run.'\n );\n }\n return this.Graph.getRunMessages();\n }\n\n async processStream(\n inputs: t.IState,\n config: Partial<RunnableConfig> & { version: 'v1' | 'v2'; run_id?: string },\n streamOptions?: t.EventStreamOptions\n ): Promise<MessageContentComplex[] | undefined> {\n if (!this.graphRunnable) {\n throw new Error(\n 'Run not initialized. Make sure to use Run.create() to instantiate the Run.'\n );\n }\n if (!this.Graph) {\n throw new Error(\n 'Graph not initialized. Make sure to use Run.create() to instantiate the Run.'\n );\n }\n\n this.Graph.resetValues(streamOptions?.keepContent);\n const provider = this.Graph.provider;\n const hasTools = this.Graph.tools ? this.Graph.tools.length > 0 : false;\n if (streamOptions?.callbacks) {\n /* TODO: conflicts with callback manager */\n const callbacks = (config.callbacks as t.ProvidedCallbacks) ?? [];\n config.callbacks = callbacks.concat(\n this.getCallbacks(streamOptions.callbacks)\n );\n }\n\n if (!this.id) {\n throw new Error('Run ID not provided');\n }\n\n const tokenCounter =\n streamOptions?.tokenCounter ??\n (streamOptions?.indexTokenCountMap\n ? await createTokenCounter()\n : undefined);\n const tools = this.Graph.tools as\n | Array<t.GenericTool | undefined>\n | undefined;\n const toolTokens = tokenCounter\n ? (tools?.reduce((acc, tool) => {\n if (!(tool as Partial<t.GenericTool>).schema) {\n return acc;\n }\n\n const jsonSchema = zodToJsonSchema(\n (tool?.schema as t.ZodObjectAny).describe(tool?.description ?? ''),\n tool?.name ?? ''\n );\n return (\n acc + tokenCounter(new SystemMessage(JSON.stringify(jsonSchema)))\n );\n }, 0) ?? 0)\n : 0;\n let instructionTokens = toolTokens;\n if (this.Graph.systemMessage && tokenCounter) {\n instructionTokens += tokenCounter(this.Graph.systemMessage);\n }\n const tokenMap = streamOptions?.indexTokenCountMap ?? {};\n if (this.Graph.systemMessage && instructionTokens > 0) {\n this.Graph.indexTokenCountMap = shiftIndexTokenCountMap(\n tokenMap,\n instructionTokens\n );\n } else if (instructionTokens > 0) {\n tokenMap[0] = tokenMap[0] + instructionTokens;\n this.Graph.indexTokenCountMap = tokenMap;\n } else {\n this.Graph.indexTokenCountMap = tokenMap;\n }\n\n this.Graph.maxContextTokens = streamOptions?.maxContextTokens;\n this.Graph.tokenCounter = tokenCounter;\n\n config.run_id = this.id;\n config.configurable = Object.assign(config.configurable ?? {}, {\n run_id: this.id,\n provider: this.provider,\n });\n\n const stream = this.graphRunnable.streamEvents(inputs, config);\n\n for await (const event of stream) {\n const { data, name, metadata, ...info } = event;\n\n let eventName: t.EventName = info.event;\n if (\n hasTools &&\n manualToolStreamProviders.has(provider) &&\n eventName === GraphEvents.CHAT_MODEL_STREAM\n ) {\n /* Skipping CHAT_MODEL_STREAM event due to double-call edge case */\n continue;\n }\n\n if (eventName && eventName === GraphEvents.ON_CUSTOM_EVENT) {\n eventName = name;\n }\n\n const handler = this.handlerRegistry.getHandler(eventName);\n if (handler) {\n handler.handle(eventName, data, metadata, this.Graph);\n }\n }\n\n if (this.returnContent) {\n return this.Graph.getContentParts();\n }\n }\n\n private createSystemCallback<K extends keyof ClientCallbacks>(\n clientCallbacks: ClientCallbacks,\n key: K\n ): SystemCallbacks[K] {\n return ((...args: unknown[]) => {\n const clientCallback = clientCallbacks[key];\n if (clientCallback && this.Graph) {\n (clientCallback as (...args: unknown[]) => void)(this.Graph, ...args);\n }\n }) as SystemCallbacks[K];\n }\n\n getCallbacks(clientCallbacks: ClientCallbacks): SystemCallbacks {\n return {\n [Callback.TOOL_ERROR]: this.createSystemCallback(\n clientCallbacks,\n Callback.TOOL_ERROR\n ),\n [Callback.TOOL_START]: this.createSystemCallback(\n clientCallbacks,\n Callback.TOOL_START\n ),\n [Callback.TOOL_END]: this.createSystemCallback(\n clientCallbacks,\n Callback.TOOL_END\n ),\n };\n }\n\n async generateTitle({\n provider,\n inputText,\n contentParts,\n titlePrompt,\n clientOptions,\n chainOptions,\n skipLanguage,\n omitOptions = defaultOmitOptions,\n }: t.RunTitleOptions): Promise<{ language: string; title: string }> {\n const convoTemplate = PromptTemplate.fromTemplate(\n 'User: {input}\\nAI: {output}'\n );\n const response = contentParts\n .map((part) => {\n if (part?.type === 'text') return part.text;\n return '';\n })\n .join('\\n');\n const convo = (\n await convoTemplate.invoke({ input: inputText, output: response })\n ).value;\n const model = this.Graph?.getNewModel({\n provider,\n omitOptions,\n clientOptions,\n });\n if (!model) {\n return { language: '', title: '' };\n }\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions | undefined)\n ?.temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions | undefined)\n ?.topP as number;\n model.frequencyPenalty = (\n clientOptions as t.OpenAIClientOptions | undefined\n )?.frequencyPenalty as number;\n model.presencePenalty = (\n clientOptions as t.OpenAIClientOptions | undefined\n )?.presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions | undefined)\n ?.n as number;\n }\n const chain = await createTitleRunnable(model, titlePrompt);\n return (await chain.invoke(\n { convo, inputText, skipLanguage },\n chainOptions\n )) as { language: string; title: string };\n }\n}\n"],"names":["ChatOpenAI","AzureChatOpenAI"],"mappings":";;;;;;;;;;;;;AAAA;AAqBa,MAAA,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACxC,QAAQ;IACR,UAAU;IACV,WAAW;IACX,WAAW;IACX,eAAe;IACf,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,8BAA8B;AAC/B,CAAA;MAEY,GAAG,CAAA;AACd,IAAA,aAAa;;;AAGL,IAAA,eAAe;AACvB,IAAA,EAAE;AACF,IAAA,KAAK;AACL,IAAA,QAAQ;IACR,aAAa,GAAY,KAAK;AAE9B,IAAA,WAAA,CAAoB,MAA4B,EAAA;AAC9C,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE;QAChC,IAAI,CAAC,KAAK,EAAE;AACV,YAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC;;AAGxC,QAAA,IAAI,CAAC,EAAE,GAAG,KAAK;AAEf,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE;AAE7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,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE;;QAEpC,IACE,YAAY,CAAC,QAAQ,CAAC;aACrB,KAAK,YAAYA,YAAU,IAAI,KAAK,YAAYC,iBAAe,CAAC,EACjE;YACA,KAAK,CAAC,WAAW,GAAI;AACnB,kBAAE,WAAqB;YACzB,KAAK,CAAC,IAAI,GAAI;AACZ,kBAAE,IAAc;AAClB,YAAA,KAAK,CAAC,gBAAgB,GACpB,aACD,EAAE,gBAA0B;AAC7B,YAAA,KAAK,CAAC,eAAe,GACnB,aACD,EAAE,eAAyB;YAC5B,KAAK,CAAC,CAAC,GAAI;AACT,kBAAE,CAAW;;QAEjB,MAAM,KAAK,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3D,QAAA,QAAQ,MAAM,KAAK,CAAC,MAAM,CACxB,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAClC,YAAY,CACb;;AAEJ;;;;"}
|
|
@@ -70,7 +70,7 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
|
|
|
70
70
|
systemMessage: SystemMessage | undefined;
|
|
71
71
|
messages: BaseMessage[];
|
|
72
72
|
runId: string | undefined;
|
|
73
|
-
tools?: t.
|
|
73
|
+
tools?: t.GraphTools;
|
|
74
74
|
toolMap?: t.ToolMap;
|
|
75
75
|
startIndex: number;
|
|
76
76
|
provider: Providers;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { POSSIBLE_ROLES, type Part, type Content, type EnhancedGenerateContentResponse, type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool } from '@google/generative-ai';
|
|
2
2
|
import { BaseMessage, UsageMetadata } from '@langchain/core/messages';
|
|
3
3
|
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
4
4
|
import { GoogleGenerativeAIToolType } from '../types';
|
|
@@ -11,7 +11,7 @@ export declare function getMessageAuthor(message: BaseMessage): string;
|
|
|
11
11
|
*/
|
|
12
12
|
export declare function convertAuthorToRole(author: string): (typeof POSSIBLE_ROLES)[number];
|
|
13
13
|
export declare function convertMessageContentToParts(message: BaseMessage, isMultimodalModel: boolean, previousMessages: BaseMessage[]): Part[];
|
|
14
|
-
export declare function convertBaseMessagesToContent(messages: BaseMessage[], isMultimodalModel: boolean, convertSystemMessageToHumanContent?: boolean): Content[];
|
|
14
|
+
export declare function convertBaseMessagesToContent(messages: BaseMessage[], isMultimodalModel: boolean, convertSystemMessageToHumanContent?: boolean): Content[] | undefined;
|
|
15
15
|
export declare function convertResponseContentToChatGenerationChunk(response: EnhancedGenerateContentResponse, extra: {
|
|
16
16
|
usageMetadata?: UsageMetadata | undefined;
|
|
17
17
|
index: number;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { StateGraphArgs, StateGraph, CompiledStateGraph } from '@langchain/langgraph';
|
|
2
|
+
import type { BindToolsInput } from '@langchain/core/language_models/chat_models';
|
|
2
3
|
import type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
3
4
|
import type { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
5
|
+
import type { GoogleAIToolType } from '@langchain/google-common';
|
|
4
6
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
5
7
|
import type { ToolMap, GenericTool } from '@/types/tools';
|
|
6
8
|
import type { ClientOptions } from '@/types/llm';
|
|
@@ -17,9 +19,9 @@ export type GraphStateChannels<T extends BaseGraphState> = StateGraphArgs<T>['ch
|
|
|
17
19
|
export type Workflow<T extends BaseGraphState = BaseGraphState, U extends Partial<T> = Partial<T>, N extends string = string> = StateGraph<T, U, N>;
|
|
18
20
|
export type CompiledWorkflow<T extends BaseGraphState = BaseGraphState, U extends Partial<T> = Partial<T>, N extends string = string> = CompiledStateGraph<T, U, N>;
|
|
19
21
|
export type EventStreamCallbackHandlerInput = Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<infer T, 'autoClose'> ? T : never;
|
|
20
|
-
export type StreamChunk = ChatGenerationChunk & {
|
|
22
|
+
export type StreamChunk = (ChatGenerationChunk & {
|
|
21
23
|
message: AIMessageChunk;
|
|
22
|
-
} | AIMessageChunk;
|
|
24
|
+
}) | AIMessageChunk;
|
|
23
25
|
/**
|
|
24
26
|
* Data associated with a StreamEvent.
|
|
25
27
|
*/
|
|
@@ -117,9 +119,10 @@ export type PartMetadata = {
|
|
|
117
119
|
action?: boolean;
|
|
118
120
|
output?: string;
|
|
119
121
|
};
|
|
120
|
-
export type ModelEndData = StreamEventData & {
|
|
122
|
+
export type ModelEndData = (StreamEventData & {
|
|
121
123
|
output: AIMessageChunk | undefined;
|
|
122
|
-
} | undefined;
|
|
124
|
+
}) | undefined;
|
|
125
|
+
export type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];
|
|
123
126
|
export type StandardGraphInput = {
|
|
124
127
|
runId?: string;
|
|
125
128
|
toolEnd?: boolean;
|
|
@@ -128,8 +131,8 @@ export type StandardGraphInput = {
|
|
|
128
131
|
signal?: AbortSignal;
|
|
129
132
|
instructions?: string;
|
|
130
133
|
streamBuffer?: number;
|
|
131
|
-
tools?: GenericTool[];
|
|
132
134
|
clientOptions: ClientOptions;
|
|
133
135
|
additional_instructions?: string;
|
|
134
136
|
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
137
|
+
tools?: GraphTools;
|
|
135
138
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { RunnableToolLike } from '@langchain/core/runnables';
|
|
2
1
|
import type { StructuredToolInterface } from '@langchain/core/tools';
|
|
2
|
+
import type { RunnableToolLike } from '@langchain/core/runnables';
|
|
3
3
|
import type { ToolCall } from '@langchain/core/messages/tool';
|
|
4
4
|
import type { ToolErrorData } from './stream';
|
|
5
5
|
import { EnvVar } from '@/common';
|
package/package.json
CHANGED
package/src/graphs/Graph.ts
CHANGED
|
@@ -135,7 +135,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
|
|
|
135
135
|
systemMessage: SystemMessage | undefined;
|
|
136
136
|
messages: BaseMessage[] = [];
|
|
137
137
|
runId: string | undefined;
|
|
138
|
-
tools?: t.
|
|
138
|
+
tools?: t.GraphTools;
|
|
139
139
|
toolMap?: t.ToolMap;
|
|
140
140
|
startIndex: number = 0;
|
|
141
141
|
provider: Providers;
|
|
@@ -354,7 +354,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
|
|
|
354
354
|
| ToolNode<t.BaseGraphState> {
|
|
355
355
|
// return new ToolNode<t.BaseGraphState>(this.tools);
|
|
356
356
|
return new CustomToolNode<t.BaseGraphState>({
|
|
357
|
-
tools: this.tools || [],
|
|
357
|
+
tools: (this.tools as t.GenericTool[] | undefined) || [],
|
|
358
358
|
toolMap: this.toolMap,
|
|
359
359
|
toolCallStepIds: this.toolCallStepIds,
|
|
360
360
|
errorHandler: (data, metadata) =>
|
package/src/llm/google/index.ts
CHANGED
|
@@ -133,7 +133,7 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
133
133
|
this.useSystemInstruction
|
|
134
134
|
);
|
|
135
135
|
let actualPrompt = prompt;
|
|
136
|
-
if (prompt[0].role === 'system') {
|
|
136
|
+
if (prompt?.[0].role === 'system') {
|
|
137
137
|
const [systemInstruction] = prompt;
|
|
138
138
|
/** @ts-ignore */
|
|
139
139
|
this.client.systemInstruction = systemInstruction;
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
|
-
EnhancedGenerateContentResponse,
|
|
3
|
-
Content,
|
|
4
|
-
Part,
|
|
5
|
-
type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,
|
|
6
|
-
type FunctionDeclaration as GenerativeAIFunctionDeclaration,
|
|
7
2
|
POSSIBLE_ROLES,
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
3
|
+
type Part,
|
|
4
|
+
type Content,
|
|
5
|
+
type TextPart,
|
|
6
|
+
type FileDataPart,
|
|
7
|
+
type InlineDataPart,
|
|
8
|
+
type FunctionCallPart,
|
|
9
|
+
type GenerateContentCandidate,
|
|
10
|
+
type EnhancedGenerateContentResponse,
|
|
11
|
+
type FunctionDeclaration as GenerativeAIFunctionDeclaration,
|
|
12
|
+
type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,
|
|
12
13
|
} from '@google/generative-ai';
|
|
13
14
|
import {
|
|
14
15
|
AIMessageChunk,
|
|
@@ -412,9 +413,9 @@ export function convertBaseMessagesToContent(
|
|
|
412
413
|
messages: BaseMessage[],
|
|
413
414
|
isMultimodalModel: boolean,
|
|
414
415
|
convertSystemMessageToHumanContent: boolean = false
|
|
415
|
-
): Content[] {
|
|
416
|
+
): Content[] | undefined {
|
|
416
417
|
return messages.reduce<{
|
|
417
|
-
content: Content[];
|
|
418
|
+
content: Content[] | undefined;
|
|
418
419
|
mergeWithPreviousContent: boolean;
|
|
419
420
|
}>(
|
|
420
421
|
(acc, message, index) => {
|
|
@@ -427,7 +428,7 @@ export function convertBaseMessagesToContent(
|
|
|
427
428
|
}
|
|
428
429
|
const role = convertAuthorToRole(author);
|
|
429
430
|
|
|
430
|
-
const prevContent = acc.content[acc.content.length];
|
|
431
|
+
const prevContent = acc.content?.[acc.content.length];
|
|
431
432
|
if (
|
|
432
433
|
!acc.mergeWithPreviousContent &&
|
|
433
434
|
prevContent &&
|
|
@@ -445,7 +446,7 @@ export function convertBaseMessagesToContent(
|
|
|
445
446
|
);
|
|
446
447
|
|
|
447
448
|
if (acc.mergeWithPreviousContent) {
|
|
448
|
-
const prevContent = acc.content[acc.content.length - 1];
|
|
449
|
+
const prevContent = acc.content?.[acc.content.length - 1];
|
|
449
450
|
if (!prevContent) {
|
|
450
451
|
throw new Error(
|
|
451
452
|
'There was a problem parsing your system message. Please try a prompt without one.'
|
|
@@ -473,7 +474,7 @@ export function convertBaseMessagesToContent(
|
|
|
473
474
|
return {
|
|
474
475
|
mergeWithPreviousContent:
|
|
475
476
|
author === 'system' && !convertSystemMessageToHumanContent,
|
|
476
|
-
content: [...acc.content, content],
|
|
477
|
+
content: [...(acc.content ?? []), content],
|
|
477
478
|
};
|
|
478
479
|
},
|
|
479
480
|
{ content: [], mergeWithPreviousContent: false }
|
|
@@ -491,12 +492,15 @@ export function convertResponseContentToChatGenerationChunk(
|
|
|
491
492
|
return null;
|
|
492
493
|
}
|
|
493
494
|
const functionCalls = response.functionCalls();
|
|
494
|
-
const [candidate] = response.candidates
|
|
495
|
-
|
|
495
|
+
const [candidate] = response.candidates as [
|
|
496
|
+
Partial<GenerateContentCandidate> | undefined,
|
|
497
|
+
];
|
|
498
|
+
const { content: candidateContent, ...generationInfo } = candidate ?? {};
|
|
496
499
|
let content: MessageContent | undefined;
|
|
497
500
|
// Checks if some parts do not have text. If false, it means that the content is a string.
|
|
498
501
|
const reasoningParts: string[] = [];
|
|
499
502
|
if (
|
|
503
|
+
candidateContent != null &&
|
|
500
504
|
Array.isArray(candidateContent.parts) &&
|
|
501
505
|
candidateContent.parts.every((p) => 'text' in p)
|
|
502
506
|
) {
|
|
@@ -510,7 +514,7 @@ export function convertResponseContentToChatGenerationChunk(
|
|
|
510
514
|
textParts.push(part.text ?? '');
|
|
511
515
|
}
|
|
512
516
|
content = textParts.join('');
|
|
513
|
-
} else if (Array.isArray(candidateContent.parts)) {
|
|
517
|
+
} else if (candidateContent && Array.isArray(candidateContent.parts)) {
|
|
514
518
|
content = candidateContent.parts.map((p) => {
|
|
515
519
|
if ('text' in p && 'thought' in p && p.thought === true) {
|
|
516
520
|
reasoningParts.push(p.text ?? '');
|
|
@@ -565,10 +569,14 @@ export function convertResponseContentToChatGenerationChunk(
|
|
|
565
569
|
additional_kwargs.reasoning = reasoningParts.join('');
|
|
566
570
|
}
|
|
567
571
|
|
|
572
|
+
if (candidate?.groundingMetadata) {
|
|
573
|
+
additional_kwargs.groundingMetadata = candidate.groundingMetadata;
|
|
574
|
+
}
|
|
575
|
+
|
|
568
576
|
return new ChatGenerationChunk({
|
|
569
577
|
text,
|
|
570
578
|
message: new AIMessageChunk({
|
|
571
|
-
content: content
|
|
579
|
+
content: content,
|
|
572
580
|
name: !candidateContent ? undefined : candidateContent.role,
|
|
573
581
|
tool_call_chunks: toolCallChunks,
|
|
574
582
|
// Each chunk can have unique "generationInfo", and merging strategy is unclear,
|
package/src/run.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// src/run.ts
|
|
2
2
|
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
3
3
|
import { PromptTemplate } from '@langchain/core/prompts';
|
|
4
|
-
import { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';
|
|
5
4
|
import { SystemMessage } from '@langchain/core/messages';
|
|
5
|
+
import { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';
|
|
6
6
|
import type {
|
|
7
7
|
BaseMessage,
|
|
8
8
|
MessageContentComplex,
|
|
@@ -147,15 +147,18 @@ export class Run<T extends t.BaseGraphState> {
|
|
|
147
147
|
(streamOptions?.indexTokenCountMap
|
|
148
148
|
? await createTokenCounter()
|
|
149
149
|
: undefined);
|
|
150
|
+
const tools = this.Graph.tools as
|
|
151
|
+
| Array<t.GenericTool | undefined>
|
|
152
|
+
| undefined;
|
|
150
153
|
const toolTokens = tokenCounter
|
|
151
|
-
? (
|
|
154
|
+
? (tools?.reduce((acc, tool) => {
|
|
152
155
|
if (!(tool as Partial<t.GenericTool>).schema) {
|
|
153
156
|
return acc;
|
|
154
157
|
}
|
|
155
158
|
|
|
156
159
|
const jsonSchema = zodToJsonSchema(
|
|
157
|
-
(tool
|
|
158
|
-
tool
|
|
160
|
+
(tool?.schema as t.ZodObjectAny).describe(tool?.description ?? ''),
|
|
161
|
+
tool?.name ?? ''
|
|
159
162
|
);
|
|
160
163
|
return (
|
|
161
164
|
acc + tokenCounter(new SystemMessage(JSON.stringify(jsonSchema)))
|
package/src/types/graph.ts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
// src/types/graph.ts
|
|
2
|
-
import type {
|
|
2
|
+
import type {
|
|
3
|
+
StateGraphArgs,
|
|
4
|
+
StateGraph,
|
|
5
|
+
CompiledStateGraph,
|
|
6
|
+
} from '@langchain/langgraph';
|
|
7
|
+
import type { BindToolsInput } from '@langchain/core/language_models/chat_models';
|
|
3
8
|
import type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
4
9
|
import type { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
10
|
+
import type { GoogleAIToolType } from '@langchain/google-common';
|
|
5
11
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
6
12
|
import type { ToolMap, GenericTool } from '@/types/tools';
|
|
7
13
|
import type { ClientOptions } from '@/types/llm';
|
|
@@ -22,56 +28,78 @@ export type IState = BaseGraphState;
|
|
|
22
28
|
// }
|
|
23
29
|
|
|
24
30
|
export interface EventHandler {
|
|
25
|
-
handle(
|
|
31
|
+
handle(
|
|
32
|
+
event: string,
|
|
33
|
+
data: StreamEventData | ModelEndData,
|
|
34
|
+
metadata?: Record<string, unknown>,
|
|
35
|
+
graph?: Graph
|
|
36
|
+
): void;
|
|
26
37
|
}
|
|
27
38
|
|
|
28
|
-
export type GraphStateChannels<T extends BaseGraphState> =
|
|
39
|
+
export type GraphStateChannels<T extends BaseGraphState> =
|
|
40
|
+
StateGraphArgs<T>['channels'];
|
|
29
41
|
|
|
30
|
-
export type Workflow<
|
|
42
|
+
export type Workflow<
|
|
43
|
+
T extends BaseGraphState = BaseGraphState,
|
|
44
|
+
U extends Partial<T> = Partial<T>,
|
|
45
|
+
N extends string = string,
|
|
46
|
+
> = StateGraph<T, U, N>;
|
|
31
47
|
|
|
32
|
-
export type CompiledWorkflow<
|
|
48
|
+
export type CompiledWorkflow<
|
|
49
|
+
T extends BaseGraphState = BaseGraphState,
|
|
50
|
+
U extends Partial<T> = Partial<T>,
|
|
51
|
+
N extends string = string,
|
|
52
|
+
> = CompiledStateGraph<T, U, N>;
|
|
33
53
|
|
|
34
|
-
export type EventStreamCallbackHandlerInput =
|
|
54
|
+
export type EventStreamCallbackHandlerInput =
|
|
55
|
+
Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<
|
|
56
|
+
infer T,
|
|
57
|
+
'autoClose'
|
|
58
|
+
>
|
|
59
|
+
? T
|
|
60
|
+
: never;
|
|
35
61
|
|
|
36
|
-
export type StreamChunk =
|
|
37
|
-
|
|
38
|
-
|
|
62
|
+
export type StreamChunk =
|
|
63
|
+
| (ChatGenerationChunk & {
|
|
64
|
+
message: AIMessageChunk;
|
|
65
|
+
})
|
|
66
|
+
| AIMessageChunk;
|
|
39
67
|
|
|
40
68
|
/**
|
|
41
69
|
* Data associated with a StreamEvent.
|
|
42
70
|
*/
|
|
43
71
|
export type StreamEventData = {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
/**
|
|
73
|
+
* The input passed to the runnable that generated the event.
|
|
74
|
+
* Inputs will sometimes be available at the *START* of the runnable, and
|
|
75
|
+
* sometimes at the *END* of the runnable.
|
|
76
|
+
* If a runnable is able to stream its inputs, then its input by definition
|
|
77
|
+
* won't be known until the *END* of the runnable when it has finished streaming
|
|
78
|
+
* its inputs.
|
|
79
|
+
*/
|
|
80
|
+
input?: unknown;
|
|
81
|
+
/**
|
|
82
|
+
* The output of the runnable that generated the event.
|
|
83
|
+
* Outputs will only be available at the *END* of the runnable.
|
|
84
|
+
* For most runnables, this field can be inferred from the `chunk` field,
|
|
85
|
+
* though there might be some exceptions for special cased runnables (e.g., like
|
|
86
|
+
* chat models), which may return more information.
|
|
87
|
+
*/
|
|
88
|
+
output?: unknown;
|
|
89
|
+
/**
|
|
90
|
+
* A streaming chunk from the output that generated the event.
|
|
91
|
+
* chunks support addition in general, and adding them up should result
|
|
92
|
+
* in the output of the runnable that generated the event.
|
|
93
|
+
*/
|
|
94
|
+
chunk?: StreamChunk;
|
|
95
|
+
/**
|
|
96
|
+
* Runnable config for invoking other runnables within handlers.
|
|
97
|
+
*/
|
|
98
|
+
config?: RunnableConfig;
|
|
99
|
+
/**
|
|
100
|
+
* Custom result from the runnable that generated the event.
|
|
101
|
+
*/
|
|
102
|
+
result?: unknown;
|
|
75
103
|
};
|
|
76
104
|
|
|
77
105
|
/**
|
|
@@ -80,54 +108,54 @@ export type StreamEventData = {
|
|
|
80
108
|
* Schema of a streaming event which is produced from the streamEvents method.
|
|
81
109
|
*/
|
|
82
110
|
export type StreamEvent = {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
111
|
+
/**
|
|
112
|
+
* Event names are of the format: on_[runnable_type]_(start|stream|end).
|
|
113
|
+
*
|
|
114
|
+
* Runnable types are one of:
|
|
115
|
+
* - llm - used by non chat models
|
|
116
|
+
* - chat_model - used by chat models
|
|
117
|
+
* - prompt -- e.g., ChatPromptTemplate
|
|
118
|
+
* - tool -- LangChain tools
|
|
119
|
+
* - chain - most Runnables are of this type
|
|
120
|
+
*
|
|
121
|
+
* Further, the events are categorized as one of:
|
|
122
|
+
* - start - when the runnable starts
|
|
123
|
+
* - stream - when the runnable is streaming
|
|
124
|
+
* - end - when the runnable ends
|
|
125
|
+
*
|
|
126
|
+
* start, stream and end are associated with slightly different `data` payload.
|
|
127
|
+
*
|
|
128
|
+
* Please see the documentation for `EventData` for more details.
|
|
129
|
+
*/
|
|
130
|
+
event: string;
|
|
131
|
+
/** The name of the runnable that generated the event. */
|
|
132
|
+
name: string;
|
|
133
|
+
/**
|
|
134
|
+
* An randomly generated ID to keep track of the execution of the given runnable.
|
|
135
|
+
*
|
|
136
|
+
* Each child runnable that gets invoked as part of the execution of a parent runnable
|
|
137
|
+
* is assigned its own unique ID.
|
|
138
|
+
*/
|
|
139
|
+
run_id: string;
|
|
140
|
+
/**
|
|
141
|
+
* Tags associated with the runnable that generated this event.
|
|
142
|
+
* Tags are always inherited from parent runnables.
|
|
143
|
+
*/
|
|
144
|
+
tags?: string[];
|
|
145
|
+
/** Metadata associated with the runnable that generated this event. */
|
|
146
|
+
metadata: Record<string, unknown>;
|
|
147
|
+
/**
|
|
148
|
+
* Event data.
|
|
149
|
+
*
|
|
150
|
+
* The contents of the event data depend on the event type.
|
|
151
|
+
*/
|
|
152
|
+
data: StreamEventData;
|
|
125
153
|
};
|
|
126
154
|
|
|
127
155
|
export type GraphConfig = {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
156
|
+
provider: string;
|
|
157
|
+
thread_id?: string;
|
|
158
|
+
run_id?: string;
|
|
131
159
|
};
|
|
132
160
|
|
|
133
161
|
export type PartMetadata = {
|
|
@@ -138,8 +166,10 @@ export type PartMetadata = {
|
|
|
138
166
|
output?: string;
|
|
139
167
|
};
|
|
140
168
|
|
|
141
|
-
export type ModelEndData =
|
|
142
|
-
|
|
169
|
+
export type ModelEndData =
|
|
170
|
+
| (StreamEventData & { output: AIMessageChunk | undefined })
|
|
171
|
+
| undefined;
|
|
172
|
+
export type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];
|
|
143
173
|
export type StandardGraphInput = {
|
|
144
174
|
runId?: string;
|
|
145
175
|
toolEnd?: boolean;
|
|
@@ -148,8 +178,8 @@ export type StandardGraphInput = {
|
|
|
148
178
|
signal?: AbortSignal;
|
|
149
179
|
instructions?: string;
|
|
150
180
|
streamBuffer?: number;
|
|
151
|
-
tools?: GenericTool[];
|
|
152
181
|
clientOptions: ClientOptions;
|
|
153
182
|
additional_instructions?: string;
|
|
154
183
|
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
155
|
-
|
|
184
|
+
tools?: GraphTools;
|
|
185
|
+
};
|