@upstash/workflow 0.2.3 → 0.2.5-agents

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/astro.mjs CHANGED
@@ -1,12 +1,19 @@
1
1
  import {
2
+ SDK_TELEMETRY,
2
3
  serveBase
3
- } from "./chunk-QBJ3LQIO.mjs";
4
+ } from "./chunk-RFX5YRRT.mjs";
5
+ import "./chunk-PU5J4TNC.mjs";
4
6
 
5
7
  // platforms/astro.ts
6
8
  function serve(routeFunction, options) {
7
9
  const POST = (apiContext) => {
8
10
  const { handler } = serveBase(
9
11
  (workflowContext) => routeFunction(workflowContext, apiContext),
12
+ {
13
+ sdk: SDK_TELEMETRY,
14
+ framework: "astro",
15
+ runtime: process.versions.bun ? `bun@${process.versions.bun}/node@${process.version}` : `node@${process.version}`
16
+ },
10
17
  options
11
18
  );
12
19
  return handler(apiContext.request);
@@ -0,0 +1,251 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/agents/adapters.ts
34
+ import { createOpenAI } from "@ai-sdk/openai";
35
+ import { tool } from "ai";
36
+ var AGENT_NAME_HEADER = "upstash-agent-name";
37
+ var createWorkflowOpenAI = (context) => {
38
+ return createOpenAI({
39
+ compatibility: "strict",
40
+ fetch: async (input, init) => {
41
+ try {
42
+ const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
43
+ const body = init?.body ? JSON.parse(init.body) : void 0;
44
+ const agentName = headers[AGENT_NAME_HEADER];
45
+ const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
46
+ const responseInfo = await context.call(stepName, {
47
+ url: input.toString(),
48
+ method: init?.method,
49
+ headers,
50
+ body
51
+ });
52
+ const responseHeaders = new Headers(
53
+ Object.entries(responseInfo.header).reduce(
54
+ (acc, [key, values]) => {
55
+ acc[key] = values.join(", ");
56
+ return acc;
57
+ },
58
+ {}
59
+ )
60
+ );
61
+ return new Response(JSON.stringify(responseInfo.body), {
62
+ status: responseInfo.status,
63
+ headers: responseHeaders
64
+ });
65
+ } catch (error) {
66
+ if (error instanceof Error && error.name === "WorkflowAbort") {
67
+ throw error;
68
+ } else {
69
+ console.error("Error in fetch implementation:", error);
70
+ throw error;
71
+ }
72
+ }
73
+ }
74
+ });
75
+ };
76
+ var wrapTools = ({
77
+ context,
78
+ tools
79
+ }) => {
80
+ return Object.fromEntries(
81
+ Object.entries(tools).map((toolInfo) => {
82
+ const [toolName, tool3] = toolInfo;
83
+ const aiSDKTool = convertToAISDKTool(tool3);
84
+ const execute = aiSDKTool.execute;
85
+ if (execute) {
86
+ const wrappedExecute = (...params) => {
87
+ return context.run(`Run tool ${toolName}`, () => execute(...params));
88
+ };
89
+ aiSDKTool.execute = wrappedExecute;
90
+ }
91
+ return [toolName, aiSDKTool];
92
+ })
93
+ );
94
+ };
95
+ var convertToAISDKTool = (tool3) => {
96
+ const isLangchainTool = "invoke" in tool3;
97
+ return isLangchainTool ? convertLangchainTool(tool3) : tool3;
98
+ };
99
+ var convertLangchainTool = (langchainTool) => {
100
+ return tool({
101
+ description: langchainTool.description,
102
+ parameters: langchainTool.schema,
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
+ execute: async (param) => langchainTool.invoke(param)
105
+ });
106
+ };
107
+
108
+ // src/agents/agent.ts
109
+ import { z } from "zod";
110
+ import { generateText, tool as tool2, ToolExecutionError } from "ai";
111
+ var Agent = class {
112
+ name;
113
+ tools;
114
+ maxSteps;
115
+ background;
116
+ model;
117
+ constructor({ tools, maxSteps, background, name, model }) {
118
+ this.name = name;
119
+ this.tools = tools ?? {};
120
+ this.maxSteps = maxSteps;
121
+ this.background = background;
122
+ this.model = model;
123
+ }
124
+ async call({ prompt }) {
125
+ try {
126
+ return await generateText({
127
+ model: this.model,
128
+ tools: this.tools,
129
+ maxSteps: this.maxSteps,
130
+ system: this.background,
131
+ prompt,
132
+ headers: {
133
+ [AGENT_NAME_HEADER]: this.name
134
+ }
135
+ });
136
+ } catch (error) {
137
+ if (error instanceof ToolExecutionError) {
138
+ if (error.cause instanceof Error && error.cause.name === "WorkflowAbort") {
139
+ throw error.cause;
140
+ } else if (error.cause instanceof ToolExecutionError && error.cause.cause instanceof Error && error.cause.cause.name === "WorkflowAbort") {
141
+ throw error.cause.cause;
142
+ } else {
143
+ throw error;
144
+ }
145
+ } else {
146
+ throw error;
147
+ }
148
+ }
149
+ }
150
+ asTool() {
151
+ const toolDescriptions = Object.values(this.tools).map((tool3) => tool3.description).join("\n");
152
+ return tool2({
153
+ parameters: z.object({ prompt: z.string() }),
154
+ execute: async ({ prompt }) => {
155
+ return await this.call({ prompt });
156
+ },
157
+ description: `An AI Agent with the following background: ${this.background}Has access to the following tools: ${toolDescriptions}`
158
+ });
159
+ }
160
+ };
161
+ var MANAGER_AGENT_PROMPT = `You are an AI agent who orchestrates other AI Agents.
162
+ These other agents have tools available to them.
163
+ Given a prompt, utilize these agents to address requests.
164
+ Don't always call all the agents provided to you at the same time. You can call one and use it's response to call another.
165
+ `;
166
+ var ManagerAgent = class extends Agent {
167
+ agents;
168
+ constructor({
169
+ maxSteps,
170
+ background = MANAGER_AGENT_PROMPT,
171
+ agents,
172
+ model,
173
+ name = "manager llm"
174
+ }) {
175
+ super({
176
+ background,
177
+ maxSteps,
178
+ tools: Object.fromEntries(agents.map((agent) => [agent.name, agent.asTool()])),
179
+ name,
180
+ model
181
+ });
182
+ this.agents = agents;
183
+ }
184
+ };
185
+
186
+ // src/agents/task.ts
187
+ var Task = class {
188
+ context;
189
+ taskParameters;
190
+ constructor({
191
+ context,
192
+ taskParameters
193
+ }) {
194
+ this.context = context;
195
+ this.taskParameters = taskParameters;
196
+ }
197
+ async run() {
198
+ const { prompt, ...otherParams } = this.taskParameters;
199
+ const safePrompt = await this.context.run("Get Prompt", () => prompt);
200
+ if ("agent" in otherParams) {
201
+ const agent = otherParams.agent;
202
+ const result = await agent.call({
203
+ prompt: safePrompt
204
+ });
205
+ return { text: result.text };
206
+ } else {
207
+ const { agents, maxSteps, model, background } = otherParams;
208
+ const managerAgent = new ManagerAgent({
209
+ model,
210
+ maxSteps,
211
+ agents,
212
+ name: "Manager LLM",
213
+ background
214
+ });
215
+ const result = await managerAgent.call({ prompt: safePrompt });
216
+ return { text: result.text };
217
+ }
218
+ }
219
+ };
220
+
221
+ // src/agents/index.ts
222
+ var WorkflowAgents = class {
223
+ context;
224
+ constructor({ context }) {
225
+ this.context = context;
226
+ }
227
+ agent(params) {
228
+ const wrappedTools = wrapTools({ context: this.context, tools: params.tools });
229
+ return new Agent({
230
+ ...params,
231
+ tools: wrappedTools
232
+ });
233
+ }
234
+ task(taskParameters) {
235
+ return new Task({ context: this.context, taskParameters });
236
+ }
237
+ openai(...params) {
238
+ const openai = createWorkflowOpenAI(this.context);
239
+ return openai(...params);
240
+ }
241
+ };
242
+
243
+ export {
244
+ __require,
245
+ __commonJS,
246
+ __toESM,
247
+ createWorkflowOpenAI,
248
+ Agent,
249
+ ManagerAgent,
250
+ WorkflowAgents
251
+ };