@copilotkit/runtime 0.0.0-feat-dynamic-copilotcloud-qa-20250117190454
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/.eslintrc.js +7 -0
- package/CHANGELOG.md +913 -0
- package/README.md +46 -0
- package/__snapshots__/schema/schema.graphql +273 -0
- package/dist/chunk-44O2JGUY.mjs +12 -0
- package/dist/chunk-44O2JGUY.mjs.map +1 -0
- package/dist/chunk-BETLEV37.mjs +25 -0
- package/dist/chunk-BETLEV37.mjs.map +1 -0
- package/dist/chunk-CLGKEUOA.mjs +1408 -0
- package/dist/chunk-CLGKEUOA.mjs.map +1 -0
- package/dist/chunk-D2WLFQS6.mjs +43 -0
- package/dist/chunk-D2WLFQS6.mjs.map +1 -0
- package/dist/chunk-DFOKBSIS.mjs +1 -0
- package/dist/chunk-DFOKBSIS.mjs.map +1 -0
- package/dist/chunk-FA5DJ2TZ.mjs +3437 -0
- package/dist/chunk-FA5DJ2TZ.mjs.map +1 -0
- package/dist/chunk-HNUNXFTW.mjs +129 -0
- package/dist/chunk-HNUNXFTW.mjs.map +1 -0
- package/dist/chunk-SFLMY3ES.mjs +80 -0
- package/dist/chunk-SFLMY3ES.mjs.map +1 -0
- package/dist/chunk-U3V2BCGI.mjs +152 -0
- package/dist/chunk-U3V2BCGI.mjs.map +1 -0
- package/dist/chunk-ZCU6UPCY.mjs +25 -0
- package/dist/chunk-ZCU6UPCY.mjs.map +1 -0
- package/dist/copilot-runtime-1a224a0f.d.ts +196 -0
- package/dist/graphql/types/base/index.d.ts +6 -0
- package/dist/graphql/types/base/index.js +63 -0
- package/dist/graphql/types/base/index.js.map +1 -0
- package/dist/graphql/types/base/index.mjs +8 -0
- package/dist/graphql/types/base/index.mjs.map +1 -0
- package/dist/graphql/types/converted/index.d.ts +2 -0
- package/dist/graphql/types/converted/index.js +187 -0
- package/dist/graphql/types/converted/index.js.map +1 -0
- package/dist/graphql/types/converted/index.mjs +17 -0
- package/dist/graphql/types/converted/index.mjs.map +1 -0
- package/dist/groq-adapter-c35c5374.d.ts +281 -0
- package/dist/index-24315d90.d.ts +103 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +5258 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +76 -0
- package/dist/index.mjs.map +1 -0
- package/dist/langserve-a16ef8f4.d.ts +180 -0
- package/dist/lib/cloud/index.d.ts +6 -0
- package/dist/lib/cloud/index.js +18 -0
- package/dist/lib/cloud/index.js.map +1 -0
- package/dist/lib/cloud/index.mjs +1 -0
- package/dist/lib/cloud/index.mjs.map +1 -0
- package/dist/lib/index.d.ts +20 -0
- package/dist/lib/index.js +4906 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/index.mjs +58 -0
- package/dist/lib/index.mjs.map +1 -0
- package/dist/lib/integrations/index.d.ts +33 -0
- package/dist/lib/integrations/index.js +2229 -0
- package/dist/lib/integrations/index.js.map +1 -0
- package/dist/lib/integrations/index.mjs +34 -0
- package/dist/lib/integrations/index.mjs.map +1 -0
- package/dist/lib/integrations/nest/index.d.ts +14 -0
- package/dist/lib/integrations/nest/index.js +2138 -0
- package/dist/lib/integrations/nest/index.js.map +1 -0
- package/dist/lib/integrations/nest/index.mjs +13 -0
- package/dist/lib/integrations/nest/index.mjs.map +1 -0
- package/dist/lib/integrations/node-express/index.d.ts +14 -0
- package/dist/lib/integrations/node-express/index.js +2138 -0
- package/dist/lib/integrations/node-express/index.js.map +1 -0
- package/dist/lib/integrations/node-express/index.mjs +13 -0
- package/dist/lib/integrations/node-express/index.mjs.map +1 -0
- package/dist/lib/integrations/node-http/index.d.ts +14 -0
- package/dist/lib/integrations/node-http/index.js +2124 -0
- package/dist/lib/integrations/node-http/index.js.map +1 -0
- package/dist/lib/integrations/node-http/index.mjs +12 -0
- package/dist/lib/integrations/node-http/index.mjs.map +1 -0
- package/dist/service-adapters/index.d.ts +84 -0
- package/dist/service-adapters/index.js +1448 -0
- package/dist/service-adapters/index.js.map +1 -0
- package/dist/service-adapters/index.mjs +26 -0
- package/dist/service-adapters/index.mjs.map +1 -0
- package/dist/utils/index.d.ts +49 -0
- package/dist/utils/index.js +174 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/index.mjs +12 -0
- package/dist/utils/index.mjs.map +1 -0
- package/jest.config.js +5 -0
- package/package.json +85 -0
- package/scripts/generate-gql-schema.ts +13 -0
- package/src/agents/langgraph/event-source.ts +287 -0
- package/src/agents/langgraph/events.ts +338 -0
- package/src/graphql/inputs/action.input.ts +16 -0
- package/src/graphql/inputs/agent-session.input.ts +13 -0
- package/src/graphql/inputs/agent-state.input.ts +10 -0
- package/src/graphql/inputs/cloud-guardrails.input.ts +16 -0
- package/src/graphql/inputs/cloud.input.ts +8 -0
- package/src/graphql/inputs/context-property.input.ts +10 -0
- package/src/graphql/inputs/custom-property.input.ts +15 -0
- package/src/graphql/inputs/forwarded-parameters.input.ts +22 -0
- package/src/graphql/inputs/frontend.input.ts +14 -0
- package/src/graphql/inputs/generate-copilot-response.input.ts +47 -0
- package/src/graphql/inputs/message.input.ts +92 -0
- package/src/graphql/resolvers/copilot.resolver.ts +556 -0
- package/src/graphql/types/agents-response.type.ts +22 -0
- package/src/graphql/types/base/index.ts +10 -0
- package/src/graphql/types/converted/index.ts +136 -0
- package/src/graphql/types/copilot-response.type.ts +113 -0
- package/src/graphql/types/enums.ts +37 -0
- package/src/graphql/types/guardrails-result.type.ts +20 -0
- package/src/graphql/types/message-status.type.ts +40 -0
- package/src/graphql/types/response-status.type.ts +66 -0
- package/src/index.ts +4 -0
- package/src/lib/cloud/index.ts +4 -0
- package/src/lib/index.ts +8 -0
- package/src/lib/integrations/index.ts +6 -0
- package/src/lib/integrations/nest/index.ts +17 -0
- package/src/lib/integrations/nextjs/app-router.ts +40 -0
- package/src/lib/integrations/nextjs/pages-router.ts +49 -0
- package/src/lib/integrations/node-express/index.ts +17 -0
- package/src/lib/integrations/node-http/index.ts +34 -0
- package/src/lib/integrations/shared.ts +109 -0
- package/src/lib/logger.ts +28 -0
- package/src/lib/runtime/copilot-runtime.ts +466 -0
- package/src/lib/runtime/remote-action-constructors.ts +304 -0
- package/src/lib/runtime/remote-actions.ts +174 -0
- package/src/lib/runtime/remote-lg-action.ts +657 -0
- package/src/lib/telemetry-client.ts +52 -0
- package/src/service-adapters/anthropic/anthropic-adapter.ts +205 -0
- package/src/service-adapters/anthropic/utils.ts +144 -0
- package/src/service-adapters/conversion.ts +64 -0
- package/src/service-adapters/events.ts +419 -0
- package/src/service-adapters/experimental/empty/empty-adapter.ts +33 -0
- package/src/service-adapters/experimental/ollama/ollama-adapter.ts +79 -0
- package/src/service-adapters/google/google-genai-adapter.ts +39 -0
- package/src/service-adapters/groq/groq-adapter.ts +173 -0
- package/src/service-adapters/index.ts +16 -0
- package/src/service-adapters/langchain/langchain-adapter.ts +99 -0
- package/src/service-adapters/langchain/langserve.ts +87 -0
- package/src/service-adapters/langchain/types.ts +14 -0
- package/src/service-adapters/langchain/utils.ts +306 -0
- package/src/service-adapters/openai/openai-adapter.ts +210 -0
- package/src/service-adapters/openai/openai-assistant-adapter.ts +304 -0
- package/src/service-adapters/openai/utils.ts +161 -0
- package/src/service-adapters/service-adapter.ts +30 -0
- package/src/service-adapters/unify/unify-adapter.ts +145 -0
- package/src/utils/failed-response-status-reasons.ts +48 -0
- package/src/utils/index.ts +1 -0
- package/tsconfig.json +11 -0
- package/tsup.config.ts +16 -0
- package/typedoc.json +4 -0
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
import { Arg, Ctx, Mutation, Query, Resolver } from "type-graphql";
|
|
2
|
+
import {
|
|
3
|
+
ReplaySubject,
|
|
4
|
+
Subject,
|
|
5
|
+
Subscription,
|
|
6
|
+
filter,
|
|
7
|
+
finalize,
|
|
8
|
+
firstValueFrom,
|
|
9
|
+
shareReplay,
|
|
10
|
+
skipWhile,
|
|
11
|
+
take,
|
|
12
|
+
takeWhile,
|
|
13
|
+
tap,
|
|
14
|
+
} from "rxjs";
|
|
15
|
+
import { GenerateCopilotResponseInput } from "../inputs/generate-copilot-response.input";
|
|
16
|
+
import { CopilotResponse } from "../types/copilot-response.type";
|
|
17
|
+
import { ActionInputAvailability, MessageRole } from "../types/enums";
|
|
18
|
+
import { Repeater } from "graphql-yoga";
|
|
19
|
+
import type { CopilotRequestContextProperties, GraphQLContext } from "../../lib/integrations";
|
|
20
|
+
import { RuntimeEvent, RuntimeEventTypes } from "../../service-adapters/events";
|
|
21
|
+
import {
|
|
22
|
+
FailedMessageStatus,
|
|
23
|
+
MessageStatusUnion,
|
|
24
|
+
SuccessMessageStatus,
|
|
25
|
+
} from "../types/message-status.type";
|
|
26
|
+
import { ResponseStatusUnion, SuccessResponseStatus } from "../types/response-status.type";
|
|
27
|
+
import { GraphQLJSONObject } from "graphql-scalars";
|
|
28
|
+
import { plainToInstance } from "class-transformer";
|
|
29
|
+
import { GuardrailsResult } from "../types/guardrails-result.type";
|
|
30
|
+
import { GraphQLError } from "graphql";
|
|
31
|
+
import {
|
|
32
|
+
GuardrailsValidationFailureResponse,
|
|
33
|
+
MessageStreamInterruptedResponse,
|
|
34
|
+
UnknownErrorResponse,
|
|
35
|
+
} from "../../utils";
|
|
36
|
+
import {
|
|
37
|
+
ActionExecutionMessage,
|
|
38
|
+
AgentStateMessage,
|
|
39
|
+
Message,
|
|
40
|
+
ResultMessage,
|
|
41
|
+
TextMessage,
|
|
42
|
+
} from "../types/converted";
|
|
43
|
+
import telemetry from "../../lib/telemetry-client";
|
|
44
|
+
import { randomId } from "@copilotkit/shared";
|
|
45
|
+
import { EndpointType, LangGraphPlatformAgent } from "../../lib/runtime/remote-actions";
|
|
46
|
+
import { AgentsResponse } from "../types/agents-response.type";
|
|
47
|
+
|
|
48
|
+
const invokeGuardrails = async ({
|
|
49
|
+
baseUrl,
|
|
50
|
+
copilotCloudPublicApiKey,
|
|
51
|
+
data,
|
|
52
|
+
onResult,
|
|
53
|
+
onError,
|
|
54
|
+
}: {
|
|
55
|
+
baseUrl: string;
|
|
56
|
+
copilotCloudPublicApiKey: string;
|
|
57
|
+
data: GenerateCopilotResponseInput;
|
|
58
|
+
onResult: (result: GuardrailsResult) => void;
|
|
59
|
+
onError: (err: Error) => void;
|
|
60
|
+
}) => {
|
|
61
|
+
if (
|
|
62
|
+
data.messages.length &&
|
|
63
|
+
data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user
|
|
64
|
+
) {
|
|
65
|
+
const messages = data.messages
|
|
66
|
+
.filter(
|
|
67
|
+
(m) =>
|
|
68
|
+
m.textMessage !== undefined &&
|
|
69
|
+
(m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),
|
|
70
|
+
)
|
|
71
|
+
.map((m) => ({
|
|
72
|
+
role: m.textMessage!.role,
|
|
73
|
+
content: m.textMessage.content,
|
|
74
|
+
}));
|
|
75
|
+
|
|
76
|
+
const lastMessage = messages[messages.length - 1];
|
|
77
|
+
const restOfMessages = messages.slice(0, -1);
|
|
78
|
+
|
|
79
|
+
const body = {
|
|
80
|
+
input: lastMessage.content,
|
|
81
|
+
validTopics: data.cloud.guardrails.inputValidationRules.allowList,
|
|
82
|
+
invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,
|
|
83
|
+
messages: restOfMessages,
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: {
|
|
89
|
+
"Content-Type": "application/json",
|
|
90
|
+
"X-CopilotCloud-Public-API-Key": copilotCloudPublicApiKey,
|
|
91
|
+
},
|
|
92
|
+
body: JSON.stringify(body),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
if (guardrailsResult.ok) {
|
|
96
|
+
const resultJson: GuardrailsResult = await guardrailsResult.json();
|
|
97
|
+
onResult(resultJson);
|
|
98
|
+
} else {
|
|
99
|
+
onError(await guardrailsResult.json());
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
@Resolver(() => CopilotResponse)
|
|
105
|
+
export class CopilotResolver {
|
|
106
|
+
@Query(() => String)
|
|
107
|
+
async hello() {
|
|
108
|
+
return "Hello World";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
@Query(() => AgentsResponse)
|
|
112
|
+
async availableAgents(@Ctx() ctx: GraphQLContext) {
|
|
113
|
+
let logger = ctx.logger.child({ component: "CopilotResolver.availableAgents" });
|
|
114
|
+
|
|
115
|
+
logger.debug("Processing");
|
|
116
|
+
const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
|
|
117
|
+
|
|
118
|
+
logger.debug("Event source created, creating response");
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
agents,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@Mutation(() => CopilotResponse)
|
|
126
|
+
async generateCopilotResponse(
|
|
127
|
+
@Ctx() ctx: GraphQLContext,
|
|
128
|
+
@Arg("data") data: GenerateCopilotResponseInput,
|
|
129
|
+
@Arg("properties", () => GraphQLJSONObject, { nullable: true })
|
|
130
|
+
properties?: CopilotRequestContextProperties,
|
|
131
|
+
) {
|
|
132
|
+
telemetry.capture("oss.runtime.copilot_request_created", {
|
|
133
|
+
"cloud.guardrails.enabled": data.cloud?.guardrails !== undefined,
|
|
134
|
+
requestType: data.metadata.requestType,
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
let logger = ctx.logger.child({ component: "CopilotResolver.generateCopilotResponse" });
|
|
138
|
+
logger.debug({ data }, "Generating Copilot response");
|
|
139
|
+
|
|
140
|
+
if (properties) {
|
|
141
|
+
logger.debug("Properties provided, merging with context properties");
|
|
142
|
+
ctx.properties = { ...ctx.properties, ...properties };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const copilotRuntime = ctx._copilotkit.runtime;
|
|
146
|
+
const serviceAdapter = ctx._copilotkit.serviceAdapter;
|
|
147
|
+
|
|
148
|
+
let copilotCloudPublicApiKey: string | null = null;
|
|
149
|
+
let copilotCloudBaseUrl: string;
|
|
150
|
+
|
|
151
|
+
if (data.cloud) {
|
|
152
|
+
logger = logger.child({ cloud: true });
|
|
153
|
+
logger.debug("Cloud configuration provided, checking for public API key in headers");
|
|
154
|
+
const key = ctx.request.headers.get("x-copilotcloud-public-api-key");
|
|
155
|
+
if (key) {
|
|
156
|
+
logger.debug("Public API key found in headers");
|
|
157
|
+
copilotCloudPublicApiKey = key;
|
|
158
|
+
} else {
|
|
159
|
+
logger.error("Public API key not found in headers");
|
|
160
|
+
throw new GraphQLError("X-CopilotCloud-Public-API-Key header is required");
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (process.env.COPILOT_CLOUD_BASE_URL) {
|
|
164
|
+
copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;
|
|
165
|
+
} else if (ctx._copilotkit.cloud?.baseUrl) {
|
|
166
|
+
copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;
|
|
167
|
+
} else {
|
|
168
|
+
copilotCloudBaseUrl = "https://api.cloud.copilotkit.ai";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
logger = logger.child({ copilotCloudBaseUrl });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
logger.debug("Setting up subjects");
|
|
175
|
+
const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();
|
|
176
|
+
const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();
|
|
177
|
+
const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();
|
|
178
|
+
|
|
179
|
+
let outputMessages: Message[] = [];
|
|
180
|
+
let resolveOutputMessagesPromise: (messages: Message[]) => void;
|
|
181
|
+
let rejectOutputMessagesPromise: (err: Error) => void;
|
|
182
|
+
|
|
183
|
+
const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {
|
|
184
|
+
resolveOutputMessagesPromise = resolve;
|
|
185
|
+
rejectOutputMessagesPromise = reject;
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
logger.debug("Processing");
|
|
189
|
+
const {
|
|
190
|
+
eventSource,
|
|
191
|
+
threadId = randomId(),
|
|
192
|
+
runId,
|
|
193
|
+
serverSideActions,
|
|
194
|
+
actionInputsWithoutAgents,
|
|
195
|
+
} = await copilotRuntime.processRuntimeRequest({
|
|
196
|
+
serviceAdapter,
|
|
197
|
+
messages: data.messages,
|
|
198
|
+
actions: data.frontend.actions.filter(
|
|
199
|
+
(action) => action.available !== ActionInputAvailability.disabled,
|
|
200
|
+
),
|
|
201
|
+
threadId: data.threadId,
|
|
202
|
+
runId: data.runId,
|
|
203
|
+
publicApiKey: undefined,
|
|
204
|
+
outputMessagesPromise,
|
|
205
|
+
graphqlContext: ctx,
|
|
206
|
+
forwardedParameters: data.forwardedParameters,
|
|
207
|
+
agentSession: data.agentSession,
|
|
208
|
+
agentStates: data.agentStates,
|
|
209
|
+
url: data.frontend.url,
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
logger.debug("Event source created, creating response");
|
|
213
|
+
|
|
214
|
+
const response = {
|
|
215
|
+
threadId,
|
|
216
|
+
runId,
|
|
217
|
+
status: firstValueFrom(responseStatus$),
|
|
218
|
+
messages: new Repeater(async (pushMessage, stopStreamingMessages) => {
|
|
219
|
+
logger.debug("Messages repeater created");
|
|
220
|
+
|
|
221
|
+
if (data.cloud?.guardrails) {
|
|
222
|
+
logger = logger.child({ guardrails: true });
|
|
223
|
+
logger.debug("Guardrails is enabled, validating input");
|
|
224
|
+
|
|
225
|
+
invokeGuardrails({
|
|
226
|
+
baseUrl: copilotCloudBaseUrl,
|
|
227
|
+
copilotCloudPublicApiKey,
|
|
228
|
+
data,
|
|
229
|
+
onResult: (result) => {
|
|
230
|
+
logger.debug({ status: result.status }, "Guardrails validation done");
|
|
231
|
+
guardrailsResult$.next(result);
|
|
232
|
+
|
|
233
|
+
// Guardrails validation failed
|
|
234
|
+
if (result.status === "denied") {
|
|
235
|
+
// send the reason to the client and interrupt streaming
|
|
236
|
+
responseStatus$.next(
|
|
237
|
+
new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),
|
|
238
|
+
);
|
|
239
|
+
interruptStreaming$.next({
|
|
240
|
+
reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// resolve messages promise to the middleware
|
|
244
|
+
outputMessages = [
|
|
245
|
+
plainToInstance(TextMessage, {
|
|
246
|
+
id: randomId(),
|
|
247
|
+
createdAt: new Date(),
|
|
248
|
+
content: result.reason,
|
|
249
|
+
role: MessageRole.assistant,
|
|
250
|
+
}),
|
|
251
|
+
];
|
|
252
|
+
resolveOutputMessagesPromise(outputMessages);
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
onError: (err) => {
|
|
256
|
+
logger.error({ err }, "Error in guardrails validation");
|
|
257
|
+
responseStatus$.next(
|
|
258
|
+
new UnknownErrorResponse({
|
|
259
|
+
description: `An unknown error has occurred in the guardrails validation`,
|
|
260
|
+
}),
|
|
261
|
+
);
|
|
262
|
+
interruptStreaming$.next({
|
|
263
|
+
reason: `Interrupted due to unknown error in guardrails validation`,
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
// reject the middleware promise
|
|
267
|
+
rejectOutputMessagesPromise(err);
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
let eventStreamSubscription: Subscription;
|
|
273
|
+
|
|
274
|
+
// run and process the event stream
|
|
275
|
+
const eventStream = eventSource
|
|
276
|
+
.processRuntimeEvents({
|
|
277
|
+
serverSideActions,
|
|
278
|
+
guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,
|
|
279
|
+
actionInputsWithoutAgents: actionInputsWithoutAgents.filter(
|
|
280
|
+
// TODO-AGENTS: do not exclude ALL server side actions
|
|
281
|
+
(action) =>
|
|
282
|
+
!serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),
|
|
283
|
+
),
|
|
284
|
+
})
|
|
285
|
+
.pipe(
|
|
286
|
+
// shareReplay() ensures that later subscribers will see the whole stream instead of
|
|
287
|
+
// just the events that were emitted after the subscriber was added.
|
|
288
|
+
shareReplay(),
|
|
289
|
+
finalize(() => {
|
|
290
|
+
logger.debug("Event stream finalized");
|
|
291
|
+
}),
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
logger.debug("Event stream created, subscribing to event stream");
|
|
295
|
+
|
|
296
|
+
eventStreamSubscription = eventStream.subscribe({
|
|
297
|
+
next: async (event) => {
|
|
298
|
+
switch (event.type) {
|
|
299
|
+
////////////////////////////////
|
|
300
|
+
// TextMessageStart
|
|
301
|
+
////////////////////////////////
|
|
302
|
+
case RuntimeEventTypes.TextMessageStart:
|
|
303
|
+
// create a sub stream that contains the message content
|
|
304
|
+
const textMessageContentStream = eventStream.pipe(
|
|
305
|
+
// skip until this message start event
|
|
306
|
+
skipWhile((e) => e !== event),
|
|
307
|
+
// take until the message end event
|
|
308
|
+
takeWhile(
|
|
309
|
+
(e) =>
|
|
310
|
+
!(
|
|
311
|
+
e.type === RuntimeEventTypes.TextMessageEnd &&
|
|
312
|
+
e.messageId == event.messageId
|
|
313
|
+
),
|
|
314
|
+
),
|
|
315
|
+
// filter out any other message events or message ids
|
|
316
|
+
filter(
|
|
317
|
+
(e) =>
|
|
318
|
+
e.type == RuntimeEventTypes.TextMessageContent &&
|
|
319
|
+
e.messageId == event.messageId,
|
|
320
|
+
),
|
|
321
|
+
);
|
|
322
|
+
|
|
323
|
+
// signal when we are done streaming
|
|
324
|
+
const streamingTextStatus = new Subject<typeof MessageStatusUnion>();
|
|
325
|
+
|
|
326
|
+
const messageId = event.messageId;
|
|
327
|
+
// push the new message
|
|
328
|
+
pushMessage({
|
|
329
|
+
id: messageId,
|
|
330
|
+
parentMessageId: event.parentMessageId,
|
|
331
|
+
status: firstValueFrom(streamingTextStatus),
|
|
332
|
+
createdAt: new Date(),
|
|
333
|
+
role: MessageRole.assistant,
|
|
334
|
+
content: new Repeater(async (pushTextChunk, stopStreamingText) => {
|
|
335
|
+
logger.debug("Text message content repeater created");
|
|
336
|
+
|
|
337
|
+
const textChunks: string[] = [];
|
|
338
|
+
let textSubscription: Subscription;
|
|
339
|
+
|
|
340
|
+
interruptStreaming$
|
|
341
|
+
.pipe(
|
|
342
|
+
shareReplay(),
|
|
343
|
+
take(1),
|
|
344
|
+
tap(({ reason, messageId }) => {
|
|
345
|
+
logger.debug({ reason, messageId }, "Text streaming interrupted");
|
|
346
|
+
|
|
347
|
+
streamingTextStatus.next(
|
|
348
|
+
plainToInstance(FailedMessageStatus, { reason }),
|
|
349
|
+
);
|
|
350
|
+
|
|
351
|
+
responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));
|
|
352
|
+
stopStreamingText();
|
|
353
|
+
textSubscription?.unsubscribe();
|
|
354
|
+
}),
|
|
355
|
+
)
|
|
356
|
+
.subscribe();
|
|
357
|
+
|
|
358
|
+
logger.debug("Subscribing to text message content stream");
|
|
359
|
+
|
|
360
|
+
textSubscription = textMessageContentStream.subscribe({
|
|
361
|
+
next: async (e: RuntimeEvent) => {
|
|
362
|
+
if (e.type == RuntimeEventTypes.TextMessageContent) {
|
|
363
|
+
await pushTextChunk(e.content);
|
|
364
|
+
textChunks.push(e.content);
|
|
365
|
+
}
|
|
366
|
+
},
|
|
367
|
+
error: (err) => {
|
|
368
|
+
logger.error({ err }, "Error in text message content stream");
|
|
369
|
+
interruptStreaming$.next({
|
|
370
|
+
reason: "Error streaming message content",
|
|
371
|
+
messageId,
|
|
372
|
+
});
|
|
373
|
+
stopStreamingText();
|
|
374
|
+
textSubscription?.unsubscribe();
|
|
375
|
+
},
|
|
376
|
+
complete: () => {
|
|
377
|
+
logger.debug("Text message content stream completed");
|
|
378
|
+
streamingTextStatus.next(new SuccessMessageStatus());
|
|
379
|
+
stopStreamingText();
|
|
380
|
+
textSubscription?.unsubscribe();
|
|
381
|
+
|
|
382
|
+
outputMessages.push(
|
|
383
|
+
plainToInstance(TextMessage, {
|
|
384
|
+
id: messageId,
|
|
385
|
+
createdAt: new Date(),
|
|
386
|
+
content: textChunks.join(""),
|
|
387
|
+
role: MessageRole.assistant,
|
|
388
|
+
}),
|
|
389
|
+
);
|
|
390
|
+
},
|
|
391
|
+
});
|
|
392
|
+
}),
|
|
393
|
+
});
|
|
394
|
+
break;
|
|
395
|
+
////////////////////////////////
|
|
396
|
+
// ActionExecutionStart
|
|
397
|
+
////////////////////////////////
|
|
398
|
+
case RuntimeEventTypes.ActionExecutionStart:
|
|
399
|
+
logger.debug("Action execution start event received");
|
|
400
|
+
const actionExecutionArgumentStream = eventStream.pipe(
|
|
401
|
+
skipWhile((e) => e !== event),
|
|
402
|
+
// take until the action execution end event
|
|
403
|
+
takeWhile(
|
|
404
|
+
(e) =>
|
|
405
|
+
!(
|
|
406
|
+
e.type === RuntimeEventTypes.ActionExecutionEnd &&
|
|
407
|
+
e.actionExecutionId == event.actionExecutionId
|
|
408
|
+
),
|
|
409
|
+
),
|
|
410
|
+
// filter out any other action execution events or action execution ids
|
|
411
|
+
filter(
|
|
412
|
+
(e) =>
|
|
413
|
+
e.type == RuntimeEventTypes.ActionExecutionArgs &&
|
|
414
|
+
e.actionExecutionId == event.actionExecutionId,
|
|
415
|
+
),
|
|
416
|
+
);
|
|
417
|
+
const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();
|
|
418
|
+
pushMessage({
|
|
419
|
+
id: event.actionExecutionId,
|
|
420
|
+
parentMessageId: event.parentMessageId,
|
|
421
|
+
status: firstValueFrom(streamingArgumentsStatus),
|
|
422
|
+
createdAt: new Date(),
|
|
423
|
+
name: event.actionName,
|
|
424
|
+
arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
|
|
425
|
+
logger.debug("Action execution argument stream created");
|
|
426
|
+
|
|
427
|
+
const argumentChunks: string[] = [];
|
|
428
|
+
let actionExecutionArgumentSubscription: Subscription;
|
|
429
|
+
|
|
430
|
+
actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({
|
|
431
|
+
next: async (e: RuntimeEvent) => {
|
|
432
|
+
if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
|
|
433
|
+
await pushArgumentsChunk(e.args);
|
|
434
|
+
argumentChunks.push(e.args);
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
error: (err) => {
|
|
438
|
+
logger.error({ err }, "Error in action execution argument stream");
|
|
439
|
+
streamingArgumentsStatus.next(
|
|
440
|
+
plainToInstance(FailedMessageStatus, {
|
|
441
|
+
reason:
|
|
442
|
+
"An unknown error has occurred in the action execution argument stream",
|
|
443
|
+
}),
|
|
444
|
+
);
|
|
445
|
+
stopStreamingArguments();
|
|
446
|
+
actionExecutionArgumentSubscription?.unsubscribe();
|
|
447
|
+
},
|
|
448
|
+
complete: () => {
|
|
449
|
+
logger.debug("Action execution argument stream completed");
|
|
450
|
+
streamingArgumentsStatus.next(new SuccessMessageStatus());
|
|
451
|
+
stopStreamingArguments();
|
|
452
|
+
actionExecutionArgumentSubscription?.unsubscribe();
|
|
453
|
+
|
|
454
|
+
outputMessages.push(
|
|
455
|
+
plainToInstance(ActionExecutionMessage, {
|
|
456
|
+
id: event.actionExecutionId,
|
|
457
|
+
createdAt: new Date(),
|
|
458
|
+
name: event.actionName,
|
|
459
|
+
arguments: argumentChunks.join(""),
|
|
460
|
+
}),
|
|
461
|
+
);
|
|
462
|
+
},
|
|
463
|
+
});
|
|
464
|
+
}),
|
|
465
|
+
});
|
|
466
|
+
break;
|
|
467
|
+
////////////////////////////////
|
|
468
|
+
// ActionExecutionResult
|
|
469
|
+
////////////////////////////////
|
|
470
|
+
case RuntimeEventTypes.ActionExecutionResult:
|
|
471
|
+
logger.debug({ result: event.result }, "Action execution result event received");
|
|
472
|
+
pushMessage({
|
|
473
|
+
id: "result-" + event.actionExecutionId,
|
|
474
|
+
status: new SuccessMessageStatus(),
|
|
475
|
+
createdAt: new Date(),
|
|
476
|
+
actionExecutionId: event.actionExecutionId,
|
|
477
|
+
actionName: event.actionName,
|
|
478
|
+
result: event.result,
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
outputMessages.push(
|
|
482
|
+
plainToInstance(ResultMessage, {
|
|
483
|
+
id: "result-" + event.actionExecutionId,
|
|
484
|
+
createdAt: new Date(),
|
|
485
|
+
actionExecutionId: event.actionExecutionId,
|
|
486
|
+
actionName: event.actionName,
|
|
487
|
+
result: event.result,
|
|
488
|
+
}),
|
|
489
|
+
);
|
|
490
|
+
break;
|
|
491
|
+
////////////////////////////////
|
|
492
|
+
// AgentStateMessage
|
|
493
|
+
////////////////////////////////
|
|
494
|
+
case RuntimeEventTypes.AgentStateMessage:
|
|
495
|
+
logger.debug({ event }, "Agent message event received");
|
|
496
|
+
pushMessage({
|
|
497
|
+
id: randomId(),
|
|
498
|
+
status: new SuccessMessageStatus(),
|
|
499
|
+
threadId: event.threadId,
|
|
500
|
+
agentName: event.agentName,
|
|
501
|
+
nodeName: event.nodeName,
|
|
502
|
+
runId: event.runId,
|
|
503
|
+
active: event.active,
|
|
504
|
+
state: event.state,
|
|
505
|
+
running: event.running,
|
|
506
|
+
role: MessageRole.assistant,
|
|
507
|
+
createdAt: new Date(),
|
|
508
|
+
});
|
|
509
|
+
outputMessages.push(
|
|
510
|
+
plainToInstance(AgentStateMessage, {
|
|
511
|
+
id: randomId(),
|
|
512
|
+
threadId: event.threadId,
|
|
513
|
+
agentName: event.agentName,
|
|
514
|
+
nodeName: event.nodeName,
|
|
515
|
+
runId: event.runId,
|
|
516
|
+
active: event.active,
|
|
517
|
+
state: event.state,
|
|
518
|
+
running: event.running,
|
|
519
|
+
role: MessageRole.assistant,
|
|
520
|
+
createdAt: new Date(),
|
|
521
|
+
}),
|
|
522
|
+
);
|
|
523
|
+
break;
|
|
524
|
+
}
|
|
525
|
+
},
|
|
526
|
+
error: (err) => {
|
|
527
|
+
logger.error({ err }, "Error in event stream");
|
|
528
|
+
responseStatus$.next(
|
|
529
|
+
new UnknownErrorResponse({
|
|
530
|
+
description: `An unknown error has occurred in the event stream`,
|
|
531
|
+
}),
|
|
532
|
+
);
|
|
533
|
+
eventStreamSubscription?.unsubscribe();
|
|
534
|
+
stopStreamingMessages();
|
|
535
|
+
|
|
536
|
+
rejectOutputMessagesPromise(err);
|
|
537
|
+
},
|
|
538
|
+
complete: async () => {
|
|
539
|
+
logger.debug("Event stream completed");
|
|
540
|
+
if (data.cloud?.guardrails) {
|
|
541
|
+
logger.debug("Guardrails is enabled, waiting for guardrails result");
|
|
542
|
+
await firstValueFrom(guardrailsResult$);
|
|
543
|
+
}
|
|
544
|
+
responseStatus$.next(new SuccessResponseStatus());
|
|
545
|
+
eventStreamSubscription?.unsubscribe();
|
|
546
|
+
stopStreamingMessages();
|
|
547
|
+
|
|
548
|
+
resolveOutputMessagesPromise(outputMessages);
|
|
549
|
+
},
|
|
550
|
+
});
|
|
551
|
+
}),
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
return response;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Field, InterfaceType, ObjectType } from "type-graphql";
|
|
2
|
+
import { MessageRole } from "./enums";
|
|
3
|
+
import { MessageStatusUnion } from "./message-status.type";
|
|
4
|
+
import { ResponseStatusUnion } from "./response-status.type";
|
|
5
|
+
|
|
6
|
+
@ObjectType()
|
|
7
|
+
export class Agent {
|
|
8
|
+
@Field(() => String)
|
|
9
|
+
id: string;
|
|
10
|
+
|
|
11
|
+
@Field(() => String)
|
|
12
|
+
name: string;
|
|
13
|
+
|
|
14
|
+
@Field(() => String)
|
|
15
|
+
description?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
@ObjectType()
|
|
19
|
+
export class AgentsResponse {
|
|
20
|
+
@Field(() => [Agent])
|
|
21
|
+
agents: Agent[];
|
|
22
|
+
}
|