@upstash/workflow 0.2.22 → 0.3.0-rc

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.
@@ -97,12 +97,11 @@ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
97
97
  var DEFAULT_CONTENT_TYPE = "application/json";
98
98
  var NO_CONCURRENCY = 1;
99
99
  var DEFAULT_RETRIES = 3;
100
- var VERSION = "v0.2.22";
100
+ var VERSION = "v0.3.0-rc";
101
101
  var SDK_TELEMETRY = `@upstash/workflow@${VERSION}`;
102
102
  var TELEMETRY_HEADER_SDK = "Upstash-Telemetry-Sdk";
103
103
  var TELEMETRY_HEADER_FRAMEWORK = "Upstash-Telemetry-Framework";
104
104
  var TELEMETRY_HEADER_RUNTIME = "Upstash-Telemetry-Runtime";
105
- var TELEMETRY_HEADER_AGENT = "Upstash-Telemetry-Agent";
106
105
 
107
106
  // src/types.ts
108
107
  var StepTypes = [
@@ -116,137 +115,6 @@ var StepTypes = [
116
115
  "Invoke"
117
116
  ];
118
117
 
119
- // src/agents/adapters.ts
120
- import { tool } from "ai";
121
-
122
- // src/agents/constants.ts
123
- var AGENT_NAME_HEADER = "upstash-agent-name";
124
- var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
125
-
126
- These other agents have tools available to them.
127
-
128
- Given a prompt, utilize these agents to address requests.
129
-
130
- 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.
131
-
132
- Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
133
- you need from that agent.
134
- `;
135
-
136
- // src/agents/adapters.ts
137
- var fetchWithContextCall = async (context, agentCallParams, ...params) => {
138
- const [input, init] = params;
139
- try {
140
- const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
141
- const body = init?.body ? JSON.parse(init.body) : void 0;
142
- const agentName = headers[AGENT_NAME_HEADER];
143
- const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
144
- const responseInfo = await context.call(stepName, {
145
- url: input.toString(),
146
- method: init?.method,
147
- headers,
148
- body,
149
- timeout: agentCallParams?.timeout,
150
- retries: agentCallParams?.retries,
151
- retryDelay: agentCallParams?.retryDelay,
152
- flowControl: agentCallParams?.flowControl
153
- });
154
- const responseHeaders = new Headers(
155
- Object.entries(responseInfo.header).reduce(
156
- (acc, [key, values]) => {
157
- acc[key] = values.join(", ");
158
- return acc;
159
- },
160
- {}
161
- )
162
- );
163
- return new Response(JSON.stringify(responseInfo.body), {
164
- status: responseInfo.status,
165
- headers: responseHeaders
166
- });
167
- } catch (error) {
168
- if (error instanceof Error && isInstanceOf(error, WorkflowAbort)) {
169
- throw error;
170
- } else {
171
- console.error("Error in fetch implementation:", error);
172
- throw error;
173
- }
174
- }
175
- };
176
- var createWorkflowModel = ({
177
- context,
178
- provider,
179
- providerParams,
180
- agentCallParams
181
- }) => {
182
- return provider({
183
- fetch: (...params) => fetchWithContextCall(context, agentCallParams, ...params),
184
- ...providerParams
185
- });
186
- };
187
- var wrapTools = ({
188
- context,
189
- tools
190
- }) => {
191
- return Object.fromEntries(
192
- Object.entries(tools).map((toolInfo) => {
193
- const [toolName, tool3] = toolInfo;
194
- const executeAsStep = "executeAsStep" in tool3 ? tool3.executeAsStep : true;
195
- const aiSDKTool = convertToAISDKTool(tool3);
196
- const execute = aiSDKTool.execute;
197
- if (execute && executeAsStep) {
198
- const wrappedExecute = (...params) => {
199
- return context.run(`Run tool ${toolName}`, () => execute(...params));
200
- };
201
- aiSDKTool.execute = wrappedExecute;
202
- }
203
- return [toolName, aiSDKTool];
204
- })
205
- );
206
- };
207
- var convertToAISDKTool = (tool3) => {
208
- const isLangchainTool = "invoke" in tool3;
209
- return isLangchainTool ? convertLangchainTool(tool3) : tool3;
210
- };
211
- var convertLangchainTool = (langchainTool) => {
212
- return tool({
213
- description: langchainTool.description,
214
- parameters: langchainTool.schema,
215
- execute: async (...param) => langchainTool.invoke(...param)
216
- });
217
- };
218
- var WorkflowTool = class {
219
- /**
220
- * description of the tool
221
- */
222
- description;
223
- /**
224
- * schema of the tool
225
- */
226
- schema;
227
- /**
228
- * function to invoke the tool
229
- */
230
- invoke;
231
- /**
232
- * whether the invoke method of the tool is to be wrapped with `context.run`
233
- */
234
- executeAsStep;
235
- /**
236
- *
237
- * @param description description of the tool
238
- * @param schema schema of the tool
239
- * @param invoke function to invoke the tool
240
- * @param executeAsStep whether the invoke method of the tool is to be wrapped with `context.run`
241
- */
242
- constructor(params) {
243
- this.description = params.description;
244
- this.schema = params.schema;
245
- this.invoke = params.invoke;
246
- this.executeAsStep = params.executeAsStep ?? true;
247
- }
248
- };
249
-
250
118
  // src/serve/serve-many.ts
251
119
  var getWorkflowId = (url) => {
252
120
  const components = url.split("/");
@@ -753,9 +621,9 @@ var Ok = class {
753
621
  }
754
622
  safeUnwrap() {
755
623
  const value = this.value;
756
- return function* () {
624
+ return (function* () {
757
625
  return value;
758
- }();
626
+ })();
759
627
  }
760
628
  _unsafeUnwrap(_) {
761
629
  return this.value;
@@ -814,10 +682,10 @@ var Err = class {
814
682
  }
815
683
  safeUnwrap() {
816
684
  const error = this.error;
817
- return function* () {
685
+ return (function* () {
818
686
  yield err(error);
819
687
  throw new Error("Do not use this generator out of `safeTry`");
820
- }();
688
+ })();
821
689
  }
822
690
  _unsafeUnwrap(config) {
823
691
  throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
@@ -1820,8 +1688,7 @@ var WorkflowHeaders = class {
1820
1688
  [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
1821
1689
  [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody,WF_DetectTrigger" + (this.keepTriggerConfig ? ",WF_TriggerOnConfig" : ""),
1822
1690
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1823
- ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {},
1824
- ...this.workflowConfig.telemetry && this.stepInfo?.lazyStep instanceof LazyCallStep && this.stepInfo.lazyStep.headers[AGENT_NAME_HEADER] ? { [TELEMETRY_HEADER_AGENT]: "true" } : {}
1691
+ ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1825
1692
  };
1826
1693
  if (this.stepInfo?.lazyStep.stepType !== "Call") {
1827
1694
  this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
@@ -2484,225 +2351,6 @@ var WorkflowApi = class extends BaseWorkflowApi {
2484
2351
  }
2485
2352
  };
2486
2353
 
2487
- // src/agents/index.ts
2488
- import { createOpenAI } from "@ai-sdk/openai";
2489
-
2490
- // src/agents/agent.ts
2491
- import { z } from "zod";
2492
- import { generateText, tool as tool2, ToolExecutionError } from "ai";
2493
-
2494
- // src/serve/utils.ts
2495
- var isDisabledWorkflowContext = (context) => {
2496
- return "disabled" in context;
2497
- };
2498
-
2499
- // src/agents/agent.ts
2500
- var Agent = class {
2501
- name;
2502
- tools;
2503
- maxSteps;
2504
- background;
2505
- model;
2506
- temparature;
2507
- context;
2508
- constructor({ tools, maxSteps, background, name, model, temparature = 0.1 }, context) {
2509
- this.name = name;
2510
- this.tools = tools ?? {};
2511
- this.maxSteps = maxSteps;
2512
- this.background = background;
2513
- this.model = model;
2514
- this.temparature = temparature;
2515
- this.context = context;
2516
- }
2517
- /**
2518
- * Trigger the agent by passing a prompt
2519
- *
2520
- * @param prompt task to assign to the agent
2521
- * @returns Response as `{ text: string }`
2522
- */
2523
- async call({ prompt }) {
2524
- try {
2525
- if (isDisabledWorkflowContext(this.context)) {
2526
- await this.context.sleep("abort", 0);
2527
- }
2528
- const result = await generateText({
2529
- model: this.model,
2530
- tools: this.tools,
2531
- maxSteps: this.maxSteps,
2532
- system: this.background,
2533
- prompt,
2534
- headers: {
2535
- [AGENT_NAME_HEADER]: this.name
2536
- },
2537
- temperature: this.temparature
2538
- });
2539
- return { text: result.text };
2540
- } catch (error) {
2541
- if (isInstanceOf(error, ToolExecutionError)) {
2542
- if (error.cause instanceof Error && isInstanceOf(error.cause, WorkflowAbort)) {
2543
- throw error.cause;
2544
- } else if (isInstanceOf(error.cause, ToolExecutionError) && isInstanceOf(error.cause.cause, WorkflowAbort)) {
2545
- throw error.cause.cause;
2546
- } else {
2547
- throw error;
2548
- }
2549
- } else {
2550
- throw error;
2551
- }
2552
- }
2553
- }
2554
- /**
2555
- * Convert the agent to a tool which can be used by other agents.
2556
- *
2557
- * @returns the agent as a tool
2558
- */
2559
- asTool() {
2560
- const toolDescriptions = Object.values(this.tools).map((tool3) => tool3.description).join("\n");
2561
- return tool2({
2562
- parameters: z.object({ prompt: z.string() }),
2563
- execute: async ({ prompt }) => {
2564
- return await this.call({ prompt });
2565
- },
2566
- description: `An AI Agent with the following background: ${this.background}Has access to the following tools: ${toolDescriptions}`
2567
- });
2568
- }
2569
- };
2570
- var ManagerAgent = class extends Agent {
2571
- agents;
2572
- /**
2573
- * A manager agent which coordinates agents available to it to achieve a
2574
- * given task
2575
- *
2576
- * @param name Name of the agent
2577
- * @param background Background of the agent. If not passed, default will be used.
2578
- * @param model LLM model to use
2579
- * @param agents: List of agents available to the agent
2580
- * @param maxSteps number of times the manager agent can call the LLM at most.
2581
- * If the agent abruptly stops execution after calling other agents, you may
2582
- * need to increase maxSteps
2583
- */
2584
- constructor({
2585
- agents,
2586
- background = MANAGER_AGENT_PROMPT,
2587
- model,
2588
- maxSteps,
2589
- name = "manager llm"
2590
- }, context) {
2591
- super(
2592
- {
2593
- background,
2594
- maxSteps,
2595
- tools: Object.fromEntries(agents.map((agent) => [agent.name, agent.asTool()])),
2596
- name,
2597
- model
2598
- },
2599
- context
2600
- );
2601
- this.agents = agents;
2602
- }
2603
- };
2604
-
2605
- // src/agents/task.ts
2606
- var Task = class {
2607
- context;
2608
- taskParameters;
2609
- constructor({
2610
- context,
2611
- taskParameters
2612
- }) {
2613
- this.context = context;
2614
- this.taskParameters = taskParameters;
2615
- }
2616
- /**
2617
- * Run the agents to complete the task
2618
- *
2619
- * @returns Result of the task as { text: string }
2620
- */
2621
- async run() {
2622
- const { prompt, ...otherParams } = this.taskParameters;
2623
- if ("agent" in otherParams) {
2624
- const agent = otherParams.agent;
2625
- const result = await agent.call({
2626
- prompt
2627
- });
2628
- return { text: result.text };
2629
- } else {
2630
- const { agents, maxSteps, model, background } = otherParams;
2631
- const managerAgent = new ManagerAgent(
2632
- {
2633
- model,
2634
- maxSteps,
2635
- agents,
2636
- name: "Manager LLM",
2637
- background
2638
- },
2639
- this.context
2640
- );
2641
- const result = await managerAgent.call({ prompt });
2642
- return { text: result.text };
2643
- }
2644
- }
2645
- };
2646
-
2647
- // src/agents/index.ts
2648
- var WorkflowAgents = class {
2649
- context;
2650
- constructor({ context }) {
2651
- this.context = context;
2652
- }
2653
- /**
2654
- * Defines an agent
2655
- *
2656
- * ```ts
2657
- * const researcherAgent = context.agents.agent({
2658
- * model,
2659
- * name: 'academic',
2660
- * maxSteps: 2,
2661
- * tools: {
2662
- * wikiTool: new WikipediaQueryRun({
2663
- * topKResults: 1,
2664
- * maxDocContentLength: 500,
2665
- * })
2666
- * },
2667
- * background:
2668
- * 'You are researcher agent with access to Wikipedia. ' +
2669
- * 'Utilize Wikipedia as much as possible for correct information',
2670
- * });
2671
- * ```
2672
- *
2673
- * @param params agent parameters
2674
- * @returns
2675
- */
2676
- agent(params) {
2677
- const wrappedTools = wrapTools({ context: this.context, tools: params.tools });
2678
- return new Agent(
2679
- {
2680
- ...params,
2681
- tools: wrappedTools
2682
- },
2683
- this.context
2684
- );
2685
- }
2686
- task(taskParameters) {
2687
- return new Task({ context: this.context, taskParameters });
2688
- }
2689
- /**
2690
- * creates an openai model for agents
2691
- */
2692
- openai(...params) {
2693
- const [model, settings] = params;
2694
- const { baseURL, apiKey, callSettings, ...otherSettings } = settings ?? {};
2695
- const openaiModel = this.AISDKModel({
2696
- context: this.context,
2697
- provider: createOpenAI,
2698
- providerParams: { baseURL, apiKey, compatibility: "strict" },
2699
- agentCallParams: callSettings
2700
- });
2701
- return openaiModel(model, otherSettings);
2702
- }
2703
- AISDKModel = createWorkflowModel;
2704
- };
2705
-
2706
2354
  // src/context/context.ts
2707
2355
  var WorkflowContext = class {
2708
2356
  executor;
@@ -2936,7 +2584,7 @@ var WorkflowContext = class {
2936
2584
  * @returns result of the step function
2937
2585
  */
2938
2586
  async run(stepName, stepFunction) {
2939
- const wrappedStepFunction = () => this.executor.wrapStep(stepName, stepFunction);
2587
+ const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
2940
2588
  return await this.addStep(new LazyFunctionStep(stepName, wrappedStepFunction));
2941
2589
  }
2942
2590
  /**
@@ -3107,11 +2755,6 @@ var WorkflowContext = class {
3107
2755
  context: this
3108
2756
  });
3109
2757
  }
3110
- get agents() {
3111
- return new WorkflowAgents({
3112
- context: this
3113
- });
3114
- }
3115
2758
  };
3116
2759
 
3117
2760
  // src/logger.ts
@@ -3778,7 +3421,6 @@ export {
3778
3421
  StepTypes,
3779
3422
  triggerFirstInvocation,
3780
3423
  prepareFlowControl,
3781
- WorkflowTool,
3782
3424
  serveManyBase,
3783
3425
  WorkflowContext,
3784
3426
  WorkflowLogger,
package/cloudflare.d.mts CHANGED
@@ -1,9 +1,7 @@
1
- import { R as RouteFunction, o as PublicServeOptions, z as InvokableWorkflow } from './types-9nCq6bRP.mjs';
2
- import { s as serveManyBase } from './serve-many-CctdYIfB.mjs';
1
+ import { R as RouteFunction, n as PublicServeOptions, y as InvokableWorkflow } from './types-DESkn7K9.mjs';
2
+ import { s as serveManyBase } from './serve-many-DEwKPF6H.mjs';
3
3
  import '@upstash/qstash';
4
4
  import 'zod';
5
- import 'ai';
6
- import '@ai-sdk/openai';
7
5
 
8
6
  type WorkflowBindings = {
9
7
  QSTASH_TOKEN: string;
@@ -35,7 +33,7 @@ type WorkersHandlerArgs = [Request, Record<string, string | undefined>];
35
33
  declare const serve: <TInitialPayload = unknown, TResult = unknown>(routeFunction: RouteFunction<TInitialPayload, TResult>, options?: PublicServeOptions<TInitialPayload>) => {
36
34
  fetch: (...args: PagesHandlerArgs | WorkersHandlerArgs) => Promise<Response>;
37
35
  };
38
- declare const createWorkflow: <TInitialPayload, TResult>(routeFunction: RouteFunction<TInitialPayload, TResult>, options?: PublicServeOptions<TInitialPayload> | undefined) => InvokableWorkflow<TInitialPayload, TResult>;
36
+ declare const createWorkflow: <TInitialPayload, TResult>(...params: Parameters<typeof serve<TInitialPayload, TResult>>) => InvokableWorkflow<TInitialPayload, TResult>;
39
37
  declare const serveMany: (workflows: Parameters<typeof serveManyBase>[0]["workflows"], options?: Parameters<typeof serveManyBase>[0]["options"]) => {
40
38
  fetch: (...params: PagesHandlerArgs | WorkersHandlerArgs) => Promise<any>;
41
39
  };
package/cloudflare.d.ts CHANGED
@@ -1,9 +1,7 @@
1
- import { R as RouteFunction, o as PublicServeOptions, z as InvokableWorkflow } from './types-9nCq6bRP.js';
2
- import { s as serveManyBase } from './serve-many-BXDr30rl.js';
1
+ import { R as RouteFunction, n as PublicServeOptions, y as InvokableWorkflow } from './types-DESkn7K9.js';
2
+ import { s as serveManyBase } from './serve-many-DVtHRxeg.js';
3
3
  import '@upstash/qstash';
4
4
  import 'zod';
5
- import 'ai';
6
- import '@ai-sdk/openai';
7
5
 
8
6
  type WorkflowBindings = {
9
7
  QSTASH_TOKEN: string;
@@ -35,7 +33,7 @@ type WorkersHandlerArgs = [Request, Record<string, string | undefined>];
35
33
  declare const serve: <TInitialPayload = unknown, TResult = unknown>(routeFunction: RouteFunction<TInitialPayload, TResult>, options?: PublicServeOptions<TInitialPayload>) => {
36
34
  fetch: (...args: PagesHandlerArgs | WorkersHandlerArgs) => Promise<Response>;
37
35
  };
38
- declare const createWorkflow: <TInitialPayload, TResult>(routeFunction: RouteFunction<TInitialPayload, TResult>, options?: PublicServeOptions<TInitialPayload> | undefined) => InvokableWorkflow<TInitialPayload, TResult>;
36
+ declare const createWorkflow: <TInitialPayload, TResult>(...params: Parameters<typeof serve<TInitialPayload, TResult>>) => InvokableWorkflow<TInitialPayload, TResult>;
39
37
  declare const serveMany: (workflows: Parameters<typeof serveManyBase>[0]["workflows"], options?: Parameters<typeof serveManyBase>[0]["options"]) => {
40
38
  fetch: (...params: PagesHandlerArgs | WorkersHandlerArgs) => Promise<any>;
41
39
  };