@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/express.mjs CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  __require,
5
5
  __toESM,
6
6
  serveBase
7
- } from "./chunk-ETDFMXER.mjs";
7
+ } from "./chunk-VOM3CFYZ.mjs";
8
8
 
9
9
  // node_modules/depd/index.js
10
10
  var require_depd = __commonJS({
package/h3.d.mts CHANGED
@@ -1,6 +1,8 @@
1
1
  import * as h3 from 'h3';
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
  declare const serve: <TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, options?: PublicServeOptions<TInitialPayload>) => {
6
8
  handler: h3.EventHandler<h3.EventHandlerRequest, Promise<Response | {
package/h3.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import * as h3 from 'h3';
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
  declare const serve: <TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, options?: PublicServeOptions<TInitialPayload>) => {
6
8
  handler: h3.EventHandler<h3.EventHandlerRequest, Promise<Response | {
package/h3.js CHANGED
@@ -1138,29 +1138,16 @@ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
1138
1138
  await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
1139
1139
  deletedWorkflowRunId: workflowContext.workflowRunId
1140
1140
  });
1141
- try {
1142
- await workflowContext.qstashClient.http.request({
1143
- path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
1144
- method: "DELETE",
1145
- parseResponseAsJson: false
1146
- });
1147
- await debug?.log(
1148
- "SUBMIT",
1149
- "SUBMIT_CLEANUP",
1150
- `workflow run ${workflowContext.workflowRunId} deleted.`
1151
- );
1152
- return { deleted: true };
1153
- } catch (error) {
1154
- if (error instanceof import_qstash3.QstashError && error.status === 404) {
1155
- await debug?.log("WARN", "SUBMIT_CLEANUP", {
1156
- message: `Failed to remove workflow run ${workflowContext.workflowRunId} as it doesn't exist.`,
1157
- name: error.name,
1158
- errorMessage: error.message
1159
- });
1160
- return { deleted: false };
1161
- }
1162
- throw error;
1163
- }
1141
+ await workflowContext.qstashClient.http.request({
1142
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
1143
+ method: "DELETE",
1144
+ parseResponseAsJson: false
1145
+ });
1146
+ await debug?.log(
1147
+ "SUBMIT",
1148
+ "SUBMIT_CLEANUP",
1149
+ `workflow run ${workflowContext.workflowRunId} deleted.`
1150
+ );
1164
1151
  };
1165
1152
  var recreateUserHeaders = (headers) => {
1166
1153
  const filteredHeaders = new Headers();
@@ -1944,6 +1931,283 @@ var WorkflowApi = class extends BaseWorkflowApi {
1944
1931
  }
1945
1932
  };
1946
1933
 
1934
+ // src/agents/adapters.ts
1935
+ var import_openai2 = require("@ai-sdk/openai");
1936
+ var import_ai = require("ai");
1937
+
1938
+ // src/agents/constants.ts
1939
+ var AGENT_NAME_HEADER = "upstash-agent-name";
1940
+ var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
1941
+
1942
+ These other agents have tools available to them.
1943
+
1944
+ Given a prompt, utilize these agents to address requests.
1945
+
1946
+ 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.
1947
+
1948
+ Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
1949
+ you need from that agent.
1950
+ `;
1951
+
1952
+ // src/agents/adapters.ts
1953
+ var createWorkflowOpenAI = (context) => {
1954
+ return (0, import_openai2.createOpenAI)({
1955
+ compatibility: "strict",
1956
+ fetch: async (input, init) => {
1957
+ try {
1958
+ const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
1959
+ const body = init?.body ? JSON.parse(init.body) : void 0;
1960
+ const agentName = headers[AGENT_NAME_HEADER];
1961
+ const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
1962
+ const responseInfo = await context.call(stepName, {
1963
+ url: input.toString(),
1964
+ method: init?.method,
1965
+ headers,
1966
+ body
1967
+ });
1968
+ const responseHeaders = new Headers(
1969
+ Object.entries(responseInfo.header).reduce(
1970
+ (acc, [key, values]) => {
1971
+ acc[key] = values.join(", ");
1972
+ return acc;
1973
+ },
1974
+ {}
1975
+ )
1976
+ );
1977
+ return new Response(JSON.stringify(responseInfo.body), {
1978
+ status: responseInfo.status,
1979
+ headers: responseHeaders
1980
+ });
1981
+ } catch (error) {
1982
+ if (error instanceof Error && error.name === "WorkflowAbort") {
1983
+ throw error;
1984
+ } else {
1985
+ console.error("Error in fetch implementation:", error);
1986
+ throw error;
1987
+ }
1988
+ }
1989
+ }
1990
+ });
1991
+ };
1992
+ var wrapTools = ({
1993
+ context,
1994
+ tools
1995
+ }) => {
1996
+ return Object.fromEntries(
1997
+ Object.entries(tools).map((toolInfo) => {
1998
+ const [toolName, tool3] = toolInfo;
1999
+ const aiSDKTool = convertToAISDKTool(tool3);
2000
+ const execute = aiSDKTool.execute;
2001
+ if (execute) {
2002
+ const wrappedExecute = (...params) => {
2003
+ return context.run(`Run tool ${toolName}`, () => execute(...params));
2004
+ };
2005
+ aiSDKTool.execute = wrappedExecute;
2006
+ }
2007
+ return [toolName, aiSDKTool];
2008
+ })
2009
+ );
2010
+ };
2011
+ var convertToAISDKTool = (tool3) => {
2012
+ const isLangchainTool = "invoke" in tool3;
2013
+ return isLangchainTool ? convertLangchainTool(tool3) : tool3;
2014
+ };
2015
+ var convertLangchainTool = (langchainTool) => {
2016
+ return (0, import_ai.tool)({
2017
+ description: langchainTool.description,
2018
+ parameters: langchainTool.schema,
2019
+ execute: async (...param) => langchainTool.invoke(...param)
2020
+ });
2021
+ };
2022
+
2023
+ // src/agents/agent.ts
2024
+ var import_zod = require("zod");
2025
+ var import_ai2 = require("ai");
2026
+ var Agent = class {
2027
+ name;
2028
+ tools;
2029
+ maxSteps;
2030
+ background;
2031
+ model;
2032
+ temparature;
2033
+ constructor({ tools, maxSteps, background, name, model, temparature = 0.1 }) {
2034
+ this.name = name;
2035
+ this.tools = tools ?? {};
2036
+ this.maxSteps = maxSteps;
2037
+ this.background = background;
2038
+ this.model = model;
2039
+ this.temparature = temparature;
2040
+ }
2041
+ /**
2042
+ * Trigger the agent by passing a prompt
2043
+ *
2044
+ * @param prompt task to assign to the agent
2045
+ * @returns Response as `{ text: string }`
2046
+ */
2047
+ async call({ prompt }) {
2048
+ try {
2049
+ const result = await (0, import_ai2.generateText)({
2050
+ model: this.model,
2051
+ tools: this.tools,
2052
+ maxSteps: this.maxSteps,
2053
+ system: this.background,
2054
+ prompt,
2055
+ headers: {
2056
+ [AGENT_NAME_HEADER]: this.name
2057
+ },
2058
+ temperature: this.temparature
2059
+ });
2060
+ return { text: result.text };
2061
+ } catch (error) {
2062
+ if (error instanceof import_ai2.ToolExecutionError) {
2063
+ if (error.cause instanceof Error && error.cause.name === "WorkflowAbort") {
2064
+ throw error.cause;
2065
+ } else if (error.cause instanceof import_ai2.ToolExecutionError && error.cause.cause instanceof Error && error.cause.cause.name === "WorkflowAbort") {
2066
+ throw error.cause.cause;
2067
+ } else {
2068
+ throw error;
2069
+ }
2070
+ } else {
2071
+ throw error;
2072
+ }
2073
+ }
2074
+ }
2075
+ /**
2076
+ * Convert the agent to a tool which can be used by other agents.
2077
+ *
2078
+ * @returns the agent as a tool
2079
+ */
2080
+ asTool() {
2081
+ const toolDescriptions = Object.values(this.tools).map((tool3) => tool3.description).join("\n");
2082
+ return (0, import_ai2.tool)({
2083
+ parameters: import_zod.z.object({ prompt: import_zod.z.string() }),
2084
+ execute: async ({ prompt }) => {
2085
+ return await this.call({ prompt });
2086
+ },
2087
+ description: `An AI Agent with the following background: ${this.background}Has access to the following tools: ${toolDescriptions}`
2088
+ });
2089
+ }
2090
+ };
2091
+ var ManagerAgent = class extends Agent {
2092
+ agents;
2093
+ /**
2094
+ * A manager agent which coordinates agents available to it to achieve a
2095
+ * given task
2096
+ *
2097
+ * @param name Name of the agent
2098
+ * @param background Background of the agent. If not passed, default will be used.
2099
+ * @param model LLM model to use
2100
+ * @param agents: List of agents available to the agent
2101
+ * @param maxSteps number of times the manager agent can call the LLM at most.
2102
+ * If the agent abruptly stops execution after calling other agents, you may
2103
+ * need to increase maxSteps
2104
+ */
2105
+ constructor({
2106
+ agents,
2107
+ background = MANAGER_AGENT_PROMPT,
2108
+ model,
2109
+ maxSteps,
2110
+ name = "manager llm"
2111
+ }) {
2112
+ super({
2113
+ background,
2114
+ maxSteps,
2115
+ tools: Object.fromEntries(agents.map((agent) => [agent.name, agent.asTool()])),
2116
+ name,
2117
+ model
2118
+ });
2119
+ this.agents = agents;
2120
+ }
2121
+ };
2122
+
2123
+ // src/agents/task.ts
2124
+ var Task = class {
2125
+ context;
2126
+ taskParameters;
2127
+ constructor({
2128
+ context,
2129
+ taskParameters
2130
+ }) {
2131
+ this.context = context;
2132
+ this.taskParameters = taskParameters;
2133
+ }
2134
+ /**
2135
+ * Run the agents to complete the task
2136
+ *
2137
+ * @returns Result of the task as { text: string }
2138
+ */
2139
+ async run() {
2140
+ const { prompt, ...otherParams } = this.taskParameters;
2141
+ const safePrompt = await this.context.run("Get Prompt", () => prompt);
2142
+ if ("agent" in otherParams) {
2143
+ const agent = otherParams.agent;
2144
+ const result = await agent.call({
2145
+ prompt: safePrompt
2146
+ });
2147
+ return { text: result.text };
2148
+ } else {
2149
+ const { agents, maxSteps, model, background } = otherParams;
2150
+ const managerAgent = new ManagerAgent({
2151
+ model,
2152
+ maxSteps,
2153
+ agents,
2154
+ name: "Manager LLM",
2155
+ background
2156
+ });
2157
+ const result = await managerAgent.call({ prompt: safePrompt });
2158
+ return { text: result.text };
2159
+ }
2160
+ }
2161
+ };
2162
+
2163
+ // src/agents/index.ts
2164
+ var WorkflowAgents = class {
2165
+ context;
2166
+ constructor({ context }) {
2167
+ this.context = context;
2168
+ }
2169
+ /**
2170
+ * Defines an agent
2171
+ *
2172
+ * ```ts
2173
+ * const researcherAgent = context.agents.agent({
2174
+ * model,
2175
+ * name: 'academic',
2176
+ * maxSteps: 2,
2177
+ * tools: {
2178
+ * wikiTool: new WikipediaQueryRun({
2179
+ * topKResults: 1,
2180
+ * maxDocContentLength: 500,
2181
+ * })
2182
+ * },
2183
+ * background:
2184
+ * 'You are researcher agent with access to Wikipedia. ' +
2185
+ * 'Utilize Wikipedia as much as possible for correct information',
2186
+ * });
2187
+ * ```
2188
+ *
2189
+ * @param params agent parameters
2190
+ * @returns
2191
+ */
2192
+ agent(params) {
2193
+ const wrappedTools = wrapTools({ context: this.context, tools: params.tools });
2194
+ return new Agent({
2195
+ ...params,
2196
+ tools: wrappedTools
2197
+ });
2198
+ }
2199
+ task(taskParameters) {
2200
+ return new Task({ context: this.context, taskParameters });
2201
+ }
2202
+ /**
2203
+ * creates an openai model for agents
2204
+ */
2205
+ openai(...params) {
2206
+ const openai2 = createWorkflowOpenAI(this.context);
2207
+ return openai2(...params);
2208
+ }
2209
+ };
2210
+
1947
2211
  // src/context/context.ts
1948
2212
  var WorkflowContext = class {
1949
2213
  executor;
@@ -2329,6 +2593,11 @@ var WorkflowContext = class {
2329
2593
  context: this
2330
2594
  });
2331
2595
  }
2596
+ get agents() {
2597
+ return new WorkflowAgents({
2598
+ context: this
2599
+ });
2600
+ }
2332
2601
  };
2333
2602
 
2334
2603
  // src/logger.ts
package/h3.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
  // node_modules/defu/dist/defu.mjs
7
7
  function isPlainObject(value) {
package/hono.d.mts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { Context } from 'hono';
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 { Variables } from 'hono/types';
4
4
  import '@upstash/qstash';
5
+ import 'ai';
6
+ import '@ai-sdk/openai';
5
7
 
6
8
  type WorkflowBindings = {
7
9
  QSTASH_TOKEN: string;
package/hono.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { Context } from 'hono';
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 { Variables } from 'hono/types';
4
4
  import '@upstash/qstash';
5
+ import 'ai';
6
+ import '@ai-sdk/openai';
5
7
 
6
8
  type WorkflowBindings = {
7
9
  QSTASH_TOKEN: string;