langchain 1.0.0-alpha.3 → 1.0.0-alpha.5
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/agents/ReactAgent.cjs +1 -1
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +3 -3
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +3 -3
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +2 -2
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/RunnableCallable.cjs +5 -0
- package/dist/agents/RunnableCallable.cjs.map +1 -1
- package/dist/agents/RunnableCallable.d.cts +2 -0
- package/dist/agents/RunnableCallable.d.cts.map +1 -1
- package/dist/agents/RunnableCallable.d.ts +2 -0
- package/dist/agents/RunnableCallable.d.ts.map +1 -1
- package/dist/agents/RunnableCallable.js +5 -0
- package/dist/agents/RunnableCallable.js.map +1 -1
- package/dist/agents/annotation.cjs +2 -2
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.d.cts +4 -4
- package/dist/agents/annotation.d.cts.map +1 -1
- package/dist/agents/annotation.d.ts +3 -3
- package/dist/agents/annotation.d.ts.map +1 -1
- package/dist/agents/annotation.js +2 -2
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/createAgent.cjs +10 -0
- package/dist/agents/createAgent.cjs.map +1 -0
- package/dist/agents/createAgent.js +10 -0
- package/dist/agents/createAgent.js.map +1 -0
- package/dist/agents/errors.cjs +1 -1
- package/dist/agents/errors.cjs.map +1 -1
- package/dist/agents/errors.js +1 -1
- package/dist/agents/errors.js.map +1 -1
- package/dist/agents/index.cjs +23 -4
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +96 -33
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +96 -33
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +23 -4
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.cjs +255 -0
- package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.cts +68 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.ts +68 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/ReactAgent.js +254 -0
- package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -0
- package/dist/agents/middlewareAgent/annotation.cjs +39 -0
- package/dist/agents/middlewareAgent/annotation.cjs.map +1 -0
- package/dist/agents/middlewareAgent/annotation.js +38 -0
- package/dist/agents/middlewareAgent/annotation.js.map +1 -0
- package/dist/agents/middlewareAgent/index.cjs +11 -0
- package/dist/agents/middlewareAgent/index.cjs.map +1 -0
- package/dist/agents/middlewareAgent/index.js +11 -0
- package/dist/agents/middlewareAgent/index.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware.cjs +47 -0
- package/dist/agents/middlewareAgent/middleware.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware.d.cts +46 -0
- package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware.d.ts +46 -0
- package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware.js +46 -0
- package/dist/agents/middlewareAgent/middleware.js.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.cjs +235 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.d.cts +199 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.d.ts +199 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.js +234 -0
- package/dist/agents/middlewareAgent/middlewares/hitl.js.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/index.cjs +8 -0
- package/dist/agents/middlewareAgent/middlewares/index.d.cts +4 -0
- package/dist/agents/middlewareAgent/middlewares/index.d.ts +4 -0
- package/dist/agents/middlewareAgent/middlewares/index.js +5 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs +153 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts +152 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts +152 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.js +152 -0
- package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.cjs +262 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.d.cts +89 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.d.ts +89 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.js +260 -0
- package/dist/agents/middlewareAgent/middlewares/summarization.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +29 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +29 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +332 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.js +331 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +27 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +27 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/middleware.cjs +73 -0
- package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/middleware.js +73 -0
- package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/utils.cjs +74 -0
- package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/utils.js +70 -0
- package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -0
- package/dist/agents/middlewareAgent/types.d.cts +393 -0
- package/dist/agents/middlewareAgent/types.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/types.d.ts +393 -0
- package/dist/agents/middlewareAgent/types.d.ts.map +1 -0
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +1 -1
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.d.cts +4 -4
- package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
- package/dist/agents/nodes/ToolNode.d.ts +1 -1
- package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
- package/dist/agents/nodes/ToolNode.js +1 -1
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/responses.cjs +1 -1
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +1 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +1 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +1 -1
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/types.d.cts +12 -12
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +8 -8
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +1 -1
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +1 -1
- package/dist/agents/utils.js.map +1 -1
- package/dist/agents/withAgentName.cjs +1 -1
- package/dist/agents/withAgentName.cjs.map +1 -1
- package/dist/agents/withAgentName.js +1 -1
- package/dist/agents/withAgentName.js.map +1 -1
- package/dist/chains/api/api_chain.d.cts +1 -1
- package/dist/chains/base.d.cts +1 -1
- package/dist/chains/combine_docs_chain.d.cts +1 -1
- package/dist/chains/combine_documents/stuff.d.cts +1 -1
- package/dist/chains/conversational_retrieval_chain.d.cts +1 -1
- package/dist/chains/graph_qa/cypher.d.cts +1 -1
- package/dist/chains/history_aware_retriever.d.cts +2 -2
- package/dist/chains/llm_chain.d.cts +3 -3
- package/dist/chains/openai_functions/base.d.cts +3 -3
- package/dist/chains/openai_functions/openapi.d.cts +1 -1
- package/dist/chains/openai_functions/structured_output.d.cts +3 -3
- package/dist/chains/openai_functions/tagging.d.cts +1 -1
- package/dist/chains/query_constructor/index.cjs +1 -1
- package/dist/chains/query_constructor/index.d.cts +2 -2
- package/dist/chains/query_constructor/index.d.ts +1 -1
- package/dist/chains/query_constructor/index.js +1 -1
- package/dist/chains/question_answering/load.d.ts +2 -2
- package/dist/chains/question_answering/load.d.ts.map +1 -1
- package/dist/chains/retrieval.d.cts +1 -1
- package/dist/chains/router/llm_router.d.cts +1 -1
- package/dist/chains/router/multi_prompt.cjs +1 -1
- package/dist/chains/router/multi_prompt.js +1 -1
- package/dist/chains/router/multi_retrieval_qa.cjs +1 -1
- package/dist/chains/router/multi_retrieval_qa.js +1 -1
- package/dist/chains/sql_db/sql_db_chain.d.cts +2 -2
- package/dist/chains/summarization/load.d.ts +2 -2
- package/dist/chains/summarization/load.d.ts.map +1 -1
- package/dist/chat_models/universal.d.cts +3 -3
- package/dist/evaluation/agents/trajectory.d.cts +3 -3
- package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts +1 -1
- package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.cts +1 -1
- package/dist/evaluation/qa/eval_chain.d.cts +1 -1
- package/dist/index.cjs +5 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -5
- package/dist/index.d.ts +4 -3
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/load/import_map.cjs +1 -1
- package/dist/load/import_map.js +1 -1
- package/dist/memory/summary.d.cts +1 -1
- package/dist/output_parsers/fix.d.cts +1 -1
- package/dist/output_parsers/http_response.d.cts +1 -1
- package/dist/output_parsers/structured.cjs +1 -1
- package/dist/output_parsers/structured.d.cts +2 -2
- package/dist/output_parsers/structured.d.ts +1 -1
- package/dist/output_parsers/structured.js +1 -1
- package/dist/tools/fs.d.cts +1 -1
- package/dist/tools/json.d.cts +1 -1
- package/dist/tools/retriever.d.cts +1 -1
- package/dist/tools/vectorstore.d.cts +1 -1
- package/dist/tools/webbrowser.d.cts +1 -1
- package/package.json +14 -3
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { isClientTool, validateLLMHasNoBoundTools } from "../utils.js";
|
|
2
|
+
import { ToolNode } from "../nodes/ToolNode.js";
|
|
3
|
+
import { createAgentAnnotationConditional } from "./annotation.js";
|
|
4
|
+
import { initializeMiddlewareStates } from "./nodes/utils.js";
|
|
5
|
+
import { AgentNode } from "./nodes/AgentNode.js";
|
|
6
|
+
import { BeforeModelNode } from "./nodes/BeforeModalNode.js";
|
|
7
|
+
import { AfterModelNode } from "./nodes/AfterModalNode.js";
|
|
8
|
+
import { AIMessage, ToolMessage } from "@langchain/core/messages";
|
|
9
|
+
import { Command, END, START, Send, StateGraph } from "@langchain/langgraph";
|
|
10
|
+
|
|
11
|
+
//#region src/agents/middlewareAgent/ReactAgent.ts
|
|
12
|
+
var ReactAgent = class {
|
|
13
|
+
#graph;
|
|
14
|
+
#toolBehaviorVersion = "v2";
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.options = options;
|
|
17
|
+
this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;
|
|
18
|
+
/**
|
|
19
|
+
* Check if the LLM already has bound tools and throw if it does.
|
|
20
|
+
*/
|
|
21
|
+
if (options.llm && typeof options.llm !== "function") validateLLMHasNoBoundTools(options.llm);
|
|
22
|
+
/**
|
|
23
|
+
* validate that model and llm options are not provided together
|
|
24
|
+
*/
|
|
25
|
+
if (options.llm && options.model) throw new Error("Cannot provide both `model` and `llm` options.");
|
|
26
|
+
/**
|
|
27
|
+
* validate that either model or llm option is provided
|
|
28
|
+
*/
|
|
29
|
+
if (!options.llm && !options.model) throw new Error("Either `model` or `llm` option must be provided to create an agent.");
|
|
30
|
+
const toolClasses = (Array.isArray(options.tools) ? options.tools : options.tools?.tools) ?? [];
|
|
31
|
+
/**
|
|
32
|
+
* If any of the tools are configured to return_directly after running,
|
|
33
|
+
* our graph needs to check if these were called
|
|
34
|
+
*/
|
|
35
|
+
const shouldReturnDirect = new Set(toolClasses.filter(isClientTool).filter((tool) => "returnDirect" in tool && tool.returnDirect).map((tool) => tool.name));
|
|
36
|
+
const schema = createAgentAnnotationConditional(this.options.responseFormat !== void 0, this.options.middlewares);
|
|
37
|
+
const workflow = new StateGraph(schema, this.options.contextSchema);
|
|
38
|
+
const allNodeWorkflows = workflow;
|
|
39
|
+
const beforeModelNodes = [];
|
|
40
|
+
const afterModelNodes = [];
|
|
41
|
+
const prepareModelRequestHookMiddlewares = [];
|
|
42
|
+
const middlewares = this.options.middlewares ?? [];
|
|
43
|
+
for (let i = 0; i < middlewares.length; i++) {
|
|
44
|
+
let beforeModelNode;
|
|
45
|
+
let afterModelNode;
|
|
46
|
+
const middleware = middlewares[i];
|
|
47
|
+
if (middleware.beforeModel) {
|
|
48
|
+
beforeModelNode = new BeforeModelNode(middleware);
|
|
49
|
+
const name = `before_model_${middleware.name}_${i}`;
|
|
50
|
+
beforeModelNodes.push({
|
|
51
|
+
index: i,
|
|
52
|
+
name
|
|
53
|
+
});
|
|
54
|
+
allNodeWorkflows.addNode(name, beforeModelNode, beforeModelNode.nodeOptions);
|
|
55
|
+
}
|
|
56
|
+
if (middleware.afterModel) {
|
|
57
|
+
afterModelNode = new AfterModelNode(middleware);
|
|
58
|
+
const name = `after_model_${middleware.name}_${i}`;
|
|
59
|
+
afterModelNodes.push({
|
|
60
|
+
index: i,
|
|
61
|
+
name
|
|
62
|
+
});
|
|
63
|
+
allNodeWorkflows.addNode(name, afterModelNode, afterModelNode.nodeOptions);
|
|
64
|
+
}
|
|
65
|
+
if (middleware.prepareModelRequest) prepareModelRequestHookMiddlewares.push([middleware, () => ({
|
|
66
|
+
...beforeModelNode?.getState(),
|
|
67
|
+
...afterModelNode?.getState()
|
|
68
|
+
})]);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Add Nodes
|
|
72
|
+
*/
|
|
73
|
+
allNodeWorkflows.addNode("model_request", new AgentNode({
|
|
74
|
+
llm: this.options.llm,
|
|
75
|
+
model: this.options.model,
|
|
76
|
+
prompt: this.options.prompt,
|
|
77
|
+
includeAgentName: this.options.includeAgentName,
|
|
78
|
+
name: this.options.name,
|
|
79
|
+
responseFormat: this.options.responseFormat,
|
|
80
|
+
middlewares: this.options.middlewares,
|
|
81
|
+
toolClasses,
|
|
82
|
+
shouldReturnDirect,
|
|
83
|
+
signal: this.options.signal,
|
|
84
|
+
prepareModelRequestHookMiddlewares
|
|
85
|
+
}), AgentNode.nodeOptions);
|
|
86
|
+
/**
|
|
87
|
+
* add single tool node for all tools
|
|
88
|
+
*/
|
|
89
|
+
if (toolClasses.length > 0) {
|
|
90
|
+
const toolNode = new ToolNode(toolClasses.filter(isClientTool), { signal: this.options.signal });
|
|
91
|
+
allNodeWorkflows.addNode("tools", toolNode);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Add Edges
|
|
95
|
+
*/
|
|
96
|
+
if (beforeModelNodes.length > 0) allNodeWorkflows.addEdge(START, beforeModelNodes[0].name);
|
|
97
|
+
else allNodeWorkflows.addEdge(START, "model_request");
|
|
98
|
+
for (let i = 0; i < beforeModelNodes.length - 1; i++) allNodeWorkflows.addEdge(beforeModelNodes[i].name, beforeModelNodes[i + 1].name);
|
|
99
|
+
const lastBeforeModelNode = beforeModelNodes.at(-1);
|
|
100
|
+
if (beforeModelNodes.length > 0 && lastBeforeModelNode) allNodeWorkflows.addEdge(lastBeforeModelNode.name, "model_request");
|
|
101
|
+
const lastAfterModelNode = afterModelNodes.at(-1);
|
|
102
|
+
if (afterModelNodes.length > 0 && lastAfterModelNode) allNodeWorkflows.addEdge("model_request", lastAfterModelNode.name);
|
|
103
|
+
else {
|
|
104
|
+
const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));
|
|
105
|
+
if (modelPaths.length === 1) allNodeWorkflows.addEdge("model_request", modelPaths[0]);
|
|
106
|
+
else allNodeWorkflows.addConditionalEdges("model_request", this.#createModelRouter(), modelPaths);
|
|
107
|
+
}
|
|
108
|
+
for (let i = afterModelNodes.length - 1; i > 0; i--) allNodeWorkflows.addEdge(afterModelNodes[i].name, afterModelNodes[i - 1].name);
|
|
109
|
+
if (afterModelNodes.length > 0) {
|
|
110
|
+
const firstAfterModelNode = afterModelNodes[0].name;
|
|
111
|
+
const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));
|
|
112
|
+
if (modelPaths.length === 1) allNodeWorkflows.addEdge(firstAfterModelNode, modelPaths[0]);
|
|
113
|
+
else allNodeWorkflows.addConditionalEdges(firstAfterModelNode, this.#createModelRouter(), modelPaths);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* add edges for tools node
|
|
117
|
+
*/
|
|
118
|
+
if (toolClasses.length > 0) {
|
|
119
|
+
let toolReturnTarget;
|
|
120
|
+
if (beforeModelNodes.length > 0) toolReturnTarget = beforeModelNodes[0].name;
|
|
121
|
+
else toolReturnTarget = "model_request";
|
|
122
|
+
if (shouldReturnDirect.size > 0) allNodeWorkflows.addConditionalEdges("tools", this.#createToolsRouter(shouldReturnDirect), [toolReturnTarget, END]);
|
|
123
|
+
else allNodeWorkflows.addEdge("tools", toolReturnTarget);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* compile the graph
|
|
127
|
+
*/
|
|
128
|
+
this.#graph = allNodeWorkflows.compile({
|
|
129
|
+
checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,
|
|
130
|
+
interruptBefore: this.options.interruptBefore,
|
|
131
|
+
interruptAfter: this.options.interruptAfter,
|
|
132
|
+
store: this.options.store,
|
|
133
|
+
name: this.options.name,
|
|
134
|
+
description: this.options.description
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Get the compiled graph.
|
|
139
|
+
*/
|
|
140
|
+
get graph() {
|
|
141
|
+
return this.#graph;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Get possible edge destinations from model node.
|
|
145
|
+
* @param toolClasses names of tools to call
|
|
146
|
+
* @returns list of possible edge destinations
|
|
147
|
+
*/
|
|
148
|
+
#getModelPaths(toolClasses) {
|
|
149
|
+
const paths = [];
|
|
150
|
+
if (toolClasses.length > 0) paths.push("tools");
|
|
151
|
+
paths.push(END);
|
|
152
|
+
return paths;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Create routing function for model node conditional edges.
|
|
156
|
+
*/
|
|
157
|
+
#createModelRouter() {
|
|
158
|
+
/**
|
|
159
|
+
* determine if the agent should continue or not
|
|
160
|
+
*/
|
|
161
|
+
/**
|
|
162
|
+
* ToDo: fix type
|
|
163
|
+
*/
|
|
164
|
+
return (state) => {
|
|
165
|
+
const messages = state.messages;
|
|
166
|
+
const lastMessage = messages.at(-1);
|
|
167
|
+
if (!(lastMessage instanceof AIMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) return END;
|
|
168
|
+
/**
|
|
169
|
+
* The tool node processes a single message.
|
|
170
|
+
*/
|
|
171
|
+
if (this.#toolBehaviorVersion === "v1") return "tools";
|
|
172
|
+
/**
|
|
173
|
+
* Route to tools node
|
|
174
|
+
*/
|
|
175
|
+
return lastMessage.tool_calls.map((toolCall) => new Send("tools", {
|
|
176
|
+
...state,
|
|
177
|
+
lg_tool_call: toolCall
|
|
178
|
+
}));
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Create routing function for tools node conditional edges.
|
|
183
|
+
*/
|
|
184
|
+
#createToolsRouter(shouldReturnDirect) {
|
|
185
|
+
/**
|
|
186
|
+
* ToDo: fix type
|
|
187
|
+
*/
|
|
188
|
+
return (state) => {
|
|
189
|
+
const messages = state.messages;
|
|
190
|
+
const lastMessage = messages[messages.length - 1];
|
|
191
|
+
if (lastMessage instanceof ToolMessage && lastMessage.name && shouldReturnDirect.has(lastMessage.name)) return this.options.responseFormat ? "model_request" : END;
|
|
192
|
+
return "model_request";
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Initialize middleware states if not already present in the input state.
|
|
197
|
+
*/
|
|
198
|
+
#initializeMiddlewareStates(state) {
|
|
199
|
+
if (!this.options.middlewares || this.options.middlewares.length === 0 || state instanceof Command || !state) return state;
|
|
200
|
+
const defaultStates = initializeMiddlewareStates(this.options.middlewares, state);
|
|
201
|
+
const updatedState = { ...state };
|
|
202
|
+
if (!updatedState) return updatedState;
|
|
203
|
+
for (const [key, value] of Object.entries(defaultStates)) if (!(key in updatedState)) updatedState[key] = value;
|
|
204
|
+
return updatedState;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* @inheritdoc
|
|
208
|
+
*/
|
|
209
|
+
get invoke() {
|
|
210
|
+
const invokeFunc = async (state, config) => {
|
|
211
|
+
const initializedState = this.#initializeMiddlewareStates(state);
|
|
212
|
+
return this.#graph.invoke(initializedState, config);
|
|
213
|
+
};
|
|
214
|
+
return invokeFunc;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* ToDo(@christian-bromann): Add stream and streamEvents methods
|
|
218
|
+
*/
|
|
219
|
+
/**
|
|
220
|
+
* Visualize the graph as a PNG image.
|
|
221
|
+
* @param params - Parameters for the drawMermaidPng method.
|
|
222
|
+
* @param params.withStyles - Whether to include styles in the graph.
|
|
223
|
+
* @param params.curveStyle - The style of the graph's curves.
|
|
224
|
+
* @param params.nodeColors - The colors of the graph's nodes.
|
|
225
|
+
* @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.
|
|
226
|
+
* @param params.backgroundColor - The background color of the graph.
|
|
227
|
+
* @returns PNG image as a buffer
|
|
228
|
+
*/
|
|
229
|
+
async drawMermaidPng(params) {
|
|
230
|
+
const representation = await this.#graph.getGraphAsync();
|
|
231
|
+
const image = await representation.drawMermaidPng(params);
|
|
232
|
+
const arrayBuffer = await image.arrayBuffer();
|
|
233
|
+
const buffer = new Uint8Array(arrayBuffer);
|
|
234
|
+
return buffer;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Draw the graph as a Mermaid string.
|
|
238
|
+
* @param params - Parameters for the drawMermaid method.
|
|
239
|
+
* @param params.withStyles - Whether to include styles in the graph.
|
|
240
|
+
* @param params.curveStyle - The style of the graph's curves.
|
|
241
|
+
* @param params.nodeColors - The colors of the graph's nodes.
|
|
242
|
+
* @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.
|
|
243
|
+
* @param params.backgroundColor - The background color of the graph.
|
|
244
|
+
* @returns Mermaid string
|
|
245
|
+
*/
|
|
246
|
+
async drawMermaid(params) {
|
|
247
|
+
const representation = await this.#graph.getGraphAsync();
|
|
248
|
+
return representation.drawMermaid(params);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
//#endregion
|
|
253
|
+
export { ReactAgent };
|
|
254
|
+
//# sourceMappingURL=ReactAgent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ReactAgent.js","names":["options: CreateAgentParams<StructuredResponseFormat, ContextSchema>","#toolBehaviorVersion","beforeModelNodes: { index: number; name: string }[]","afterModelNodes: { index: number; name: string }[]","prepareModelRequestHookMiddlewares: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","beforeModelNode: BeforeModelNode | undefined","afterModelNode: AfterModelNode | undefined","#getModelPaths","#createModelRouter","toolReturnTarget: string","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","paths: (\"tools\" | typeof END)[]","state: any","shouldReturnDirect: Set<string>","state: InvokeStateParameter<TMiddlewares>","invokeFunc: InvokeFunction","config?: LangGraphRunnableConfig<FullContext>","#initializeMiddlewareStates","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../../src/agents/middlewareAgent/ReactAgent.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof, @typescript-eslint/ban-types */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport { ToolMessage, AIMessage } from \"@langchain/core/messages\";\n\nimport { createAgentAnnotationConditional } from \"./annotation.js\";\nimport { isClientTool, validateLLMHasNoBoundTools } from \"../utils.js\";\n\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"../nodes/ToolNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModalNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModalNode.js\";\nimport { initializeMiddlewareStates } from \"./nodes/utils.js\";\n\nimport type { ClientTool, ServerTool, WithStateGraphNodes } from \"../types.js\";\n\nimport {\n CreateAgentParams,\n AgentMiddleware,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n BuiltInState,\n InferMiddlewareContextInputs,\n IsAllOptional,\n InferContextInput,\n} from \"./types.js\";\n\nimport {\n type AnyAnnotationRoot,\n type ToAnnotationRoot,\n} from \"../annotation.js\";\nimport type { ResponseFormatUndefined } from \"../responses.js\";\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[]\n> = (StructuredResponseFormat extends ResponseFormatUndefined\n ? BuiltInState\n : BuiltInState & { structuredResponse: StructuredResponseFormat }) &\n InferMiddlewareStates<TMiddlewares>;\n\ntype InvokeStateParameter<\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[]\n> =\n | (BuiltInState & InferMiddlewareInputStates<TMiddlewares>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n> = CompiledStateGraph<\n any,\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n any,\n MergedAgentState<StructuredResponseFormat, TMiddlewares>,\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n> {\n #graph: AgentGraph<StructuredResponseFormat, ContextSchema, TMiddlewares>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateAgentParams<StructuredResponseFormat, ContextSchema>\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (options.llm && typeof options.llm !== \"function\") {\n validateLLMHasNoBoundTools(options.llm);\n }\n\n /**\n * validate that model and llm options are not provided together\n */\n if (options.llm && options.model) {\n throw new Error(\"Cannot provide both `model` and `llm` options.\");\n }\n\n /**\n * validate that either model or llm option is provided\n */\n if (!options.llm && !options.model) {\n throw new Error(\n \"Either `model` or `llm` option must be provided to create an agent.\"\n );\n }\n\n const toolClasses =\n (Array.isArray(options.tools) ? options.tools : options.tools?.tools) ??\n [];\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n // Create a schema that merges agent base schema with middleware state schemas\n const schema = createAgentAnnotationConditional<\n StructuredResponseFormat,\n TMiddlewares\n >(\n this.options.responseFormat !== undefined,\n this.options.middlewares as TMiddlewares\n );\n\n const workflow = new StateGraph(\n schema as AnnotationRoot<any>,\n this.options.contextSchema\n );\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"tools\" | \"model_request\" | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeModelNodes: { index: number; name: string }[] = [];\n const afterModelNodes: { index: number; name: string }[] = [];\n const prepareModelRequestHookMiddlewares: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n\n const middlewares = this.options.middlewares ?? [];\n for (let i = 0; i < middlewares.length; i++) {\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n const middleware = middlewares[i];\n if (middleware.beforeModel) {\n beforeModelNode = new BeforeModelNode(middleware);\n const name = `before_model_${middleware.name}_${i}`;\n beforeModelNodes.push({\n index: i,\n name,\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (middleware.afterModel) {\n afterModelNode = new AfterModelNode(middleware);\n const name = `after_model_${middleware.name}_${i}`;\n afterModelNodes.push({\n index: i,\n name,\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n\n if (middleware.prepareModelRequest) {\n prepareModelRequestHookMiddlewares.push([\n middleware,\n () => ({\n ...beforeModelNode?.getState(),\n ...afterModelNode?.getState(),\n }),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"model_request\",\n new AgentNode({\n llm: this.options.llm,\n model: this.options.model,\n prompt: this.options.prompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middlewares: this.options.middlewares,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n prepareModelRequestHookMiddlewares,\n }),\n AgentNode.nodeOptions\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine starting point based on what nodes exist\n if (beforeModelNodes.length > 0) {\n // If we have beforeModel nodes, start with the first one\n allNodeWorkflows.addEdge(START, beforeModelNodes[0].name);\n } else {\n // If no beforeModel nodes, go directly to agent\n allNodeWorkflows.addEdge(START, \"model_request\");\n }\n\n // Connect beforeModel nodes in sequence\n for (let i = 0; i < beforeModelNodes.length - 1; i++) {\n allNodeWorkflows.addEdge(\n beforeModelNodes[i].name,\n beforeModelNodes[i + 1].name\n );\n }\n\n // Connect last beforeModel node to agent\n const lastBeforeModelNode = beforeModelNodes.at(-1);\n if (beforeModelNodes.length > 0 && lastBeforeModelNode) {\n allNodeWorkflows.addEdge(lastBeforeModelNode.name, \"model_request\");\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(\"model_request\", lastAfterModelNode.name);\n } else {\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"model_request\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"model_request\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n allNodeWorkflows.addEdge(\n afterModelNodes[i].name,\n afterModelNodes[i - 1].name\n );\n }\n\n // Connect first afterModel node (last to execute) to model paths\n if (afterModelNodes.length > 0) {\n const firstAfterModelNode = afterModelNodes[0].name;\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(firstAfterModelNode, modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n // Tools should return to first beforeModel node or agent\n let toolReturnTarget: string;\n if (beforeModelNodes.length > 0) {\n toolReturnTarget = beforeModelNodes[0].name;\n } else {\n toolReturnTarget = \"model_request\";\n }\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [toolReturnTarget, END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n interruptBefore: this.options.interruptBefore,\n interruptAfter: this.options.interruptAfter,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as AgentGraph<StructuredResponseFormat, ContextSchema, TMiddlewares>;\n }\n\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<\n StructuredResponseFormat,\n ContextSchema,\n TMiddlewares\n > {\n return this.#graph;\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[]\n ): (\"tools\" | typeof END)[] {\n const paths: (\"tools\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n /**\n * ToDo: fix type\n */\n return (state: any) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !(lastMessage instanceof AIMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return END;\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node\n */\n return lastMessage.tool_calls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n /**\n * ToDo: fix type\n */\n return (state: any) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? \"model_request\" : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return \"model_request\";\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n #initializeMiddlewareStates(\n state: InvokeStateParameter<TMiddlewares>\n ): InvokeStateParameter<TMiddlewares> {\n if (\n !this.options.middlewares ||\n this.options.middlewares.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = initializeMiddlewareStates(\n this.options.middlewares,\n state\n );\n const updatedState = { ...state } as InvokeStateParameter<TMiddlewares>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n // @ts-expect-error - ToDo: fix type\n updatedState[key as keyof InvokeStateParameter<TMiddlewares>] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * @inheritdoc\n */\n get invoke() {\n type FullState = MergedAgentState<StructuredResponseFormat, TMiddlewares>;\n type FullContext = InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddlewares>;\n\n // Create overloaded function type based on whether context has required fields\n type InvokeFunction = IsAllOptional<FullContext> extends true\n ? (\n state: InvokeStateParameter<TMiddlewares>,\n config?: LangGraphRunnableConfig<FullContext>\n ) => Promise<FullState>\n : (\n state: InvokeStateParameter<TMiddlewares>,\n config?: LangGraphRunnableConfig<FullContext>\n ) => Promise<FullState>;\n\n const invokeFunc: InvokeFunction = async (\n state: InvokeStateParameter<TMiddlewares>,\n config?: LangGraphRunnableConfig<FullContext>\n ): Promise<FullState> => {\n const initializedState = this.#initializeMiddlewareStates(state);\n return this.#graph.invoke(\n initializedState,\n config as any\n ) as Promise<FullState>;\n };\n\n return invokeFunc;\n }\n\n /**\n * ToDo(@christian-bromann): Add stream and streamEvents methods\n */\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;;;;AAgFA,IAAa,aAAb,MAQE;CACA;CAEA,uBAAoC;CAEpC,YACSA,SACP;EADO;EAEP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,QAAQ,OAAO,OAAO,QAAQ,QAAQ,YACxC,2BAA2B,QAAQ,IAAI;;;;AAMzC,MAAI,QAAQ,OAAO,QAAQ,MACzB,OAAM,IAAI,MAAM;;;;AAMlB,MAAI,CAAC,QAAQ,OAAO,CAAC,QAAQ,MAC3B,OAAM,IAAI,MACR;EAIJ,MAAM,eACH,MAAM,QAAQ,QAAQ,MAAM,GAAG,QAAQ,QAAQ,QAAQ,OAAO,UAC/D,CAAE;;;;;EAMJ,MAAM,qBAAqB,IAAI,IAC7B,YACG,OAAO,aAAa,CACpB,OAAO,CAAC,SAAS,kBAAkB,QAAQ,KAAK,aAAa,CAC7D,IAAI,CAAC,SAAS,KAAK,KAAK;EAI7B,MAAM,SAAS,iCAIb,KAAK,QAAQ,mBAAmB,QAChC,KAAK,QAAQ,YACd;EAED,MAAM,WAAW,IAAI,WACnB,QACA,KAAK,QAAQ;EAGf,MAAM,mBAAmB;EAMzB,MAAMC,mBAAsD,CAAE;EAC9D,MAAMC,kBAAqD,CAAE;EAC7D,MAA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,eAAe,EAAE,GAAG,MAAO;AACjC,MAAI,CAAC,aACH,QAAO;AAIT,OAAK,MAAM,CAAC,KAAK,MAAM,IAAI,OAAO,QAAQ,cAAc,CACtD,KAAI,EAAE,OAAO,eAEX,aAAa,OAAmD;AAIpE,SAAO;CACR;;;;CAKD,IAAI,SAAS;EAgBX,MAAMC,aAA6B,OACjCD,OACAE,WACuB;GACvB,MAAM,mBAAmB,KAAKC,4BAA4B,MAAM;AAChE,UAAO,KAAKR,OAAO,OACjB,kBACA,OACD;EACF;AAED,SAAO;CACR;;;;;;;;;;;;;;CAgBD,MAAM,eAAeS,QAMlB;EACD,MAAM,iBAAiB,MAAM,KAAKT,OAAO,eAAe;EACxD,MAAM,QAAQ,MAAM,eAAe,eAAe,OAAO;EACzD,MAAM,cAAc,MAAM,MAAM,aAAa;EAC7C,MAAM,SAAS,IAAI,WAAW;AAC9B,SAAO;CACR;;;;;;;;;;;CAYD,MAAM,YAAYS,QAMf;EACD,MAAM,iBAAiB,MAAM,KAAKT,OAAO,eAAe;AACxD,SAAO,eAAe,YAAY,OAAO;CAC1C;AACF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
|
|
3
|
+
|
|
4
|
+
//#region src/agents/middlewareAgent/annotation.ts
|
|
5
|
+
function createAgentAnnotationConditional(hasStructuredResponse = true, middlewares = []) {
|
|
6
|
+
const baseAnnotation = { messages: (0, __langchain_langgraph.Annotation)({
|
|
7
|
+
reducer: __langchain_langgraph.messagesStateReducer,
|
|
8
|
+
default: () => []
|
|
9
|
+
}) };
|
|
10
|
+
for (const middleware of middlewares) if (middleware.stateSchema) {
|
|
11
|
+
let parsedDefaults = {};
|
|
12
|
+
try {
|
|
13
|
+
parsedDefaults = middleware.stateSchema.parse({});
|
|
14
|
+
} catch {}
|
|
15
|
+
const { shape } = middleware.stateSchema;
|
|
16
|
+
for (const [key] of Object.entries(shape)) {
|
|
17
|
+
/**
|
|
18
|
+
* Skip private state properties
|
|
19
|
+
*/
|
|
20
|
+
if (key.startsWith("_")) continue;
|
|
21
|
+
if (!(key in baseAnnotation)) {
|
|
22
|
+
const defaultValue = parsedDefaults[key] ?? void 0;
|
|
23
|
+
baseAnnotation[key] = (0, __langchain_langgraph.Annotation)({
|
|
24
|
+
reducer: (x, y) => y ?? x,
|
|
25
|
+
default: () => defaultValue
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (!hasStructuredResponse) return __langchain_langgraph.Annotation.Root(baseAnnotation);
|
|
31
|
+
return __langchain_langgraph.Annotation.Root({
|
|
32
|
+
...baseAnnotation,
|
|
33
|
+
structuredResponse: (0, __langchain_langgraph.Annotation)()
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.createAgentAnnotationConditional = createAgentAnnotationConditional;
|
|
39
|
+
//# sourceMappingURL=annotation.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"annotation.cjs","names":["middlewares: TMiddlewares","baseAnnotation: Record<string, any>","messagesStateReducer","parsedDefaults: Record<string, any>","x: any","y: any","Annotation"],"sources":["../../../src/agents/middlewareAgent/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-types */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport {\n Annotation,\n Messages,\n AnnotationRoot,\n messagesStateReducer,\n type BinaryOperatorAggregate,\n type LastValue,\n} from \"@langchain/langgraph\";\nimport type { ResponseFormatUndefined } from \"../responses.js\";\nimport type { AgentMiddleware, InferMiddlewareStates } from \"./types.js\";\n\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\n// Helper type for the merged annotation\ntype MergedAnnotationSpec<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[]\n> = {\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n} & (T extends ResponseFormatUndefined\n ? {}\n : { structuredResponse: LastValue<T> }) &\n InferMiddlewareStates<TMiddlewares>;\n\nexport function createAgentAnnotationConditional<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n middlewares: TMiddlewares = [] as unknown as TMiddlewares\n): AnnotationRoot<MergedAnnotationSpec<T, TMiddlewares>> {\n const baseAnnotation: Record<string, any> = {\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n };\n\n // Add middleware state properties to the annotation\n for (const middleware of middlewares) {\n if (middleware.stateSchema) {\n // Parse empty object to get default values\n let parsedDefaults: Record<string, any> = {};\n try {\n parsedDefaults = middleware.stateSchema.parse({});\n } catch {\n // If parsing fails, we'll use undefined as defaults\n }\n\n const { shape } = middleware.stateSchema;\n for (const [key] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in baseAnnotation)) {\n const defaultValue = parsedDefaults[key] ?? undefined;\n baseAnnotation[key] = Annotation({\n reducer: (x: any, y: any) => y ?? x,\n default: () => defaultValue,\n });\n }\n }\n }\n }\n\n if (!hasStructuredResponse) {\n return Annotation.Root(baseAnnotation) as AnnotationRoot<\n MergedAnnotationSpec<T, TMiddlewares>\n >;\n }\n\n return Annotation.Root({\n ...baseAnnotation,\n structuredResponse:\n Annotation<T extends ResponseFormatUndefined ? never : T>(),\n }) as unknown as AnnotationRoot<MergedAnnotationSpec<T, TMiddlewares>>;\n}\n"],"mappings":";;;;AAyBA,SAAgB,iCAId,wBAAwB,MACxBA,cAA4B,CAAE,GACyB;CACvD,MAAMC,iBAAsC,EAC1C,gDAA8C;EAC5C,SAASC;EACT,SAAS,MAAM,CAAE;CAClB,EAAC,CACH;AAGD,MAAK,MAAM,cAAc,YACvB,KAAI,WAAW,aAAa;EAE1B,IAAIC,iBAAsC,CAAE;AAC5C,MAAI;GACF,iBAAiB,WAAW,YAAY,MAAM,CAAE,EAAC;EAClD,QAAO,CAEP;EAED,MAAM,EAAE,OAAO,GAAG,WAAW;AAC7B,OAAK,MAAM,CAAC,IAAI,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIzC,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,iBAAiB;IAC5B,MAAM,eAAe,eAAe,QAAQ;IAC5C,eAAe,6CAAkB;KAC/B,SAAS,CAACC,GAAQC,MAAW,KAAK;KAClC,SAAS,MAAM;IAChB,EAAC;GACH;EACF;CACF;AAGH,KAAI,CAAC,sBACH,QAAOC,iCAAW,KAAK,eAAe;AAKxC,QAAOA,iCAAW,KAAK;EACrB,GAAG;EACH,2DAC6D;CAC9D,EAAC;AACH"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Annotation, messagesStateReducer } from "@langchain/langgraph";
|
|
2
|
+
|
|
3
|
+
//#region src/agents/middlewareAgent/annotation.ts
|
|
4
|
+
function createAgentAnnotationConditional(hasStructuredResponse = true, middlewares = []) {
|
|
5
|
+
const baseAnnotation = { messages: Annotation({
|
|
6
|
+
reducer: messagesStateReducer,
|
|
7
|
+
default: () => []
|
|
8
|
+
}) };
|
|
9
|
+
for (const middleware of middlewares) if (middleware.stateSchema) {
|
|
10
|
+
let parsedDefaults = {};
|
|
11
|
+
try {
|
|
12
|
+
parsedDefaults = middleware.stateSchema.parse({});
|
|
13
|
+
} catch {}
|
|
14
|
+
const { shape } = middleware.stateSchema;
|
|
15
|
+
for (const [key] of Object.entries(shape)) {
|
|
16
|
+
/**
|
|
17
|
+
* Skip private state properties
|
|
18
|
+
*/
|
|
19
|
+
if (key.startsWith("_")) continue;
|
|
20
|
+
if (!(key in baseAnnotation)) {
|
|
21
|
+
const defaultValue = parsedDefaults[key] ?? void 0;
|
|
22
|
+
baseAnnotation[key] = Annotation({
|
|
23
|
+
reducer: (x, y) => y ?? x,
|
|
24
|
+
default: () => defaultValue
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (!hasStructuredResponse) return Annotation.Root(baseAnnotation);
|
|
30
|
+
return Annotation.Root({
|
|
31
|
+
...baseAnnotation,
|
|
32
|
+
structuredResponse: Annotation()
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { createAgentAnnotationConditional };
|
|
38
|
+
//# sourceMappingURL=annotation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"annotation.js","names":["middlewares: TMiddlewares","baseAnnotation: Record<string, any>","parsedDefaults: Record<string, any>","x: any","y: any"],"sources":["../../../src/agents/middlewareAgent/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-types */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport {\n Annotation,\n Messages,\n AnnotationRoot,\n messagesStateReducer,\n type BinaryOperatorAggregate,\n type LastValue,\n} from \"@langchain/langgraph\";\nimport type { ResponseFormatUndefined } from \"../responses.js\";\nimport type { AgentMiddleware, InferMiddlewareStates } from \"./types.js\";\n\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\n// Helper type for the merged annotation\ntype MergedAnnotationSpec<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[]\n> = {\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n} & (T extends ResponseFormatUndefined\n ? {}\n : { structuredResponse: LastValue<T> }) &\n InferMiddlewareStates<TMiddlewares>;\n\nexport function createAgentAnnotationConditional<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n middlewares: TMiddlewares = [] as unknown as TMiddlewares\n): AnnotationRoot<MergedAnnotationSpec<T, TMiddlewares>> {\n const baseAnnotation: Record<string, any> = {\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n };\n\n // Add middleware state properties to the annotation\n for (const middleware of middlewares) {\n if (middleware.stateSchema) {\n // Parse empty object to get default values\n let parsedDefaults: Record<string, any> = {};\n try {\n parsedDefaults = middleware.stateSchema.parse({});\n } catch {\n // If parsing fails, we'll use undefined as defaults\n }\n\n const { shape } = middleware.stateSchema;\n for (const [key] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in baseAnnotation)) {\n const defaultValue = parsedDefaults[key] ?? undefined;\n baseAnnotation[key] = Annotation({\n reducer: (x: any, y: any) => y ?? x,\n default: () => defaultValue,\n });\n }\n }\n }\n }\n\n if (!hasStructuredResponse) {\n return Annotation.Root(baseAnnotation) as AnnotationRoot<\n MergedAnnotationSpec<T, TMiddlewares>\n >;\n }\n\n return Annotation.Root({\n ...baseAnnotation,\n structuredResponse:\n Annotation<T extends ResponseFormatUndefined ? never : T>(),\n }) as unknown as AnnotationRoot<MergedAnnotationSpec<T, TMiddlewares>>;\n}\n"],"mappings":";;;AAyBA,SAAgB,iCAId,wBAAwB,MACxBA,cAA4B,CAAE,GACyB;CACvD,MAAMC,iBAAsC,EAC1C,UAAU,WAAoC;EAC5C,SAAS;EACT,SAAS,MAAM,CAAE;CAClB,EAAC,CACH;AAGD,MAAK,MAAM,cAAc,YACvB,KAAI,WAAW,aAAa;EAE1B,IAAIC,iBAAsC,CAAE;AAC5C,MAAI;GACF,iBAAiB,WAAW,YAAY,MAAM,CAAE,EAAC;EAClD,QAAO,CAEP;EAED,MAAM,EAAE,OAAO,GAAG,WAAW;AAC7B,OAAK,MAAM,CAAC,IAAI,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIzC,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,iBAAiB;IAC5B,MAAM,eAAe,eAAe,QAAQ;IAC5C,eAAe,OAAO,WAAW;KAC/B,SAAS,CAACC,GAAQC,MAAW,KAAK;KAClC,SAAS,MAAM;IAChB,EAAC;GACH;EACF;CACF;AAGH,KAAI,CAAC,sBACH,QAAO,WAAW,KAAK,eAAe;AAKxC,QAAO,WAAW,KAAK;EACrB,GAAG;EACH,oBACE,YAA2D;CAC9D,EAAC;AACH"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const require_ReactAgent = require('./ReactAgent.cjs');
|
|
2
|
+
const require_middleware = require('./middleware.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/agents/middlewareAgent/index.ts
|
|
5
|
+
function createAgent(params) {
|
|
6
|
+
return new require_ReactAgent.ReactAgent(params);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
exports.createAgent = createAgent;
|
|
11
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>","ReactAgent"],"sources":["../../../src/agents/middlewareAgent/index.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport { type AnyAnnotationRoot } from \"../annotation.js\";\nimport type { CreateAgentParams, AgentMiddleware } from \"./types.js\";\nimport type { ExtractZodArrayTypes } from \"../types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n ResponseFormatUndefined,\n JsonSchemaFormat,\n} from \"../responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * })\n * })\n *\n * const agent = createAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n TMiddlewares\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddlewares>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middlewares?: TMiddlewares;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddlewares>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middlewares?: TMiddlewares;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddlewares>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & { middlewares?: TMiddlewares }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddlewares>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddlewares>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddlewares>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddlewares> {\n return new ReactAgent(params);\n}\n\nexport { createMiddleware } from \"./middleware.js\";\n"],"mappings":";;;;AA4RA,SAAgB,YAKdA,QACmE;AACnE,QAAO,IAAIC,8BAAW;AACvB"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ReactAgent } from "./ReactAgent.js";
|
|
2
|
+
import { createMiddleware } from "./middleware.js";
|
|
3
|
+
|
|
4
|
+
//#region src/agents/middlewareAgent/index.ts
|
|
5
|
+
function createAgent(params) {
|
|
6
|
+
return new ReactAgent(params);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
export { createAgent };
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>"],"sources":["../../../src/agents/middlewareAgent/index.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport { type AnyAnnotationRoot } from \"../annotation.js\";\nimport type { CreateAgentParams, AgentMiddleware } from \"./types.js\";\nimport type { ExtractZodArrayTypes } from \"../types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n ResponseFormatUndefined,\n JsonSchemaFormat,\n} from \"../responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * })\n * })\n *\n * const agent = createAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n TMiddlewares\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddlewares>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middlewares?: TMiddlewares;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddlewares>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middlewares?: TMiddlewares;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddlewares>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<T, ContextSchema, TMiddlewares>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & { middlewares?: TMiddlewares }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddlewares>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddlewares>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middlewares?: TMiddlewares;\n }\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddlewares>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddlewares> {\n return new ReactAgent(params);\n}\n\nexport { createMiddleware } from \"./middleware.js\";\n"],"mappings":";;;;AA4RA,SAAgB,YAKdA,QACmE;AACnE,QAAO,IAAI,WAAW;AACvB"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/agents/middlewareAgent/middleware.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates a middleware instance with automatic schema inference.
|
|
5
|
+
*
|
|
6
|
+
* @param config - Middleware configuration
|
|
7
|
+
* @param config.name - The name of the middleware
|
|
8
|
+
* @param config.stateSchema - The schema of the middleware state
|
|
9
|
+
* @param config.contextSchema - The schema of the middleware context
|
|
10
|
+
* @param config.prepareModelRequest - The function to prepare the model request
|
|
11
|
+
* @param config.beforeModel - The function to run before the model call
|
|
12
|
+
* @param config.afterModel - The function to run after the model call
|
|
13
|
+
* @returns A middleware instance
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const authMiddleware = createMiddleware({
|
|
18
|
+
* name: "AuthMiddleware",
|
|
19
|
+
* stateSchema: z.object({
|
|
20
|
+
* isAuthenticated: z.boolean().default(false),
|
|
21
|
+
* }),
|
|
22
|
+
* contextSchema: z.object({
|
|
23
|
+
* userId: z.string(),
|
|
24
|
+
* }),
|
|
25
|
+
* beforeModel: async (state, runtime, controls) => {
|
|
26
|
+
* if (!state.isAuthenticated) {
|
|
27
|
+
* return controls.terminate(new Error("Not authenticated"));
|
|
28
|
+
* }
|
|
29
|
+
* },
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
function createMiddleware(config) {
|
|
34
|
+
const middleware = {
|
|
35
|
+
name: config.name,
|
|
36
|
+
stateSchema: config.stateSchema,
|
|
37
|
+
contextSchema: config.contextSchema
|
|
38
|
+
};
|
|
39
|
+
if (config.prepareModelRequest) middleware.prepareModelRequest = async (options, state, runtime) => Promise.resolve(config.prepareModelRequest(options, state, runtime));
|
|
40
|
+
if (config.beforeModel) middleware.beforeModel = async (state, runtime, controls) => Promise.resolve(config.beforeModel(state, runtime, controls));
|
|
41
|
+
if (config.afterModel) middleware.afterModel = async (state, runtime, controls) => Promise.resolve(config.afterModel(state, runtime, controls));
|
|
42
|
+
return middleware;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
exports.createMiddleware = createMiddleware;
|
|
47
|
+
//# sourceMappingURL=middleware.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":["config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (\n options: ModelRequest,\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >\n ) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n afterModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../../src/agents/middlewareAgent/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-types */\nimport { z } from \"zod\";\nimport type {\n AgentMiddleware,\n Runtime,\n Controls,\n MiddlewareResult,\n AgentBuiltInState,\n ModelRequest,\n} from \"./types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.prepareModelRequest - The function to prepare the model request\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends z.ZodObject<any> | undefined = undefined,\n TContextSchema extends z.ZodObject<any> | undefined = undefined\n>(config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (\n options: ModelRequest,\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >\n ) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n afterModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n };\n\n if (config.prepareModelRequest) {\n middleware.prepareModelRequest = async (options, state, runtime) =>\n Promise.resolve(config.prepareModelRequest!(options, state, runtime));\n }\n\n if (config.beforeModel) {\n middleware.beforeModel = async (state, runtime, controls) =>\n Promise.resolve(config.beforeModel!(state, runtime, controls));\n }\n\n if (config.afterModel) {\n middleware.afterModel = async (state, runtime, controls) =>\n Promise.resolve(config.afterModel!(state, runtime, controls));\n }\n\n return middleware;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,iBAGdA,QAkDgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;CACvB;AAED,KAAI,OAAO,qBACT,WAAW,sBAAsB,OAAO,SAAS,OAAO,YACtD,QAAQ,QAAQ,OAAO,oBAAqB,SAAS,OAAO,QAAQ,CAAC;AAGzE,KAAI,OAAO,aACT,WAAW,cAAc,OAAO,OAAO,SAAS,aAC9C,QAAQ,QAAQ,OAAO,YAAa,OAAO,SAAS,SAAS,CAAC;AAGlE,KAAI,OAAO,YACT,WAAW,aAAa,OAAO,OAAO,SAAS,aAC7C,QAAQ,QAAQ,OAAO,WAAY,OAAO,SAAS,SAAS,CAAC;AAGjE,QAAO;AACR"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { AgentBuiltInState, AgentMiddleware, Controls, MiddlewareResult, ModelRequest, Runtime } from "./types.cjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/agents/middlewareAgent/middleware.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Creates a middleware instance with automatic schema inference.
|
|
8
|
+
*
|
|
9
|
+
* @param config - Middleware configuration
|
|
10
|
+
* @param config.name - The name of the middleware
|
|
11
|
+
* @param config.stateSchema - The schema of the middleware state
|
|
12
|
+
* @param config.contextSchema - The schema of the middleware context
|
|
13
|
+
* @param config.prepareModelRequest - The function to prepare the model request
|
|
14
|
+
* @param config.beforeModel - The function to run before the model call
|
|
15
|
+
* @param config.afterModel - The function to run after the model call
|
|
16
|
+
* @returns A middleware instance
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const authMiddleware = createMiddleware({
|
|
21
|
+
* name: "AuthMiddleware",
|
|
22
|
+
* stateSchema: z.object({
|
|
23
|
+
* isAuthenticated: z.boolean().default(false),
|
|
24
|
+
* }),
|
|
25
|
+
* contextSchema: z.object({
|
|
26
|
+
* userId: z.string(),
|
|
27
|
+
* }),
|
|
28
|
+
* beforeModel: async (state, runtime, controls) => {
|
|
29
|
+
* if (!state.isAuthenticated) {
|
|
30
|
+
* return controls.terminate(new Error("Not authenticated"));
|
|
31
|
+
* }
|
|
32
|
+
* },
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
declare function createMiddleware<TSchema extends z.ZodObject<any> | undefined = undefined, TContextSchema extends z.ZodObject<any> | undefined = undefined>(config: {
|
|
37
|
+
name: string;
|
|
38
|
+
stateSchema?: TSchema;
|
|
39
|
+
contextSchema?: TContextSchema;
|
|
40
|
+
prepareModelRequest?: (options: ModelRequest, state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}>) => Promise<ModelRequest | void> | ModelRequest | void;
|
|
41
|
+
beforeModel?: (state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>) => Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>> | MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>;
|
|
42
|
+
afterModel?: (state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>) => Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>> | MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>;
|
|
43
|
+
}): AgentMiddleware<TSchema, TContextSchema, any>;
|
|
44
|
+
//#endregion
|
|
45
|
+
export { createMiddleware };
|
|
46
|
+
//# sourceMappingURL=middleware.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.d.cts","names":["z","AgentMiddleware","Runtime","Controls","MiddlewareResult","AgentBuiltInState","ModelRequest","createMiddleware","ZodObject","TSchema","TContextSchema","infer","Promise","Partial"],"sources":["../../../src/agents/middlewareAgent/middleware.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-types */\nimport { z } from \"zod\";\nimport type { AgentMiddleware, Runtime, Controls, MiddlewareResult, AgentBuiltInState, ModelRequest } from \"./types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.prepareModelRequest - The function to prepare the model request\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends z.ZodObject<any> | undefined = undefined, TContextSchema extends z.ZodObject<any> | undefined = undefined>(config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (options: ModelRequest, state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}>) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>) => Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>> | MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>;\n afterModel?: (state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>) => Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>> | MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>;\n}): AgentMiddleware<TSchema, TContextSchema, any>;\n"],"mappings":";;;;;;AAiCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKmHE,iBAL3FK,gBAK2FL,CAAAA,gBAL1DF,CAAAA,CAAEQ,SAKwDN,CAAAA,GAAAA,CAAAA,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,uBALOF,CAAAA,CAAEQ,SAKTN,CAAAA,GAAAA,CAAAA,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,CAAAA,MAAAA,EAAAA;EAAO,IAA8FO,EAAAA,MAAAA;EAAO,WAAWD,CAAAA,EAHxNC,OAGwND;EAAS,aAAgBC,CAAAA,EAF/OC,cAE+OD;EAAO,mBAAbE,CAAAA,EAAAA,CAAAA,OAAAA,EADzNL,YACyNK,EAAAA,KAAAA,EAAAA,CADnMF,OACmME,SADnLX,CAAAA,CAAEQ,SACiLG,CAAAA,GAAAA,CAAAA,GADhKX,CAAAA,CAAEW,KAC8JA,CADxJF,OACwJE,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,GADvIN,iBACuIM,EAAAA,OAAAA,EAD3GT,OAC2GS,CADnGD,cACmGC,SAD5EX,CAAAA,CAAEQ,SAC0EG,CAAAA,GAAAA,CAAAA,GADzDX,CAAAA,CAAEW,KACuDA,CADjDD,cACiDC,CAAAA,GAAA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