@upstash/workflow 0.2.5-agents → 0.2.5-agents-3

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.
@@ -1,6 +1,34 @@
1
- import {
2
- WorkflowAgents
3
- } from "./chunk-PU5J4TNC.mjs";
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
+ ));
4
32
 
5
33
  // src/constants.ts
6
34
  var WORKFLOW_ID_HEADER = "Upstash-Workflow-RunId";
@@ -811,29 +839,16 @@ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
811
839
  await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
812
840
  deletedWorkflowRunId: workflowContext.workflowRunId
813
841
  });
814
- try {
815
- await workflowContext.qstashClient.http.request({
816
- path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
817
- method: "DELETE",
818
- parseResponseAsJson: false
819
- });
820
- await debug?.log(
821
- "SUBMIT",
822
- "SUBMIT_CLEANUP",
823
- `workflow run ${workflowContext.workflowRunId} deleted.`
824
- );
825
- return { deleted: true };
826
- } catch (error) {
827
- if (error instanceof QstashError3 && error.status === 404) {
828
- await debug?.log("WARN", "SUBMIT_CLEANUP", {
829
- message: `Failed to remove workflow run ${workflowContext.workflowRunId} as it doesn't exist.`,
830
- name: error.name,
831
- errorMessage: error.message
832
- });
833
- return { deleted: false };
834
- }
835
- throw error;
836
- }
842
+ await workflowContext.qstashClient.http.request({
843
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
844
+ method: "DELETE",
845
+ parseResponseAsJson: false
846
+ });
847
+ await debug?.log(
848
+ "SUBMIT",
849
+ "SUBMIT_CLEANUP",
850
+ `workflow run ${workflowContext.workflowRunId} deleted.`
851
+ );
837
852
  };
838
853
  var recreateUserHeaders = (headers) => {
839
854
  const filteredHeaders = new Headers();
@@ -1617,6 +1632,303 @@ var WorkflowApi = class extends BaseWorkflowApi {
1617
1632
  }
1618
1633
  };
1619
1634
 
1635
+ // src/agents/adapters.ts
1636
+ import { createOpenAI } from "@ai-sdk/openai";
1637
+ import { tool } from "ai";
1638
+
1639
+ // src/agents/constants.ts
1640
+ var AGENT_NAME_HEADER = "upstash-agent-name";
1641
+ var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
1642
+
1643
+ These other agents have tools available to them.
1644
+
1645
+ Given a prompt, utilize these agents to address requests.
1646
+
1647
+ 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.
1648
+
1649
+ Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
1650
+ you need from that agent.
1651
+ `;
1652
+
1653
+ // src/agents/adapters.ts
1654
+ var createWorkflowOpenAI = (context) => {
1655
+ return createOpenAI({
1656
+ compatibility: "strict",
1657
+ fetch: async (input, init) => {
1658
+ try {
1659
+ const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
1660
+ const body = init?.body ? JSON.parse(init.body) : void 0;
1661
+ const agentName = headers[AGENT_NAME_HEADER];
1662
+ const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
1663
+ const responseInfo = await context.call(stepName, {
1664
+ url: input.toString(),
1665
+ method: init?.method,
1666
+ headers,
1667
+ body
1668
+ });
1669
+ const responseHeaders = new Headers(
1670
+ Object.entries(responseInfo.header).reduce(
1671
+ (acc, [key, values]) => {
1672
+ acc[key] = values.join(", ");
1673
+ return acc;
1674
+ },
1675
+ {}
1676
+ )
1677
+ );
1678
+ return new Response(JSON.stringify(responseInfo.body), {
1679
+ status: responseInfo.status,
1680
+ headers: responseHeaders
1681
+ });
1682
+ } catch (error) {
1683
+ if (error instanceof Error && error.name === "WorkflowAbort") {
1684
+ throw error;
1685
+ } else {
1686
+ console.error("Error in fetch implementation:", error);
1687
+ throw error;
1688
+ }
1689
+ }
1690
+ }
1691
+ });
1692
+ };
1693
+ var wrapTools = ({
1694
+ context,
1695
+ tools
1696
+ }) => {
1697
+ return Object.fromEntries(
1698
+ Object.entries(tools).map((toolInfo) => {
1699
+ const [toolName, tool3] = toolInfo;
1700
+ const aiSDKTool = convertToAISDKTool(tool3);
1701
+ const execute = aiSDKTool.execute;
1702
+ if (execute) {
1703
+ const wrappedExecute = (...params) => {
1704
+ return context.run(`Run tool ${toolName}`, () => execute(...params));
1705
+ };
1706
+ aiSDKTool.execute = wrappedExecute;
1707
+ }
1708
+ return [toolName, aiSDKTool];
1709
+ })
1710
+ );
1711
+ };
1712
+ var convertToAISDKTool = (tool3) => {
1713
+ const isLangchainTool = "invoke" in tool3;
1714
+ return isLangchainTool ? convertLangchainTool(tool3) : tool3;
1715
+ };
1716
+ var convertLangchainTool = (langchainTool) => {
1717
+ return tool({
1718
+ description: langchainTool.description,
1719
+ parameters: langchainTool.schema,
1720
+ execute: async (...param) => langchainTool.invoke(...param)
1721
+ });
1722
+ };
1723
+
1724
+ // src/agents/agent.ts
1725
+ import { z } from "zod";
1726
+ import { generateText, tool as tool2, ToolExecutionError } from "ai";
1727
+
1728
+ // src/serve/utils.ts
1729
+ var isDisabledWorkflowContext = (context) => {
1730
+ return "disabled" in context;
1731
+ };
1732
+
1733
+ // src/agents/agent.ts
1734
+ var Agent = class {
1735
+ name;
1736
+ tools;
1737
+ maxSteps;
1738
+ background;
1739
+ model;
1740
+ temparature;
1741
+ context;
1742
+ constructor({ tools, maxSteps, background, name, model, temparature = 0.1 }, context) {
1743
+ this.name = name;
1744
+ this.tools = tools ?? {};
1745
+ this.maxSteps = maxSteps;
1746
+ this.background = background;
1747
+ this.model = model;
1748
+ this.temparature = temparature;
1749
+ this.context = context;
1750
+ }
1751
+ /**
1752
+ * Trigger the agent by passing a prompt
1753
+ *
1754
+ * @param prompt task to assign to the agent
1755
+ * @returns Response as `{ text: string }`
1756
+ */
1757
+ async call({ prompt }) {
1758
+ try {
1759
+ if (isDisabledWorkflowContext(this.context)) {
1760
+ await this.context.sleep("abort", 0);
1761
+ }
1762
+ const result = await generateText({
1763
+ model: this.model,
1764
+ tools: this.tools,
1765
+ maxSteps: this.maxSteps,
1766
+ system: this.background,
1767
+ prompt,
1768
+ headers: {
1769
+ [AGENT_NAME_HEADER]: this.name
1770
+ },
1771
+ temperature: this.temparature
1772
+ });
1773
+ return { text: result.text };
1774
+ } catch (error) {
1775
+ if (error instanceof ToolExecutionError) {
1776
+ if (error.cause instanceof Error && error.cause.name === "WorkflowAbort") {
1777
+ throw error.cause;
1778
+ } else if (error.cause instanceof ToolExecutionError && error.cause.cause instanceof Error && error.cause.cause.name === "WorkflowAbort") {
1779
+ throw error.cause.cause;
1780
+ } else {
1781
+ throw error;
1782
+ }
1783
+ } else {
1784
+ throw error;
1785
+ }
1786
+ }
1787
+ }
1788
+ /**
1789
+ * Convert the agent to a tool which can be used by other agents.
1790
+ *
1791
+ * @returns the agent as a tool
1792
+ */
1793
+ asTool() {
1794
+ const toolDescriptions = Object.values(this.tools).map((tool3) => tool3.description).join("\n");
1795
+ return tool2({
1796
+ parameters: z.object({ prompt: z.string() }),
1797
+ execute: async ({ prompt }) => {
1798
+ return await this.call({ prompt });
1799
+ },
1800
+ description: `An AI Agent with the following background: ${this.background}Has access to the following tools: ${toolDescriptions}`
1801
+ });
1802
+ }
1803
+ };
1804
+ var ManagerAgent = class extends Agent {
1805
+ agents;
1806
+ /**
1807
+ * A manager agent which coordinates agents available to it to achieve a
1808
+ * given task
1809
+ *
1810
+ * @param name Name of the agent
1811
+ * @param background Background of the agent. If not passed, default will be used.
1812
+ * @param model LLM model to use
1813
+ * @param agents: List of agents available to the agent
1814
+ * @param maxSteps number of times the manager agent can call the LLM at most.
1815
+ * If the agent abruptly stops execution after calling other agents, you may
1816
+ * need to increase maxSteps
1817
+ */
1818
+ constructor({
1819
+ agents,
1820
+ background = MANAGER_AGENT_PROMPT,
1821
+ model,
1822
+ maxSteps,
1823
+ name = "manager llm"
1824
+ }, context) {
1825
+ super(
1826
+ {
1827
+ background,
1828
+ maxSteps,
1829
+ tools: Object.fromEntries(agents.map((agent) => [agent.name, agent.asTool()])),
1830
+ name,
1831
+ model
1832
+ },
1833
+ context
1834
+ );
1835
+ this.agents = agents;
1836
+ }
1837
+ };
1838
+
1839
+ // src/agents/task.ts
1840
+ var Task = class {
1841
+ context;
1842
+ taskParameters;
1843
+ constructor({
1844
+ context,
1845
+ taskParameters
1846
+ }) {
1847
+ this.context = context;
1848
+ this.taskParameters = taskParameters;
1849
+ }
1850
+ /**
1851
+ * Run the agents to complete the task
1852
+ *
1853
+ * @returns Result of the task as { text: string }
1854
+ */
1855
+ async run() {
1856
+ const { prompt, ...otherParams } = this.taskParameters;
1857
+ if ("agent" in otherParams) {
1858
+ const agent = otherParams.agent;
1859
+ const result = await agent.call({
1860
+ prompt
1861
+ });
1862
+ return { text: result.text };
1863
+ } else {
1864
+ const { agents, maxSteps, model, background } = otherParams;
1865
+ const managerAgent = new ManagerAgent(
1866
+ {
1867
+ model,
1868
+ maxSteps,
1869
+ agents,
1870
+ name: "Manager LLM",
1871
+ background
1872
+ },
1873
+ this.context
1874
+ );
1875
+ const result = await managerAgent.call({ prompt });
1876
+ return { text: result.text };
1877
+ }
1878
+ }
1879
+ };
1880
+
1881
+ // src/agents/index.ts
1882
+ var WorkflowAgents = class {
1883
+ context;
1884
+ constructor({ context }) {
1885
+ this.context = context;
1886
+ }
1887
+ /**
1888
+ * Defines an agent
1889
+ *
1890
+ * ```ts
1891
+ * const researcherAgent = context.agents.agent({
1892
+ * model,
1893
+ * name: 'academic',
1894
+ * maxSteps: 2,
1895
+ * tools: {
1896
+ * wikiTool: new WikipediaQueryRun({
1897
+ * topKResults: 1,
1898
+ * maxDocContentLength: 500,
1899
+ * })
1900
+ * },
1901
+ * background:
1902
+ * 'You are researcher agent with access to Wikipedia. ' +
1903
+ * 'Utilize Wikipedia as much as possible for correct information',
1904
+ * });
1905
+ * ```
1906
+ *
1907
+ * @param params agent parameters
1908
+ * @returns
1909
+ */
1910
+ agent(params) {
1911
+ const wrappedTools = wrapTools({ context: this.context, tools: params.tools });
1912
+ return new Agent(
1913
+ {
1914
+ ...params,
1915
+ tools: wrappedTools
1916
+ },
1917
+ this.context
1918
+ );
1919
+ }
1920
+ task(taskParameters) {
1921
+ return new Task({ context: this.context, taskParameters });
1922
+ }
1923
+ /**
1924
+ * creates an openai model for agents
1925
+ */
1926
+ openai(...params) {
1927
+ const openai2 = createWorkflowOpenAI(this.context);
1928
+ return openai2(...params);
1929
+ }
1930
+ };
1931
+
1620
1932
  // src/context/context.ts
1621
1933
  var WorkflowContext = class {
1622
1934
  executor;
@@ -2087,6 +2399,7 @@ function decodeBase64(base64) {
2087
2399
  import { Client as Client2 } from "@upstash/qstash";
2088
2400
  var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
2089
2401
  static disabledMessage = "disabled-qstash-worklfow-run";
2402
+ disabled = true;
2090
2403
  /**
2091
2404
  * overwrite the WorkflowContext.addStep method to always raise WorkflowAbort
2092
2405
  * error in order to stop the execution whenever we encounter a step.
@@ -2211,7 +2524,6 @@ var checkIfLastOneIsDuplicate = async (steps, debug) => {
2211
2524
  if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
2212
2525
  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.`;
2213
2526
  await debug?.log("WARN", "RESPONSE_DEFAULT", message);
2214
- console.log(steps);
2215
2527
  console.warn(message);
2216
2528
  return true;
2217
2529
  }
@@ -2571,6 +2883,9 @@ var serve = (routeFunction, options) => {
2571
2883
  };
2572
2884
 
2573
2885
  export {
2886
+ __require,
2887
+ __commonJS,
2888
+ __toESM,
2574
2889
  makeNotifyRequest,
2575
2890
  makeGetWaitersRequest,
2576
2891
  SDK_TELEMETRY,
package/cloudflare.d.mts CHANGED
@@ -1,8 +1,7 @@
1
- import { R as RouteFunction, j as PublicServeOptions } from './types-BEyIoCRe.mjs';
1
+ import { R as RouteFunction, j as PublicServeOptions } from './types-CalpUeFX.mjs';
2
2
  import '@upstash/qstash';
3
3
  import 'ai';
4
4
  import '@ai-sdk/openai';
5
- import 'langchain/tools';
6
5
 
7
6
  type WorkflowBindings = {
8
7
  QSTASH_TOKEN: string;
package/cloudflare.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- import { R as RouteFunction, j as PublicServeOptions } from './types-BEyIoCRe.js';
1
+ import { R as RouteFunction, j as PublicServeOptions } from './types-CalpUeFX.js';
2
2
  import '@upstash/qstash';
3
3
  import 'ai';
4
4
  import '@ai-sdk/openai';
5
- import 'langchain/tools';
6
5
 
7
6
  type WorkflowBindings = {
8
7
  QSTASH_TOKEN: string;