@upstash/workflow 0.2.5-agent-1 → 0.2.5-agents-2

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/index.mjs CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  makeNotifyRequest,
10
10
  serve,
11
11
  triggerFirstInvocation
12
- } from "./chunk-ETDFMXER.mjs";
12
+ } from "./chunk-VOM3CFYZ.mjs";
13
13
 
14
14
  // src/client/index.ts
15
15
  import { Client as QStashClient } from "@upstash/qstash";
package/nextjs.d.mts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { NextApiHandler } from 'next';
2
- import { R as RouteFunction, j as PublicServeOptions } from './types-Bt4-paRy.mjs';
2
+ import { R as RouteFunction, j as PublicServeOptions } from './types-D9gwTj2n.mjs';
3
3
  import '@upstash/qstash';
4
+ import 'ai';
5
+ import '@ai-sdk/openai';
4
6
 
5
7
  /**
6
8
  * Serve method to serve a Upstash Workflow in a Nextjs project
package/nextjs.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { NextApiHandler } from 'next';
2
- import { R as RouteFunction, j as PublicServeOptions } from './types-Bt4-paRy.js';
2
+ import { R as RouteFunction, j as PublicServeOptions } from './types-D9gwTj2n.js';
3
3
  import '@upstash/qstash';
4
+ import 'ai';
5
+ import '@ai-sdk/openai';
4
6
 
5
7
  /**
6
8
  * Serve method to serve a Upstash Workflow in a Nextjs project
package/nextjs.js CHANGED
@@ -827,29 +827,16 @@ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
827
827
  await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
828
828
  deletedWorkflowRunId: workflowContext.workflowRunId
829
829
  });
830
- try {
831
- await workflowContext.qstashClient.http.request({
832
- path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
833
- method: "DELETE",
834
- parseResponseAsJson: false
835
- });
836
- await debug?.log(
837
- "SUBMIT",
838
- "SUBMIT_CLEANUP",
839
- `workflow run ${workflowContext.workflowRunId} deleted.`
840
- );
841
- return { deleted: true };
842
- } catch (error) {
843
- if (error instanceof import_qstash3.QstashError && error.status === 404) {
844
- await debug?.log("WARN", "SUBMIT_CLEANUP", {
845
- message: `Failed to remove workflow run ${workflowContext.workflowRunId} as it doesn't exist.`,
846
- name: error.name,
847
- errorMessage: error.message
848
- });
849
- return { deleted: false };
850
- }
851
- throw error;
852
- }
830
+ await workflowContext.qstashClient.http.request({
831
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
832
+ method: "DELETE",
833
+ parseResponseAsJson: false
834
+ });
835
+ await debug?.log(
836
+ "SUBMIT",
837
+ "SUBMIT_CLEANUP",
838
+ `workflow run ${workflowContext.workflowRunId} deleted.`
839
+ );
853
840
  };
854
841
  var recreateUserHeaders = (headers) => {
855
842
  const filteredHeaders = new Headers();
@@ -1633,6 +1620,283 @@ var WorkflowApi = class extends BaseWorkflowApi {
1633
1620
  }
1634
1621
  };
1635
1622
 
1623
+ // src/agents/adapters.ts
1624
+ var import_openai2 = require("@ai-sdk/openai");
1625
+ var import_ai = require("ai");
1626
+
1627
+ // src/agents/constants.ts
1628
+ var AGENT_NAME_HEADER = "upstash-agent-name";
1629
+ var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
1630
+
1631
+ These other agents have tools available to them.
1632
+
1633
+ Given a prompt, utilize these agents to address requests.
1634
+
1635
+ 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.
1636
+
1637
+ Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
1638
+ you need from that agent.
1639
+ `;
1640
+
1641
+ // src/agents/adapters.ts
1642
+ var createWorkflowOpenAI = (context) => {
1643
+ return (0, import_openai2.createOpenAI)({
1644
+ compatibility: "strict",
1645
+ fetch: async (input, init) => {
1646
+ try {
1647
+ const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
1648
+ const body = init?.body ? JSON.parse(init.body) : void 0;
1649
+ const agentName = headers[AGENT_NAME_HEADER];
1650
+ const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
1651
+ const responseInfo = await context.call(stepName, {
1652
+ url: input.toString(),
1653
+ method: init?.method,
1654
+ headers,
1655
+ body
1656
+ });
1657
+ const responseHeaders = new Headers(
1658
+ Object.entries(responseInfo.header).reduce(
1659
+ (acc, [key, values]) => {
1660
+ acc[key] = values.join(", ");
1661
+ return acc;
1662
+ },
1663
+ {}
1664
+ )
1665
+ );
1666
+ return new Response(JSON.stringify(responseInfo.body), {
1667
+ status: responseInfo.status,
1668
+ headers: responseHeaders
1669
+ });
1670
+ } catch (error) {
1671
+ if (error instanceof Error && error.name === "WorkflowAbort") {
1672
+ throw error;
1673
+ } else {
1674
+ console.error("Error in fetch implementation:", error);
1675
+ throw error;
1676
+ }
1677
+ }
1678
+ }
1679
+ });
1680
+ };
1681
+ var wrapTools = ({
1682
+ context,
1683
+ tools
1684
+ }) => {
1685
+ return Object.fromEntries(
1686
+ Object.entries(tools).map((toolInfo) => {
1687
+ const [toolName, tool3] = toolInfo;
1688
+ const aiSDKTool = convertToAISDKTool(tool3);
1689
+ const execute = aiSDKTool.execute;
1690
+ if (execute) {
1691
+ const wrappedExecute = (...params) => {
1692
+ return context.run(`Run tool ${toolName}`, () => execute(...params));
1693
+ };
1694
+ aiSDKTool.execute = wrappedExecute;
1695
+ }
1696
+ return [toolName, aiSDKTool];
1697
+ })
1698
+ );
1699
+ };
1700
+ var convertToAISDKTool = (tool3) => {
1701
+ const isLangchainTool = "invoke" in tool3;
1702
+ return isLangchainTool ? convertLangchainTool(tool3) : tool3;
1703
+ };
1704
+ var convertLangchainTool = (langchainTool) => {
1705
+ return (0, import_ai.tool)({
1706
+ description: langchainTool.description,
1707
+ parameters: langchainTool.schema,
1708
+ execute: async (...param) => langchainTool.invoke(...param)
1709
+ });
1710
+ };
1711
+
1712
+ // src/agents/agent.ts
1713
+ var import_zod = require("zod");
1714
+ var import_ai2 = require("ai");
1715
+ var Agent = class {
1716
+ name;
1717
+ tools;
1718
+ maxSteps;
1719
+ background;
1720
+ model;
1721
+ temparature;
1722
+ constructor({ tools, maxSteps, background, name, model, temparature = 0.1 }) {
1723
+ this.name = name;
1724
+ this.tools = tools ?? {};
1725
+ this.maxSteps = maxSteps;
1726
+ this.background = background;
1727
+ this.model = model;
1728
+ this.temparature = temparature;
1729
+ }
1730
+ /**
1731
+ * Trigger the agent by passing a prompt
1732
+ *
1733
+ * @param prompt task to assign to the agent
1734
+ * @returns Response as `{ text: string }`
1735
+ */
1736
+ async call({ prompt }) {
1737
+ try {
1738
+ const result = await (0, import_ai2.generateText)({
1739
+ model: this.model,
1740
+ tools: this.tools,
1741
+ maxSteps: this.maxSteps,
1742
+ system: this.background,
1743
+ prompt,
1744
+ headers: {
1745
+ [AGENT_NAME_HEADER]: this.name
1746
+ },
1747
+ temperature: this.temparature
1748
+ });
1749
+ return { text: result.text };
1750
+ } catch (error) {
1751
+ if (error instanceof import_ai2.ToolExecutionError) {
1752
+ if (error.cause instanceof Error && error.cause.name === "WorkflowAbort") {
1753
+ throw error.cause;
1754
+ } else if (error.cause instanceof import_ai2.ToolExecutionError && error.cause.cause instanceof Error && error.cause.cause.name === "WorkflowAbort") {
1755
+ throw error.cause.cause;
1756
+ } else {
1757
+ throw error;
1758
+ }
1759
+ } else {
1760
+ throw error;
1761
+ }
1762
+ }
1763
+ }
1764
+ /**
1765
+ * Convert the agent to a tool which can be used by other agents.
1766
+ *
1767
+ * @returns the agent as a tool
1768
+ */
1769
+ asTool() {
1770
+ const toolDescriptions = Object.values(this.tools).map((tool3) => tool3.description).join("\n");
1771
+ return (0, import_ai2.tool)({
1772
+ parameters: import_zod.z.object({ prompt: import_zod.z.string() }),
1773
+ execute: async ({ prompt }) => {
1774
+ return await this.call({ prompt });
1775
+ },
1776
+ description: `An AI Agent with the following background: ${this.background}Has access to the following tools: ${toolDescriptions}`
1777
+ });
1778
+ }
1779
+ };
1780
+ var ManagerAgent = class extends Agent {
1781
+ agents;
1782
+ /**
1783
+ * A manager agent which coordinates agents available to it to achieve a
1784
+ * given task
1785
+ *
1786
+ * @param name Name of the agent
1787
+ * @param background Background of the agent. If not passed, default will be used.
1788
+ * @param model LLM model to use
1789
+ * @param agents: List of agents available to the agent
1790
+ * @param maxSteps number of times the manager agent can call the LLM at most.
1791
+ * If the agent abruptly stops execution after calling other agents, you may
1792
+ * need to increase maxSteps
1793
+ */
1794
+ constructor({
1795
+ agents,
1796
+ background = MANAGER_AGENT_PROMPT,
1797
+ model,
1798
+ maxSteps,
1799
+ name = "manager llm"
1800
+ }) {
1801
+ super({
1802
+ background,
1803
+ maxSteps,
1804
+ tools: Object.fromEntries(agents.map((agent) => [agent.name, agent.asTool()])),
1805
+ name,
1806
+ model
1807
+ });
1808
+ this.agents = agents;
1809
+ }
1810
+ };
1811
+
1812
+ // src/agents/task.ts
1813
+ var Task = class {
1814
+ context;
1815
+ taskParameters;
1816
+ constructor({
1817
+ context,
1818
+ taskParameters
1819
+ }) {
1820
+ this.context = context;
1821
+ this.taskParameters = taskParameters;
1822
+ }
1823
+ /**
1824
+ * Run the agents to complete the task
1825
+ *
1826
+ * @returns Result of the task as { text: string }
1827
+ */
1828
+ async run() {
1829
+ const { prompt, ...otherParams } = this.taskParameters;
1830
+ const safePrompt = await this.context.run("Get Prompt", () => prompt);
1831
+ if ("agent" in otherParams) {
1832
+ const agent = otherParams.agent;
1833
+ const result = await agent.call({
1834
+ prompt: safePrompt
1835
+ });
1836
+ return { text: result.text };
1837
+ } else {
1838
+ const { agents, maxSteps, model, background } = otherParams;
1839
+ const managerAgent = new ManagerAgent({
1840
+ model,
1841
+ maxSteps,
1842
+ agents,
1843
+ name: "Manager LLM",
1844
+ background
1845
+ });
1846
+ const result = await managerAgent.call({ prompt: safePrompt });
1847
+ return { text: result.text };
1848
+ }
1849
+ }
1850
+ };
1851
+
1852
+ // src/agents/index.ts
1853
+ var WorkflowAgents = class {
1854
+ context;
1855
+ constructor({ context }) {
1856
+ this.context = context;
1857
+ }
1858
+ /**
1859
+ * Defines an agent
1860
+ *
1861
+ * ```ts
1862
+ * const researcherAgent = context.agents.agent({
1863
+ * model,
1864
+ * name: 'academic',
1865
+ * maxSteps: 2,
1866
+ * tools: {
1867
+ * wikiTool: new WikipediaQueryRun({
1868
+ * topKResults: 1,
1869
+ * maxDocContentLength: 500,
1870
+ * })
1871
+ * },
1872
+ * background:
1873
+ * 'You are researcher agent with access to Wikipedia. ' +
1874
+ * 'Utilize Wikipedia as much as possible for correct information',
1875
+ * });
1876
+ * ```
1877
+ *
1878
+ * @param params agent parameters
1879
+ * @returns
1880
+ */
1881
+ agent(params) {
1882
+ const wrappedTools = wrapTools({ context: this.context, tools: params.tools });
1883
+ return new Agent({
1884
+ ...params,
1885
+ tools: wrappedTools
1886
+ });
1887
+ }
1888
+ task(taskParameters) {
1889
+ return new Task({ context: this.context, taskParameters });
1890
+ }
1891
+ /**
1892
+ * creates an openai model for agents
1893
+ */
1894
+ openai(...params) {
1895
+ const openai2 = createWorkflowOpenAI(this.context);
1896
+ return openai2(...params);
1897
+ }
1898
+ };
1899
+
1636
1900
  // src/context/context.ts
1637
1901
  var WorkflowContext = class {
1638
1902
  executor;
@@ -2018,6 +2282,11 @@ var WorkflowContext = class {
2018
2282
  context: this
2019
2283
  });
2020
2284
  }
2285
+ get agents() {
2286
+ return new WorkflowAgents({
2287
+ context: this
2288
+ });
2289
+ }
2021
2290
  };
2022
2291
 
2023
2292
  // src/logger.ts
package/nextjs.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SDK_TELEMETRY,
3
3
  serveBase
4
- } from "./chunk-ETDFMXER.mjs";
4
+ } from "./chunk-VOM3CFYZ.mjs";
5
5
 
6
6
  // platforms/nextjs.ts
7
7
  var serve = (routeFunction, options) => {
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@upstash/workflow","version":"v0.2.5-agent-1","description":"Durable, Reliable and Performant Serverless Functions","main":"./index.js","module":"./index.mjs","types":"./index.d.ts","files":["./*"],"exports":{".":{"import":"./index.mjs","require":"./index.js"},"./dist/nextjs":{"import":"./nextjs.mjs","require":"./nextjs.js"},"./nextjs":{"import":"./nextjs.mjs","require":"./nextjs.js"},"./h3":{"import":"./h3.mjs","require":"./h3.js"},"./svelte":{"import":"./svelte.mjs","require":"./svelte.js"},"./solidjs":{"import":"./solidjs.mjs","require":"./solidjs.js"},"./workflow":{"import":"./workflow.mjs","require":"./workflow.js"},"./hono":{"import":"./hono.mjs","require":"./hono.js"},"./cloudflare":{"import":"./cloudflare.mjs","require":"./cloudflare.js"},"./astro":{"import":"./astro.mjs","require":"./astro.js"},"./express":{"import":"./express.mjs","require":"./express.js"}},"scripts":{"build":"tsup && cp README.md ./dist/ && cp package.json ./dist/ && cp LICENSE ./dist/","test":"bun test src","fmt":"prettier --write .","lint":"tsc && eslint \"{src,platforms}/**/*.{js,ts,tsx}\" --quiet --fix","check-exports":"bun run build && cd dist && attw -P"},"repository":{"type":"git","url":"git+https://github.com/upstash/workflow-ts.git"},"keywords":["upstash","qstash","workflow","serverless"],"author":"Cahid Arda Oz","license":"MIT","bugs":{"url":"https://github.com/upstash/workflow-ts/issues"},"homepage":"https://github.com/upstash/workflow-ts#readme","devDependencies":{"@commitlint/cli":"^19.5.0","@commitlint/config-conventional":"^19.5.0","@eslint/js":"^9.11.1","@solidjs/start":"^1.0.8","@sveltejs/kit":"^2.6.1","@types/bun":"^1.1.10","@types/express":"^5.0.0","astro":"^4.16.7","eslint":"^9.11.1","eslint-plugin-unicorn":"^55.0.0","express":"^4.21.1","globals":"^15.10.0","h3":"^1.12.0","hono":"^4.6.3","husky":"^9.1.6","next":"^14.2.14","prettier":"3.3.3","tsup":"^8.3.0","typescript":"^5.7.2","typescript-eslint":"^8.18.0"},"dependencies":{"@upstash/qstash":"^2.7.20"},"directories":{"example":"examples"}}
1
+ {"name":"@upstash/workflow","version":"v0.2.5-agents-2","description":"Durable, Reliable and Performant Serverless Functions","main":"./index.js","module":"./index.mjs","types":"./index.d.ts","files":["./*"],"exports":{".":{"import":"./index.mjs","require":"./index.js"},"./dist/nextjs":{"import":"./nextjs.mjs","require":"./nextjs.js"},"./nextjs":{"import":"./nextjs.mjs","require":"./nextjs.js"},"./h3":{"import":"./h3.mjs","require":"./h3.js"},"./svelte":{"import":"./svelte.mjs","require":"./svelte.js"},"./solidjs":{"import":"./solidjs.mjs","require":"./solidjs.js"},"./workflow":{"import":"./workflow.mjs","require":"./workflow.js"},"./hono":{"import":"./hono.mjs","require":"./hono.js"},"./cloudflare":{"import":"./cloudflare.mjs","require":"./cloudflare.js"},"./astro":{"import":"./astro.mjs","require":"./astro.js"},"./express":{"import":"./express.mjs","require":"./express.js"}},"scripts":{"build":"tsup && cp README.md ./dist/ && cp package.json ./dist/ && cp LICENSE ./dist/","test":"bun test src","fmt":"prettier --write .","lint":"tsc && eslint \"{src,platforms}/**/*.{js,ts,tsx}\" --quiet --fix","check-exports":"bun run build && cd dist && attw -P"},"repository":{"type":"git","url":"git+https://github.com/upstash/workflow-ts.git"},"keywords":["upstash","qstash","workflow","serverless"],"author":"Cahid Arda Oz","license":"MIT","bugs":{"url":"https://github.com/upstash/workflow-ts/issues"},"homepage":"https://github.com/upstash/workflow-ts#readme","devDependencies":{"@commitlint/cli":"^19.5.0","@commitlint/config-conventional":"^19.5.0","@eslint/js":"^9.11.1","@solidjs/start":"^1.0.8","@sveltejs/kit":"^2.6.1","@types/bun":"^1.1.10","@types/express":"^5.0.0","astro":"^4.16.7","eslint":"^9.11.1","eslint-plugin-unicorn":"^55.0.0","express":"^4.21.1","globals":"^15.10.0","h3":"^1.12.0","hono":"^4.6.3","husky":"^9.1.6","next":"^14.2.14","prettier":"3.3.3","tsup":"^8.3.0","typescript":"^5.7.2","typescript-eslint":"^8.18.0"},"dependencies":{"@ai-sdk/openai":"^1.0.15","@upstash/qstash":"^2.7.20","ai":"^4.0.30","zod":"^3.24.1"},"directories":{"example":"examples"}}
package/solidjs.d.mts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { APIEvent } from '@solidjs/start/server';
2
- import { R as RouteFunction, j as PublicServeOptions } from './types-Bt4-paRy.mjs';
2
+ import { R as RouteFunction, j as PublicServeOptions } from './types-D9gwTj2n.mjs';
3
3
  import '@upstash/qstash';
4
+ import 'ai';
5
+ import '@ai-sdk/openai';
4
6
 
5
7
  /**
6
8
  * Serve method to serve a Upstash Workflow in a Nextjs project
package/solidjs.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { APIEvent } from '@solidjs/start/server';
2
- import { R as RouteFunction, j as PublicServeOptions } from './types-Bt4-paRy.js';
2
+ import { R as RouteFunction, j as PublicServeOptions } from './types-D9gwTj2n.js';
3
3
  import '@upstash/qstash';
4
+ import 'ai';
5
+ import '@ai-sdk/openai';
4
6
 
5
7
  /**
6
8
  * Serve method to serve a Upstash Workflow in a Nextjs project