@upstash/workflow 0.2.4 → 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/svelte.js CHANGED
@@ -1632,6 +1632,216 @@ var WorkflowApi = class extends BaseWorkflowApi {
1632
1632
  }
1633
1633
  };
1634
1634
 
1635
+ // src/agents/adapters.ts
1636
+ var import_openai2 = require("@ai-sdk/openai");
1637
+ var import_ai = require("ai");
1638
+ var AGENT_NAME_HEADER = "upstash-agent-name";
1639
+ var createWorkflowOpenAI = (context) => {
1640
+ return (0, import_openai2.createOpenAI)({
1641
+ compatibility: "strict",
1642
+ fetch: async (input, init) => {
1643
+ try {
1644
+ const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
1645
+ const body = init?.body ? JSON.parse(init.body) : void 0;
1646
+ const agentName = headers[AGENT_NAME_HEADER];
1647
+ const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
1648
+ const responseInfo = await context.call(stepName, {
1649
+ url: input.toString(),
1650
+ method: init?.method,
1651
+ headers,
1652
+ body
1653
+ });
1654
+ const responseHeaders = new Headers(
1655
+ Object.entries(responseInfo.header).reduce(
1656
+ (acc, [key, values]) => {
1657
+ acc[key] = values.join(", ");
1658
+ return acc;
1659
+ },
1660
+ {}
1661
+ )
1662
+ );
1663
+ return new Response(JSON.stringify(responseInfo.body), {
1664
+ status: responseInfo.status,
1665
+ headers: responseHeaders
1666
+ });
1667
+ } catch (error) {
1668
+ if (error instanceof Error && error.name === "WorkflowAbort") {
1669
+ throw error;
1670
+ } else {
1671
+ console.error("Error in fetch implementation:", error);
1672
+ throw error;
1673
+ }
1674
+ }
1675
+ }
1676
+ });
1677
+ };
1678
+ var wrapTools = ({
1679
+ context,
1680
+ tools
1681
+ }) => {
1682
+ return Object.fromEntries(
1683
+ Object.entries(tools).map((toolInfo) => {
1684
+ const [toolName, tool3] = toolInfo;
1685
+ const aiSDKTool = convertToAISDKTool(tool3);
1686
+ const execute = aiSDKTool.execute;
1687
+ if (execute) {
1688
+ const wrappedExecute = (...params) => {
1689
+ return context.run(`Run tool ${toolName}`, () => execute(...params));
1690
+ };
1691
+ aiSDKTool.execute = wrappedExecute;
1692
+ }
1693
+ return [toolName, aiSDKTool];
1694
+ })
1695
+ );
1696
+ };
1697
+ var convertToAISDKTool = (tool3) => {
1698
+ const isLangchainTool = "invoke" in tool3;
1699
+ return isLangchainTool ? convertLangchainTool(tool3) : tool3;
1700
+ };
1701
+ var convertLangchainTool = (langchainTool) => {
1702
+ return (0, import_ai.tool)({
1703
+ description: langchainTool.description,
1704
+ parameters: langchainTool.schema,
1705
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1706
+ execute: async (param) => langchainTool.invoke(param)
1707
+ });
1708
+ };
1709
+
1710
+ // src/agents/agent.ts
1711
+ var import_zod = require("zod");
1712
+ var import_ai2 = require("ai");
1713
+ var Agent = class {
1714
+ name;
1715
+ tools;
1716
+ maxSteps;
1717
+ background;
1718
+ model;
1719
+ constructor({ tools, maxSteps, background, name, model }) {
1720
+ this.name = name;
1721
+ this.tools = tools ?? {};
1722
+ this.maxSteps = maxSteps;
1723
+ this.background = background;
1724
+ this.model = model;
1725
+ }
1726
+ async call({ prompt }) {
1727
+ try {
1728
+ return await (0, import_ai2.generateText)({
1729
+ model: this.model,
1730
+ tools: this.tools,
1731
+ maxSteps: this.maxSteps,
1732
+ system: this.background,
1733
+ prompt,
1734
+ headers: {
1735
+ [AGENT_NAME_HEADER]: this.name
1736
+ }
1737
+ });
1738
+ } catch (error) {
1739
+ if (error instanceof import_ai2.ToolExecutionError) {
1740
+ if (error.cause instanceof Error && error.cause.name === "WorkflowAbort") {
1741
+ throw error.cause;
1742
+ } else if (error.cause instanceof import_ai2.ToolExecutionError && error.cause.cause instanceof Error && error.cause.cause.name === "WorkflowAbort") {
1743
+ throw error.cause.cause;
1744
+ } else {
1745
+ throw error;
1746
+ }
1747
+ } else {
1748
+ throw error;
1749
+ }
1750
+ }
1751
+ }
1752
+ asTool() {
1753
+ const toolDescriptions = Object.values(this.tools).map((tool3) => tool3.description).join("\n");
1754
+ return (0, import_ai2.tool)({
1755
+ parameters: import_zod.z.object({ prompt: import_zod.z.string() }),
1756
+ execute: async ({ prompt }) => {
1757
+ return await this.call({ prompt });
1758
+ },
1759
+ description: `An AI Agent with the following background: ${this.background}Has access to the following tools: ${toolDescriptions}`
1760
+ });
1761
+ }
1762
+ };
1763
+ var MANAGER_AGENT_PROMPT = `You are an AI agent who orchestrates other AI Agents.
1764
+ These other agents have tools available to them.
1765
+ Given a prompt, utilize these agents to address requests.
1766
+ 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.
1767
+ `;
1768
+ var ManagerAgent = class extends Agent {
1769
+ agents;
1770
+ constructor({
1771
+ maxSteps,
1772
+ background = MANAGER_AGENT_PROMPT,
1773
+ agents,
1774
+ model,
1775
+ name = "manager llm"
1776
+ }) {
1777
+ super({
1778
+ background,
1779
+ maxSteps,
1780
+ tools: Object.fromEntries(agents.map((agent) => [agent.name, agent.asTool()])),
1781
+ name,
1782
+ model
1783
+ });
1784
+ this.agents = agents;
1785
+ }
1786
+ };
1787
+
1788
+ // src/agents/task.ts
1789
+ var Task = class {
1790
+ context;
1791
+ taskParameters;
1792
+ constructor({
1793
+ context,
1794
+ taskParameters
1795
+ }) {
1796
+ this.context = context;
1797
+ this.taskParameters = taskParameters;
1798
+ }
1799
+ async run() {
1800
+ const { prompt, ...otherParams } = this.taskParameters;
1801
+ const safePrompt = await this.context.run("Get Prompt", () => prompt);
1802
+ if ("agent" in otherParams) {
1803
+ const agent = otherParams.agent;
1804
+ const result = await agent.call({
1805
+ prompt: safePrompt
1806
+ });
1807
+ return { text: result.text };
1808
+ } else {
1809
+ const { agents, maxSteps, model, background } = otherParams;
1810
+ const managerAgent = new ManagerAgent({
1811
+ model,
1812
+ maxSteps,
1813
+ agents,
1814
+ name: "Manager LLM",
1815
+ background
1816
+ });
1817
+ const result = await managerAgent.call({ prompt: safePrompt });
1818
+ return { text: result.text };
1819
+ }
1820
+ }
1821
+ };
1822
+
1823
+ // src/agents/index.ts
1824
+ var WorkflowAgents = class {
1825
+ context;
1826
+ constructor({ context }) {
1827
+ this.context = context;
1828
+ }
1829
+ agent(params) {
1830
+ const wrappedTools = wrapTools({ context: this.context, tools: params.tools });
1831
+ return new Agent({
1832
+ ...params,
1833
+ tools: wrappedTools
1834
+ });
1835
+ }
1836
+ task(taskParameters) {
1837
+ return new Task({ context: this.context, taskParameters });
1838
+ }
1839
+ openai(...params) {
1840
+ const openai2 = createWorkflowOpenAI(this.context);
1841
+ return openai2(...params);
1842
+ }
1843
+ };
1844
+
1635
1845
  // src/context/context.ts
1636
1846
  var WorkflowContext = class {
1637
1847
  executor;
@@ -2017,6 +2227,11 @@ var WorkflowContext = class {
2017
2227
  context: this
2018
2228
  });
2019
2229
  }
2230
+ get agents() {
2231
+ return new WorkflowAgents({
2232
+ context: this
2233
+ });
2234
+ }
2020
2235
  };
2021
2236
 
2022
2237
  // src/logger.ts
@@ -2221,6 +2436,7 @@ var checkIfLastOneIsDuplicate = async (steps, debug) => {
2221
2436
  if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
2222
2437
  const message = `Upstash Workflow: The step '${step.stepName}' with id '${step.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;
2223
2438
  await debug?.log("WARN", "RESPONSE_DEFAULT", message);
2439
+ console.log(steps);
2224
2440
  console.warn(message);
2225
2441
  return true;
2226
2442
  }
package/svelte.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  SDK_TELEMETRY,
3
3
  serveBase
4
- } from "./chunk-ETDFMXER.mjs";
4
+ } from "./chunk-RFX5YRRT.mjs";
5
+ import "./chunk-PU5J4TNC.mjs";
5
6
 
6
7
  // platforms/svelte.ts
7
8
  var serve = (routeFunction, options) => {
@@ -1,4 +1,8 @@
1
1
  import { PublishRequest, Client, Receiver, HTTPMethods as HTTPMethods$1 } from '@upstash/qstash';
2
+ import * as ai from 'ai';
3
+ import { CoreTool, generateText } from 'ai';
4
+ import * as _ai_sdk_openai from '@ai-sdk/openai';
5
+ import { Tool } from 'langchain/tools';
2
6
 
3
7
  /**
4
8
  * Base class outlining steps. Basically, each step kind (run/sleep/sleepUntil)
@@ -387,6 +391,76 @@ declare class WorkflowApi extends BaseWorkflowApi {
387
391
  get anthropic(): AnthropicAPI;
388
392
  }
389
393
 
394
+ declare class Agent {
395
+ readonly name: AgentParameters["name"];
396
+ readonly tools: AgentParameters["tools"];
397
+ readonly maxSteps: AgentParameters["maxSteps"];
398
+ readonly background: AgentParameters["background"];
399
+ readonly model: AgentParameters["model"];
400
+ constructor({ tools, maxSteps, background, name, model }: AgentParameters);
401
+ call({ prompt }: {
402
+ prompt: string;
403
+ }): Promise<ai.GenerateTextResult<Record<string, AISDKTool>, never>>;
404
+ asTool(): AISDKTool;
405
+ }
406
+ type ManagerAgentParameters = {
407
+ agents: Agent[];
408
+ model: Model;
409
+ } & Pick<Partial<AgentParameters>, "name" | "background"> & Pick<AgentParameters, "maxSteps">;
410
+ declare class ManagerAgent extends Agent {
411
+ agents: ManagerAgentParameters["agents"];
412
+ constructor({ maxSteps, background, agents, model, name, }: ManagerAgentParameters);
413
+ }
414
+
415
+ type AISDKTool = CoreTool;
416
+ type LangchainTool = Tool;
417
+ type GenerateTextParams = Parameters<typeof generateText>[0];
418
+ type Model = GenerateTextParams["model"];
419
+ type AgentParameters<TTool extends AISDKTool | LangchainTool = AISDKTool> = {
420
+ maxSteps: number;
421
+ background: string;
422
+ tools: Record<string, TTool>;
423
+ name: string;
424
+ model: Model;
425
+ };
426
+ type TaskParams = {
427
+ prompt: string;
428
+ };
429
+ type SingleAgentTaskParams = TaskParams & {
430
+ agent: Agent;
431
+ };
432
+ type MultiAgentTaskParams = TaskParams & {
433
+ agents: Agent[];
434
+ maxSteps: number;
435
+ model: Model;
436
+ background?: string;
437
+ };
438
+
439
+ declare const createWorkflowOpenAI: (context: WorkflowContext) => _ai_sdk_openai.OpenAIProvider;
440
+
441
+ declare class Task {
442
+ private readonly context;
443
+ private readonly taskParameters;
444
+ constructor({ context, taskParameters, }: {
445
+ context: WorkflowContext;
446
+ taskParameters: SingleAgentTaskParams | MultiAgentTaskParams;
447
+ });
448
+ run(): Promise<{
449
+ text: string;
450
+ }>;
451
+ }
452
+
453
+ declare class WorkflowAgents {
454
+ private context;
455
+ constructor({ context }: {
456
+ context: WorkflowContext;
457
+ });
458
+ agent(params: AgentParameters<AISDKTool | LangchainTool>): Agent;
459
+ task(taskParameters: SingleAgentTaskParams): Task;
460
+ task(taskParameters: MultiAgentTaskParams): Task;
461
+ openai(...params: Parameters<ReturnType<typeof createWorkflowOpenAI>>): ai.LanguageModelV1;
462
+ }
463
+
390
464
  /**
391
465
  * Upstash Workflow context
392
466
  *
@@ -682,6 +756,7 @@ declare class WorkflowContext<TInitialPayload = unknown> {
682
756
  */
683
757
  protected addStep<TResult = unknown>(step: BaseLazyStep<TResult>): Promise<TResult>;
684
758
  get api(): WorkflowApi;
759
+ get agents(): WorkflowAgents;
685
760
  }
686
761
 
687
762
  /**
@@ -1057,4 +1132,4 @@ type HeaderParams = {
1057
1132
  callTimeout?: never;
1058
1133
  });
1059
1134
 
1060
- export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type FinishCondition as F, type HeaderParams as H, type LogLevel as L, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type Step as S, type Telemetry as T, type WorkflowServeOptions as W, type Waiter as a, WorkflowContext as b, type WorkflowClient as c, type WorkflowReceiver as d, StepTypes as e, type StepType as f, type RawStep as g, type SyncStepFunction as h, type StepFunction as i, type PublicServeOptions as j, type FailureFunctionPayload as k, type RequiredExceptFields as l, type WaitRequest as m, type WaitStepResponse as n, type NotifyStepResponse as o, type WaitEventOptions as p, type CallSettings as q, type WorkflowLoggerOptions as r, WorkflowLogger as s };
1135
+ export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type FinishCondition as F, type HeaderParams as H, type LogLevel as L, ManagerAgent as M, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type Step as S, type Telemetry as T, type WorkflowServeOptions as W, type Waiter as a, WorkflowContext as b, type WorkflowClient as c, type WorkflowReceiver as d, StepTypes as e, type StepType as f, type RawStep as g, type SyncStepFunction as h, type StepFunction as i, type PublicServeOptions as j, type FailureFunctionPayload as k, type RequiredExceptFields as l, type WaitRequest as m, type WaitStepResponse as n, type NotifyStepResponse as o, type WaitEventOptions as p, type CallSettings as q, type WorkflowLoggerOptions as r, WorkflowLogger as s, WorkflowAgents as t, createWorkflowOpenAI as u, Agent as v };
@@ -1,4 +1,8 @@
1
1
  import { PublishRequest, Client, Receiver, HTTPMethods as HTTPMethods$1 } from '@upstash/qstash';
2
+ import * as ai from 'ai';
3
+ import { CoreTool, generateText } from 'ai';
4
+ import * as _ai_sdk_openai from '@ai-sdk/openai';
5
+ import { Tool } from 'langchain/tools';
2
6
 
3
7
  /**
4
8
  * Base class outlining steps. Basically, each step kind (run/sleep/sleepUntil)
@@ -387,6 +391,76 @@ declare class WorkflowApi extends BaseWorkflowApi {
387
391
  get anthropic(): AnthropicAPI;
388
392
  }
389
393
 
394
+ declare class Agent {
395
+ readonly name: AgentParameters["name"];
396
+ readonly tools: AgentParameters["tools"];
397
+ readonly maxSteps: AgentParameters["maxSteps"];
398
+ readonly background: AgentParameters["background"];
399
+ readonly model: AgentParameters["model"];
400
+ constructor({ tools, maxSteps, background, name, model }: AgentParameters);
401
+ call({ prompt }: {
402
+ prompt: string;
403
+ }): Promise<ai.GenerateTextResult<Record<string, AISDKTool>, never>>;
404
+ asTool(): AISDKTool;
405
+ }
406
+ type ManagerAgentParameters = {
407
+ agents: Agent[];
408
+ model: Model;
409
+ } & Pick<Partial<AgentParameters>, "name" | "background"> & Pick<AgentParameters, "maxSteps">;
410
+ declare class ManagerAgent extends Agent {
411
+ agents: ManagerAgentParameters["agents"];
412
+ constructor({ maxSteps, background, agents, model, name, }: ManagerAgentParameters);
413
+ }
414
+
415
+ type AISDKTool = CoreTool;
416
+ type LangchainTool = Tool;
417
+ type GenerateTextParams = Parameters<typeof generateText>[0];
418
+ type Model = GenerateTextParams["model"];
419
+ type AgentParameters<TTool extends AISDKTool | LangchainTool = AISDKTool> = {
420
+ maxSteps: number;
421
+ background: string;
422
+ tools: Record<string, TTool>;
423
+ name: string;
424
+ model: Model;
425
+ };
426
+ type TaskParams = {
427
+ prompt: string;
428
+ };
429
+ type SingleAgentTaskParams = TaskParams & {
430
+ agent: Agent;
431
+ };
432
+ type MultiAgentTaskParams = TaskParams & {
433
+ agents: Agent[];
434
+ maxSteps: number;
435
+ model: Model;
436
+ background?: string;
437
+ };
438
+
439
+ declare const createWorkflowOpenAI: (context: WorkflowContext) => _ai_sdk_openai.OpenAIProvider;
440
+
441
+ declare class Task {
442
+ private readonly context;
443
+ private readonly taskParameters;
444
+ constructor({ context, taskParameters, }: {
445
+ context: WorkflowContext;
446
+ taskParameters: SingleAgentTaskParams | MultiAgentTaskParams;
447
+ });
448
+ run(): Promise<{
449
+ text: string;
450
+ }>;
451
+ }
452
+
453
+ declare class WorkflowAgents {
454
+ private context;
455
+ constructor({ context }: {
456
+ context: WorkflowContext;
457
+ });
458
+ agent(params: AgentParameters<AISDKTool | LangchainTool>): Agent;
459
+ task(taskParameters: SingleAgentTaskParams): Task;
460
+ task(taskParameters: MultiAgentTaskParams): Task;
461
+ openai(...params: Parameters<ReturnType<typeof createWorkflowOpenAI>>): ai.LanguageModelV1;
462
+ }
463
+
390
464
  /**
391
465
  * Upstash Workflow context
392
466
  *
@@ -682,6 +756,7 @@ declare class WorkflowContext<TInitialPayload = unknown> {
682
756
  */
683
757
  protected addStep<TResult = unknown>(step: BaseLazyStep<TResult>): Promise<TResult>;
684
758
  get api(): WorkflowApi;
759
+ get agents(): WorkflowAgents;
685
760
  }
686
761
 
687
762
  /**
@@ -1057,4 +1132,4 @@ type HeaderParams = {
1057
1132
  callTimeout?: never;
1058
1133
  });
1059
1134
 
1060
- export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type FinishCondition as F, type HeaderParams as H, type LogLevel as L, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type Step as S, type Telemetry as T, type WorkflowServeOptions as W, type Waiter as a, WorkflowContext as b, type WorkflowClient as c, type WorkflowReceiver as d, StepTypes as e, type StepType as f, type RawStep as g, type SyncStepFunction as h, type StepFunction as i, type PublicServeOptions as j, type FailureFunctionPayload as k, type RequiredExceptFields as l, type WaitRequest as m, type WaitStepResponse as n, type NotifyStepResponse as o, type WaitEventOptions as p, type CallSettings as q, type WorkflowLoggerOptions as r, WorkflowLogger as s };
1135
+ export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type FinishCondition as F, type HeaderParams as H, type LogLevel as L, ManagerAgent as M, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type Step as S, type Telemetry as T, type WorkflowServeOptions as W, type Waiter as a, WorkflowContext as b, type WorkflowClient as c, type WorkflowReceiver as d, StepTypes as e, type StepType as f, type RawStep as g, type SyncStepFunction as h, type StepFunction as i, type PublicServeOptions as j, type FailureFunctionPayload as k, type RequiredExceptFields as l, type WaitRequest as m, type WaitStepResponse as n, type NotifyStepResponse as o, type WaitEventOptions as p, type CallSettings as q, type WorkflowLoggerOptions as r, WorkflowLogger as s, WorkflowAgents as t, createWorkflowOpenAI as u, Agent as v };