@copilotkit/runtime 0.37.0 → 0.38.0-beta.0
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/.turbo/turbo-build.log +69 -54
- package/CHANGELOG.md +11 -0
- package/__snapshots__/schema/schema.graphql +15 -4
- package/dist/{chunk-2CCVVJDU.mjs → chunk-2PJG3NAC.mjs} +13 -15
- package/dist/chunk-2PJG3NAC.mjs.map +1 -0
- package/dist/{chunk-NFCPM5AM.mjs → chunk-6NZ4UMOD.mjs} +4 -4
- package/dist/chunk-6NZ4UMOD.mjs.map +1 -0
- package/dist/{chunk-XPAUPJMW.mjs → chunk-6YGDE3YI.mjs} +432 -220
- package/dist/chunk-6YGDE3YI.mjs.map +1 -0
- package/dist/chunk-BYB2LNMK.mjs +152 -0
- package/dist/chunk-BYB2LNMK.mjs.map +1 -0
- package/dist/{chunk-7IFP53C6.mjs → chunk-FRK6BXXV.mjs} +49 -11
- package/dist/chunk-FRK6BXXV.mjs.map +1 -0
- package/dist/{chunk-5HGYI6EG.mjs → chunk-JBDOA7MK.mjs} +34 -15
- package/dist/chunk-JBDOA7MK.mjs.map +1 -0
- package/dist/{chunk-4UA4RB4C.mjs → chunk-JIKPSUGQ.mjs} +45 -76
- package/dist/chunk-JIKPSUGQ.mjs.map +1 -0
- package/dist/{chunk-BLTAUVRP.mjs → chunk-OZMCHYYR.mjs} +5 -3
- package/dist/{chunk-BLTAUVRP.mjs.map → chunk-OZMCHYYR.mjs.map} +1 -1
- package/dist/chunk-RHQLCJGG.mjs +7 -0
- package/dist/chunk-RHQLCJGG.mjs.map +1 -0
- package/dist/failed-response-status-reasons-0ab19e06.d.ts +49 -0
- package/dist/graphql/types/base/index.mjs +2 -1
- package/dist/graphql/types/converted/index.mjs +3 -2
- package/dist/{index-f0875df3.d.ts → index-0e75acd2.d.ts} +86 -59
- package/dist/index.d.ts +7 -4
- package/dist/index.js +536 -169
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +16 -13
- package/dist/index.mjs.map +1 -1
- package/dist/{langchain-adapter-9ce103f3.d.ts → langchain-adapter-a02d1d38.d.ts} +4 -4
- package/dist/{langserve-fd5066ee.d.ts → langserve-75ebbc38.d.ts} +25 -9
- 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 +6 -4
- package/dist/lib/index.js +530 -169
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +9 -13
- package/dist/lib/integrations/index.d.ts +5 -3
- package/dist/lib/integrations/index.js +426 -64
- package/dist/lib/integrations/index.js.map +1 -1
- package/dist/lib/integrations/index.mjs +7 -5
- package/dist/lib/integrations/node-http/index.d.ts +4 -2
- package/dist/lib/integrations/node-http/index.js +416 -52
- package/dist/lib/integrations/node-http/index.js.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs +6 -4
- package/dist/pages-router-e81920d5.d.ts +21 -0
- package/dist/service-adapters/index.d.ts +2 -2
- package/dist/service-adapters/index.js +82 -25
- package/dist/service-adapters/index.js.map +1 -1
- package/dist/service-adapters/index.mjs +5 -4
- package/dist/utils/index.d.ts +1 -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/package.json +6 -4
- package/src/graphql/inputs/cloud-guardrails.input.ts +2 -5
- package/src/graphql/inputs/cloud.input.ts +2 -2
- package/src/graphql/resolvers/copilot.resolver.ts +340 -30
- package/src/graphql/types/response-status.type.ts +16 -2
- package/src/index.ts +1 -0
- package/src/lib/cloud/index.ts +4 -0
- package/src/lib/copilot-runtime.ts +116 -70
- package/src/lib/index.ts +0 -1
- package/src/lib/integrations/nextjs/app-router.ts +9 -17
- package/src/lib/integrations/nextjs/pages-router.ts +9 -15
- package/src/lib/integrations/node-http/index.ts +6 -14
- package/src/lib/integrations/shared.ts +38 -18
- package/src/lib/logger.ts +28 -0
- package/src/service-adapters/events.ts +20 -2
- package/src/service-adapters/experimental/groq/groq-adapter.ts +3 -1
- package/src/service-adapters/experimental/ollama/ollama-adapter.ts +3 -1
- package/src/service-adapters/google/google-genai-adapter.ts +6 -1
- package/src/service-adapters/google/utils.ts +1 -1
- package/src/service-adapters/index.ts +1 -1
- package/src/service-adapters/langchain/langchain-adapter.ts +8 -9
- package/src/service-adapters/langchain/langserve.ts +10 -4
- package/src/service-adapters/langchain/utils.ts +58 -9
- package/src/service-adapters/openai/openai-adapter.ts +8 -7
- package/src/service-adapters/openai/openai-assistant-adapter.ts +6 -8
- package/src/service-adapters/service-adapter.ts +1 -2
- package/src/utils/failed-response-status-reasons.ts +48 -0
- package/src/utils/index.ts +1 -0
- package/dist/chunk-2CCVVJDU.mjs.map +0 -1
- package/dist/chunk-4UA4RB4C.mjs.map +0 -1
- package/dist/chunk-5HGYI6EG.mjs.map +0 -1
- package/dist/chunk-7IFP53C6.mjs.map +0 -1
- package/dist/chunk-NFCPM5AM.mjs.map +0 -1
- package/dist/chunk-XPAUPJMW.mjs.map +0 -1
- package/dist/pages-router-b6bc6c60.d.ts +0 -30
- package/src/lib/copilot-cloud.ts +0 -63
- package/src/lib/guardrails.ts +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/lib/integrations/node-http/index.ts","../../../../src/lib/integrations/shared.ts","../../../../src/graphql/resolvers/copilot.resolver.ts","../../../../src/graphql/inputs/generate-copilot-response.input.ts","../../../../src/graphql/inputs/message.input.ts","../../../../src/graphql/types/enums.ts","../../../../src/graphql/types/base/index.ts","../../../../src/graphql/inputs/frontend.input.ts","../../../../src/graphql/inputs/action.input.ts","../../../../src/graphql/inputs/cloud.input.ts","../../../../src/graphql/inputs/cloud-guardrails.input.ts","../../../../src/graphql/types/copilot-response.type.ts","../../../../src/graphql/types/message-status.type.ts","../../../../src/graphql/types/response-status.type.ts","../../../../src/service-adapters/events.ts"],"sourcesContent":["import { createYoga } from \"graphql-yoga\";\nimport { getCommonConfig } from \"../shared\";\nimport { CopilotRuntime } from \"../../copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../../service-adapters\";\n\nexport function copilotRuntimeNodeHttpEndpoint({\n runtime,\n endpoint,\n serviceAdapter,\n}: {\n runtime: CopilotRuntime;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n}) {\n const commonConfig = getCommonConfig({ runtime, serviceAdapter });\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: endpoint,\n });\n\n return yoga;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { GuardrailsOptions } from \"../guardrails\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\ntype CopilotKitContext = {\n runtime: CopilotRuntime;\n serviceAdapter: CopilotServiceAdapter;\n properties: CopilotRequestContextProperties;\n};\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CopilotKitContext;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime;\n serviceAdapter: CopilotServiceAdapter;\n guardrails?: GuardrailsOptions;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CopilotKitContext,\n): Promise<Partial<GraphQLContext>> {\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n };\n\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n return schema;\n}\n\nexport function getCommonConfig(options?: CreateCopilotRuntimeServerOptions) {\n return {\n schema: buildSchema(),\n plugins: [useDeferStream()],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, {\n runtime: options.runtime,\n serviceAdapter: options.serviceAdapter,\n properties: {},\n }),\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport { Subject, firstValueFrom, shareReplay, skipWhile, takeWhile } from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport { MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport { nanoid } from \"nanoid\";\nimport { RuntimeEvent, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport { MessageStatusUnion, SuccessMessageStatus } from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Mutation(() => CopilotResponse)\n async generateCopilotResponse(\n @Ctx() ctx: GraphQLContext,\n @Arg(\"data\") data: GenerateCopilotResponseInput,\n @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n properties?: CopilotRequestContextProperties,\n ) {\n if (properties) {\n ctx._copilotkit.properties = { ...ctx._copilotkit.properties, ...properties };\n }\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n const responseStatus = new Subject<typeof ResponseStatusUnion>();\n\n const {\n eventSource,\n threadId = nanoid(),\n runId,\n } = await copilotRuntime.process({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions,\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: undefined,\n });\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n // run and process the event stream\n const eventStream = eventSource.process(copilotRuntime.actions).pipe(\n // shareReplay() ensures that later subscribers will see the whole stream instead of\n // just the events that were emitted after the subscriber was added.\n shareReplay(),\n );\n eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\n ////////////////////////////////\n // TextMessageStart\n ////////////////////////////////\n case RuntimeEventTypes.TextMessageStart:\n // create a sub stream that contains the message content\n const textMessageContentStream = eventStream.pipe(\n // skip until this message start event\n skipWhile((e) => e !== event),\n // take until the message end event\n takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n // push the new message\n pushMessage({\n id: nanoid(),\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n // push the message content\n await textMessageContentStream.forEach(async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n }\n });\n stopStreamingText();\n streamingTextStatus.next(new SuccessMessageStatus());\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e) => e !== event),\n takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n await actionExecutionArgumentStream.forEach(async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n }\n });\n stopStreamingArguments();\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n pushMessage({\n id: nanoid(),\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n break;\n }\n },\n error: (err) => console.error(\"Error in event source\", err),\n complete: () => {\n responseStatus.next(new SuccessResponseStatus());\n stopStreamingMessages();\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"../types/enums\";\nimport { BaseMessage } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessage {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n}\n\nexport enum ActionExecutionScope {\n server = \"server\",\n client = \"client\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(ActionExecutionScope, {\n name: \"ActionExecutionScope\",\n description: \"The scope of the action\",\n});\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessage {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput)\n guardrails: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => String)\n id: string;\n\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => [GuardrailsRuleInput], { nullable: true })\n inputValidationRules?: GuardrailsRuleInput[] = [];\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n }\n return undefined;\n },\n})\nabstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n\n @Field(() => [String])\n arguments: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import { Action } from \"@copilotkit/shared\";\nimport { of, concat, map, scan, concatMap, ReplaySubject } from \"rxjs\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n}\n\ntype FunctionCallScope = \"client\" | \"server\";\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n scope?: FunctionCallScope;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n };\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart(messageId: string) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId });\n }\n\n sendTextMessageContent(content: string) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content });\n }\n\n sendTextMessageEnd() {\n this.next({ type: RuntimeEventTypes.TextMessageEnd });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart(messageId);\n this.sendTextMessageContent(content);\n this.sendTextMessageEnd();\n }\n\n sendActionExecutionStart(actionExecutionId: string, actionName: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n });\n }\n\n sendActionExecutionArgs(args: string) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args });\n }\n\n sendActionExecutionEnd() {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd });\n }\n\n sendActionExecution(actionExecutionId: string, toolName: string, args: string) {\n this.sendActionExecutionStart(actionExecutionId, toolName);\n this.sendActionExecutionArgs(args);\n this.sendActionExecutionEnd();\n }\n\n sendActionExecutionResult(actionExecutionId: string, actionName: string, result: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n process(serversideActions: Action<any>[]) {\n this.callback(this.eventStream$).catch((error) => {\n console.error(\"Error in event source callback\", error);\n });\n return this.eventStream$.pipe(\n // mark tools for server side execution\n map((event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n event.scope = serversideActions.find((action) => action.name === event.actionName)\n ? \"server\"\n : \"client\";\n }\n return event;\n }),\n // track state\n scan(\n (acc, event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide = event.scope === \"server\";\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serversideActions.find((action) => action.name === event.actionName);\n }\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionId,\n ).catch((error) => {\n console.error(error);\n });\n return concat(of(eventWithState.event!), toolCallEventStream$);\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n action: Action<any>,\n actionArguments: string,\n actionExecutionId: string,\n) {\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n args = JSON.parse(actionArguments);\n }\n\n // call the function\n const result = await action.handler(args);\n\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;;;;;IAAAA,uBAA2B;;;ACE3B,IAAAC,wBAAgC;;;ACFhC,IAAAC,wBAAoD;AACpD,IAAAC,eAA2E;;;ACD3E,IAAAC,uBAAiC;;;ACAjC,IAAAC,uBAAiC;;;ACAjC,0BAAiC;;UAErBC,cAAAA;;;;GAAAA,gBAAAA,cAAAA,CAAAA,EAAAA;;UAMAC,uBAAAA;;;GAAAA,yBAAAA,uBAAAA,CAAAA,EAAAA;IAKZC,sCAAiBF,aAAa;EAC5BG,MAAM;EACNC,aAAa;AACf,CAAA;IAEAF,sCAAiBD,sBAAsB;EACrCE,MAAM;EACNC,aAAa;AACf,CAAA;;;ACrBA,IAAAC,uBAAiC;;;;;;;;;;;;;;;;;AAG1B,IAAMC,cAAN,MAAMA;EAEXC;EAGAC;AACF;AANaF;;MACVG,4BAAM,MAAMC,MAAAA;;GADFJ,YAAAA,WAAAA,MAAAA,MAAAA;;MAIVG,4BAAM,MAAME,IAAAA;qCACF,SAAA,cAAA,SAAA,IAAA;GALAL,YAAAA,WAAAA,aAAAA,MAAAA;AAAAA,cAAAA,aAAAA;MADZM,gCAAAA;GACYN,WAAAA;;;;;;;;;;;;;;;;;;;AFIN,IAAMO,eAAN,cAA2BC,YAAAA;EAEhCC;EAGAC;EAGAC;AACF;AATaJ;;MACVK,4BAAM,MAAMC,kBAAkB;IAAEC,UAAU;EAAK,CAAA;sCAClC,qBAAA,cAAA,SAAA,gBAAA;GAFHP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AAQU;MACjBC,gBAAgBX,QAAQW;MACxBC,YAAY,CAAC;IACf,CAAA;EACJ;AACF;AAXgBN;;;ADnDT,SAASO,+BAA+B,EAC7CC,SACAC,UACAC,eAAc,GAKf;AACC,QAAMC,eAAeC,gBAAgB;IAAEJ;IAASE;EAAe,CAAA;AAE/D,QAAMG,WAAOC,iCAAW;IACtB,GAAGH;IACHI,iBAAiBN;EACnB,CAAA;AAEA,SAAOI;AACT;AAjBgBN;","names":["import_graphql_yoga","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","MessageRole","ActionExecutionScope","registerEnumType","name","description","import_type_graphql","BaseMessage","id","createdAt","Field","String","Date","InputType","MessageInput","BaseMessage","textMessage","actionExecutionMessage","resultMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","InputType","content","role","String","MessageRole","name","arguments","scope","ActionExecutionScope","actionExecutionId","actionName","result","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","Field","String","InputType","FrontendInput","toDeprecate_fullContext","actions","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","id","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","InputType","GenerateCopilotResponseInput","threadId","runId","messages","frontend","cloud","Field","String","nullable","MessageInput","FrontendInput","CloudInput","InputType","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","reason","String","ResponseStatusUnion","createUnionType","types","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","undefined","role","content","MessageRole","ObjectType","implements","name","scope","arguments","ActionExecutionScope","actionExecutionId","actionName","result","CopilotResponse","threadId","runId","messages","ResponseStatusUnion","nullable","RuntimeEventTypes","CopilotResolver","hello","generateCopilotResponse","ctx","data","properties","_copilotkit","copilotRuntime","runtime","serviceAdapter","responseStatus","Subject","eventSource","threadId","nanoid","runId","process","messages","actions","frontend","publicApiKey","undefined","response","status","firstValueFrom","Repeater","pushMessage","stopStreamingMessages","eventStream","pipe","shareReplay","subscribe","next","event","type","RuntimeEventTypes","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","streamingTextStatus","id","createdAt","Date","role","MessageRole","assistant","content","pushTextChunk","stopStreamingText","forEach","TextMessageContent","SuccessMessageStatus","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","streamingArgumentsStatus","actionExecutionId","name","actionName","scope","arguments","pushArgumentsChunk","stopStreamingArguments","ActionExecutionArgs","args","ActionExecutionResult","result","error","err","console","complete","SuccessResponseStatus","Query","String","Mutation","CopilotResponse","Ctx","Arg","GraphQLJSONObject","nullable","Resolver","createContext","initialContext","copilotKitContext","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","emitSchemaFile","getCommonConfig","plugins","useDeferStream","context","runtime","serviceAdapter","properties","copilotRuntimeNodeHttpEndpoint","runtime","endpoint","serviceAdapter","commonConfig","getCommonConfig","yoga","createYoga","graphqlEndpoint"]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/lib/integrations/node-http/index.ts","../../../../src/lib/integrations/shared.ts","../../../../src/graphql/resolvers/copilot.resolver.ts","../../../../src/graphql/inputs/generate-copilot-response.input.ts","../../../../src/graphql/inputs/message.input.ts","../../../../src/graphql/types/enums.ts","../../../../src/graphql/types/base/index.ts","../../../../src/graphql/inputs/frontend.input.ts","../../../../src/graphql/inputs/action.input.ts","../../../../src/graphql/inputs/cloud.input.ts","../../../../src/graphql/inputs/cloud-guardrails.input.ts","../../../../src/graphql/types/copilot-response.type.ts","../../../../src/graphql/types/message-status.type.ts","../../../../src/graphql/types/response-status.type.ts","../../../../src/service-adapters/events.ts","../../../../src/graphql/types/converted/index.ts","../../../../src/utils/failed-response-status-reasons.ts","../../../../src/lib/logger.ts"],"sourcesContent":["import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\n\nexport function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n logger.debug(\"Getting common config\");\n\n const contextLogger = createLogger({ level: logLevel });\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream()],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport { MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport { nanoid } from \"nanoid\";\nimport { RuntimeEvent, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult, GuardrailsResultStatus } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport { ActionExecutionMessage, Message, ResultMessage, TextMessage } from \"../types/converted\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Mutation(() => CopilotResponse)\n async generateCopilotResponse(\n @Ctx() ctx: GraphQLContext,\n @Arg(\"data\") data: GenerateCopilotResponseInput,\n @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n properties?: CopilotRequestContextProperties,\n ) {\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n const key = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (key) {\n logger.debug(\"Public API key found in headers\");\n copilotCloudPublicApiKey = key;\n } else {\n logger.error(\"Public API key not found in headers\");\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n logger.debug(\"Processing\");\n const {\n eventSource,\n threadId = nanoid(),\n runId,\n actions,\n } = await copilotRuntime.process({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions,\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: undefined,\n properties: ctx.properties || {},\n outputMessagesPromise,\n });\n\n logger.debug(\"Event source created, creating response\");\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: nanoid(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n // run and process the event stream\n const eventStream = eventSource\n .process({\n serversideActions: actions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n })\n .pipe(\n // shareReplay() ensures that later subscribers will see the whole stream instead of\n // just the events that were emitted after the subscriber was added.\n shareReplay(),\n finalize(() => {\n logger.debug(\"Event stream finalized\");\n }),\n );\n\n logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\n ////////////////////////////////\n // TextMessageStart\n ////////////////////////////////\n case RuntimeEventTypes.TextMessageStart:\n // create a sub stream that contains the message content\n const textMessageContentStream = eventStream.pipe(\n // skip until this message start event\n skipWhile((e) => e !== event),\n // take until the message end event\n takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = nanoid();\n\n // push the new message\n pushMessage({\n id: messageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e) => e !== event),\n takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: nanoid(),\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: nanoid(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in event stream\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"../types/enums\";\nimport { BaseMessage } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessage {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n}\n\nexport enum ActionExecutionScope {\n server = \"server\",\n client = \"client\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(ActionExecutionScope, {\n name: \"ActionExecutionScope\",\n description: \"The scope of the action\",\n});\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessage {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: true })\n inputValidationRules: GuardrailsRuleInput = { allowList: [], denyList: [] };\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n }\n return undefined;\n },\n})\nabstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n\n @Field(() => [String])\n arguments: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { GraphQLJSON } from \"graphql-scalars\";\nimport { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\nexport enum FailedResponseStatusReason {\n GUARDRAILS_VALIDATION_FAILED = \"GUARDRAILS_VALIDATION_FAILED\",\n MESSAGE_STREAM_INTERRUPTED = \"MESSAGE_STREAM_INTERRUPTED\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nregisterEnumType(FailedResponseStatusReason, {\n name: \"FailedResponseStatusReason\",\n});\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => FailedResponseStatusReason)\n reason: FailedResponseStatusReason;\n\n @Field(() => GraphQLJSON, { nullable: true })\n details?: Record<string, any> = null;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import { Action } from \"@copilotkit/shared\";\nimport { of, concat, map, scan, concatMap, ReplaySubject, Subject, firstValueFrom } from \"rxjs\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n}\n\ntype FunctionCallScope = \"client\" | \"server\";\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n scope?: FunctionCallScope;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n };\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart(messageId: string) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId });\n }\n\n sendTextMessageContent(content: string) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content });\n }\n\n sendTextMessageEnd() {\n this.next({ type: RuntimeEventTypes.TextMessageEnd });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart(messageId);\n this.sendTextMessageContent(content);\n this.sendTextMessageEnd();\n }\n\n sendActionExecutionStart(actionExecutionId: string, actionName: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n });\n }\n\n sendActionExecutionArgs(args: string) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args });\n }\n\n sendActionExecutionEnd() {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd });\n }\n\n sendActionExecution(actionExecutionId: string, toolName: string, args: string) {\n this.sendActionExecutionStart(actionExecutionId, toolName);\n this.sendActionExecutionArgs(args);\n this.sendActionExecutionEnd();\n }\n\n sendActionExecutionResult(actionExecutionId: string, actionName: string, result: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n process({\n serversideActions,\n guardrailsResult$,\n }: {\n serversideActions: Action<any>[];\n guardrailsResult$?: Subject<GuardrailsResult>;\n }) {\n this.callback(this.eventStream$).catch((error) => {\n console.error(\"Error in event source callback\", error);\n });\n return this.eventStream$.pipe(\n // mark tools for server side execution\n map((event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n event.scope = serversideActions.find((action) => action.name === event.actionName)\n ? \"server\"\n : \"client\";\n }\n return event;\n }),\n // track state\n scan(\n (acc, event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide = event.scope === \"server\";\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serversideActions.find((action) => action.name === event.actionName);\n }\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n guardrailsResult$ ? guardrailsResult$ : null,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionId,\n ).catch((error) => {\n console.error(error);\n });\n return concat(of(eventWithState.event!), toolCallEventStream$);\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n guardrailsResult$: Subject<GuardrailsResult> | null,\n action: Action<any>,\n actionArguments: string,\n actionExecutionId: string,\n) {\n if (guardrailsResult$) {\n const { status } = await firstValueFrom(guardrailsResult$);\n\n if (status === \"denied\") {\n eventStream$.complete();\n return;\n }\n }\n\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n args = JSON.parse(actionArguments);\n }\n\n // call the function\n const result = await action.handler(args);\n\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n },\n });\n}\n","import {\n ActionExecutionMessageInput,\n ResultMessageInput,\n TextMessageInput,\n} from \"../../inputs/message.input\";\nimport { BaseMessage } from \"../base\";\nimport { ActionExecutionScope, MessageRole } from \"../enums\";\n\nexport class TextMessage extends BaseMessage implements TextMessageInput {\n content: string;\n role: MessageRole;\n}\n\nexport type Message = BaseMessage;\n\nexport class ActionExecutionMessage\n extends BaseMessage\n implements Omit<ActionExecutionMessageInput, \"arguments\">\n{\n name: string;\n arguments: Record<string, any>;\n scope: ActionExecutionScope;\n}\n\nexport class ResultMessage extends BaseMessage implements ResultMessageInput {\n actionExecutionId: string;\n actionName: string;\n result: string;\n}\n","import {\n FailedResponseStatus,\n FailedResponseStatusReason,\n} from \"../graphql/types/response-status.type\";\n\nexport class GuardrailsValidationFailureResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;\n declare details: {\n guardrailsReason: string;\n };\n\n constructor({ guardrailsReason }) {\n super();\n this.details = {\n guardrailsReason,\n };\n }\n}\n\nexport class MessageStreamInterruptedResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;\n declare details: {\n messageId: string;\n description: string;\n };\n\n constructor({ messageId }: { messageId: string }) {\n super();\n this.details = {\n messageId,\n description: \"Check the message for mode details\",\n };\n }\n}\n\nexport class UnknownErrorResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.UNKNOWN_ERROR;\n declare details: {\n description?: string;\n };\n\n constructor({ description }: { description?: string }) {\n super();\n this.details = {\n description,\n };\n }\n}\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;IAAAA,uBAA2B;;;ACC3B,IAAAC,wBAAgC;;;ACDhC,IAAAC,wBAAoD;AACpD,IAAAC,eAWO;;;ACZP,IAAAC,uBAAiC;;;ACAjC,IAAAC,uBAAiC;;;ACAjC,0BAAiC;;UAErBC,cAAAA;;;;GAAAA,gBAAAA,cAAAA,CAAAA,EAAAA;;UAMAC,uBAAAA;;;GAAAA,yBAAAA,uBAAAA,CAAAA,EAAAA;IAKZC,sCAAiBF,aAAa;EAC5BG,MAAM;EACNC,aAAa;AACf,CAAA;IAEAF,sCAAiBD,sBAAsB;EACrCE,MAAM;EACNC,aAAa;AACf,CAAA;;;ACrBA,IAAAC,uBAAiC;;;;;;;;;;;;;;;;;AAG1B,IAAMC,cAAN,MAAMA;EAEXC;EAGAC;AACF;AANaF;;MACVG,4BAAM,MAAMC,MAAAA;;GADFJ,YAAAA,WAAAA,MAAAA,MAAAA;;MAIVG,4BAAM,MAAME,IAAAA;qCACF,SAAA,cAAA,SAAA,IAAA;GALAL,YAAAA,WAAAA,aAAAA,MAAAA;AAAAA,cAAAA,aAAAA;MADZM,gCAAAA;GACYN,WAAAA;;;;;;;;;;;;;;;;;;;AFIN,IAAMO,eAAN,cAA2BC,YAAAA;EAEhCC;EAGAC;EAGAC;AACF;AATaJ;;MACVK,4BAAM,MAAMC,kBAAkB;IAAEC,UAAU;EAAK,CAAA;sCAClC,qBAAA,cAAA,SAAA,gBAAA;GAFHP,aAAAA,WAAAA,eAAAA,MAAAA;;MAIVK,4BAAM,MAAMG,6BAA6B;IAAED,UAAU;EAAK,CAAA;sCAClC,gCAAA,cAAA,SAAA,2BAAA;GALdP,aAAAA,WAAAA,0BAAAA,M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ACLM,SAASvB,aAAa;MAAEsB,WAAW;MAAgBD,OAAOJ;IAAS,CAAA;IACnEN,QAAQF,YAAAA;IACRe,SAAS;UAACC,2CAAAA;;IACVC,SAAS,CAACnB,QACRN,cAAcM,KAAKG,SAASN,eAAeM,QAAQL,UAAU;EACjE;AACF;AAdgBW;;;ADtET,SAASW,+BAA+BC,SAA0C;AACvF,QAAMC,eAAeC,gBAAgBF,OAAAA;AACrC,QAAMG,UAASF,aAAaG;AAC5BD,EAAAA,QAAOE,MAAM,6BAAA;AAEb,QAAMC,WAAOC,iCAAW;IACtB,GAAGN;IACHO,iBAAiBR,QAAQS;EAC3B,CAAA;AAEA,SAAOH;AACT;AAXgBP;","names":["import_graphql_yoga","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","MessageRole","ActionExecutionScope","registerEnumType","name","description","import_type_graphql","BaseMessage","id","createdAt","Field","String","Date","InputType","MessageInput","BaseMessage","textMessage","actionExecutionMessage","resultMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","InputType","content","role","String","MessageRole","name","arguments","scope","ActionExecutionScope","actionExecutionId","actionName","result","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","Field","String","InputType","FrontendInput","toDeprecate_fullContext","actions","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","GenerateCopilotResponseInput","threadId","runId","messages","frontend","cloud","Field","String","nullable","MessageInput","FrontendInput","CloudInput","InputType","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","FailedResponseStatusReason","reason","details","GraphQLJSON","nullable","ResponseStatusUnion","createUnionType","types","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","undefined","role","content","MessageRole","ObjectType","implements","name","scope","arguments","ActionExecutionScope","actionExecutionId","actionName","result","CopilotResponse","threadId","runId","messages","ResponseStatusUnion","nullable","TextMessage","BaseMessage","content","role","ActionExecutionMessage","name","arguments","scope","ResultMessage","actionExecutionId","actionName","result","RuntimeEventTypes","import_graphql_scalars","GuardrailsValidationFailureResponse","FailedResponseStatus","reason","FailedResponseStatusReason","GUARDRAILS_VALIDATION_FAILED","constructor","guardrailsReason","details","MessageStreamInterruptedResponse","MESSAGE_STREAM_INTERRUPTED","messageId","description","UnknownErrorResponse","UNKNOWN_ERROR","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","generateCopilotResponse","ctx","properties","logger","child","component","debug","copilotRuntime","_copilotkit","runtime","serviceAdapter","copilotCloudBaseUrl","key","request","get","error","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","eventSource","threadId","nanoid","runId","actions","frontend","publicApiKey","response","status","firstValueFrom","Repeater","pushMessage","stopStreamingMessages","result","next","GuardrailsValidationFailureResponse","guardrailsReason","reason","plainToInstance","TextMessage","id","createdAt","Date","err","UnknownErrorResponse","description","eventStreamSubscription","eventStream","serversideActions","pipe","shareReplay","finalize","subscribe","event","type","RuntimeEventTypes","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","streamingTextStatus","Subject","messageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","unsubscribe","TextMessageContent","push","complete","SuccessMessageStatus","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","streamingArgumentsStatus","actionExecutionId","name","actionName","scope","arguments","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","ActionExecutionArgs","args","ActionExecutionMessage","ActionExecutionResult","ResultMessage","SuccessResponseStatus","Query","String","Mutation","CopilotResponse","Ctx","Arg","GraphQLJSONObject","nullable","Resolver","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","logger","createLogger","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","logging","plugins","useDeferStream","context","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint"]}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
copilotRuntimeNodeHttpEndpoint
|
|
3
|
-
} from "../../../chunk-
|
|
4
|
-
import "../../../chunk-
|
|
5
|
-
import "../../../chunk-
|
|
6
|
-
import "../../../chunk-
|
|
3
|
+
} from "../../../chunk-6YGDE3YI.mjs";
|
|
4
|
+
import "../../../chunk-FRK6BXXV.mjs";
|
|
5
|
+
import "../../../chunk-BYB2LNMK.mjs";
|
|
6
|
+
import "../../../chunk-OZMCHYYR.mjs";
|
|
7
|
+
import "../../../chunk-6NZ4UMOD.mjs";
|
|
8
|
+
import "../../../chunk-RHQLCJGG.mjs";
|
|
7
9
|
export {
|
|
8
10
|
copilotRuntimeNodeHttpEndpoint
|
|
9
11
|
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import * as graphql_yoga from 'graphql-yoga';
|
|
2
|
+
import { YogaServerInstance } from 'graphql-yoga';
|
|
3
|
+
import { c as CreateCopilotRuntimeServerOptions, G as GraphQLContext } from './index-0e75acd2.js';
|
|
4
|
+
|
|
5
|
+
declare function copilotRuntimeNextJSAppRouterEndpoint(options: CreateCopilotRuntimeServerOptions): {
|
|
6
|
+
handleRequest: graphql_yoga.YogaServerInstance<{}, Partial<GraphQLContext>>;
|
|
7
|
+
GET: any;
|
|
8
|
+
POST: any;
|
|
9
|
+
OPTIONS: any;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
declare const config: {
|
|
13
|
+
api: {
|
|
14
|
+
bodyParser: boolean;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
type CopilotRuntimeServerInstance<T> = YogaServerInstance<T, Partial<GraphQLContext>>;
|
|
18
|
+
|
|
19
|
+
declare function copilotRuntimeNextJSPagesRouterEndpoint(options: CreateCopilotRuntimeServerOptions): CopilotRuntimeServerInstance<GraphQLContext>;
|
|
20
|
+
|
|
21
|
+
export { CopilotRuntimeServerInstance as C, config as a, copilotRuntimeNextJSPagesRouterEndpoint as b, copilotRuntimeNextJSAppRouterEndpoint as c };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { C as CopilotServiceAdapter,
|
|
2
|
-
export { G as GoogleGenerativeAIAdapter, L as LangChainAdapter, a as OpenAIAdapter, c as OpenAIAssistantAdapter } from '../langchain-adapter-
|
|
1
|
+
export { C as CopilotServiceAdapter, d as RemoteChain, R as RemoteChainParameters } from '../langserve-75ebbc38.js';
|
|
2
|
+
export { G as GoogleGenerativeAIAdapter, L as LangChainAdapter, a as OpenAIAdapter, c as OpenAIAssistantAdapter } from '../langchain-adapter-a02d1d38.js';
|
|
3
3
|
import '../index-aa091e3c.js';
|
|
4
4
|
import '../graphql/types/base/index.js';
|
|
5
5
|
import 'rxjs';
|
|
@@ -242,6 +242,7 @@ function convertSystemMessageToAssistantAPI(message) {
|
|
|
242
242
|
__name(convertSystemMessageToAssistantAPI, "convertSystemMessageToAssistantAPI");
|
|
243
243
|
|
|
244
244
|
// src/service-adapters/openai/openai-adapter.ts
|
|
245
|
+
var import_nanoid = require("nanoid");
|
|
245
246
|
var DEFAULT_MODEL = "gpt-4o";
|
|
246
247
|
var OpenAIAdapter = class {
|
|
247
248
|
model = DEFAULT_MODEL;
|
|
@@ -255,7 +256,8 @@ var OpenAIAdapter = class {
|
|
|
255
256
|
this.model = params.model;
|
|
256
257
|
}
|
|
257
258
|
}
|
|
258
|
-
async process(
|
|
259
|
+
async process(request) {
|
|
260
|
+
const { threadId, model = this.model, messages, actions, eventSource } = request;
|
|
259
261
|
const tools = actions.map(convertActionInputToOpenAITool);
|
|
260
262
|
let openaiMessages = messages.map(convertMessageToOpenAIMessage);
|
|
261
263
|
openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
|
|
@@ -302,7 +304,9 @@ var OpenAIAdapter = class {
|
|
|
302
304
|
}
|
|
303
305
|
eventStream$.complete();
|
|
304
306
|
});
|
|
305
|
-
return {
|
|
307
|
+
return {
|
|
308
|
+
threadId: threadId || (0, import_nanoid.nanoid)()
|
|
309
|
+
};
|
|
306
310
|
}
|
|
307
311
|
};
|
|
308
312
|
__name(OpenAIAdapter, "OpenAIAdapter");
|
|
@@ -320,8 +324,9 @@ var OpenAIAssistantAdapter = class {
|
|
|
320
324
|
this.fileSearchEnabled = params.fileSearchEnabled === false || true;
|
|
321
325
|
this.assistantId = params.assistantId;
|
|
322
326
|
}
|
|
323
|
-
async process(
|
|
324
|
-
|
|
327
|
+
async process(request) {
|
|
328
|
+
const { messages, actions, eventSource, runId } = request;
|
|
329
|
+
let threadId = request.threadId || (await this.openai.beta.threads.create()).id;
|
|
325
330
|
const lastMessage = messages.at(-1);
|
|
326
331
|
let nextRunId = void 0;
|
|
327
332
|
if (lastMessage instanceof ResultMessage && runId) {
|
|
@@ -491,7 +496,7 @@ function convertMessageToGoogleGenAIMessage(message) {
|
|
|
491
496
|
};
|
|
492
497
|
} else if (message instanceof ResultMessage) {
|
|
493
498
|
return {
|
|
494
|
-
role: "
|
|
499
|
+
role: "function",
|
|
495
500
|
parts: [
|
|
496
501
|
{
|
|
497
502
|
functionResponse: {
|
|
@@ -546,7 +551,7 @@ function tryParseJson(str) {
|
|
|
546
551
|
__name(tryParseJson, "tryParseJson");
|
|
547
552
|
|
|
548
553
|
// src/service-adapters/google/google-genai-adapter.ts
|
|
549
|
-
var
|
|
554
|
+
var import_nanoid2 = require("nanoid");
|
|
550
555
|
var GoogleGenerativeAIAdapter = class {
|
|
551
556
|
model;
|
|
552
557
|
constructor(options) {
|
|
@@ -608,9 +613,12 @@ var GoogleGenerativeAIAdapter = class {
|
|
|
608
613
|
let isTextMessage = false;
|
|
609
614
|
for await (const chunk of result.stream) {
|
|
610
615
|
const chunkText = chunk.text();
|
|
616
|
+
if (chunkText === "") {
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
611
619
|
if (!isTextMessage) {
|
|
612
620
|
isTextMessage = true;
|
|
613
|
-
eventStream$.sendTextMessageStart((0,
|
|
621
|
+
eventStream$.sendTextMessageStart((0, import_nanoid2.nanoid)());
|
|
614
622
|
}
|
|
615
623
|
eventStream$.sendTextMessageContent(chunkText);
|
|
616
624
|
}
|
|
@@ -620,12 +628,14 @@ var GoogleGenerativeAIAdapter = class {
|
|
|
620
628
|
let calls = (await result.response).functionCalls();
|
|
621
629
|
if (calls) {
|
|
622
630
|
for (let call of calls) {
|
|
623
|
-
eventStream$.sendActionExecution((0,
|
|
631
|
+
eventStream$.sendActionExecution((0, import_nanoid2.nanoid)(), call.name, JSON.stringify(replaceNewlinesInObject(call.args)));
|
|
624
632
|
}
|
|
625
633
|
}
|
|
626
634
|
eventStream$.complete();
|
|
627
635
|
});
|
|
628
|
-
return {
|
|
636
|
+
return {
|
|
637
|
+
threadId: request.threadId || (0, import_nanoid2.nanoid)()
|
|
638
|
+
};
|
|
629
639
|
}
|
|
630
640
|
};
|
|
631
641
|
__name(GoogleGenerativeAIAdapter, "GoogleGenerativeAIAdapter");
|
|
@@ -651,7 +661,7 @@ __name(replaceNewlinesInObject, "replaceNewlinesInObject");
|
|
|
651
661
|
var import_messages = require("@langchain/core/messages");
|
|
652
662
|
var import_tools = require("@langchain/core/tools");
|
|
653
663
|
var import_zod = require("zod");
|
|
654
|
-
var
|
|
664
|
+
var import_nanoid3 = require("nanoid");
|
|
655
665
|
function convertMessageToLangChainMessage(message) {
|
|
656
666
|
if (message instanceof TextMessage) {
|
|
657
667
|
if (message.role == "user") {
|
|
@@ -715,31 +725,59 @@ function convertActionInputToLangChainTool(actionInput) {
|
|
|
715
725
|
});
|
|
716
726
|
}
|
|
717
727
|
__name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
|
|
728
|
+
function getConstructorName(object) {
|
|
729
|
+
if (object && typeof object === "object" && object.constructor && object.constructor.name) {
|
|
730
|
+
return object.constructor.name;
|
|
731
|
+
}
|
|
732
|
+
return "";
|
|
733
|
+
}
|
|
734
|
+
__name(getConstructorName, "getConstructorName");
|
|
735
|
+
function isAIMessage(message) {
|
|
736
|
+
return getConstructorName(message) === "AIMessage";
|
|
737
|
+
}
|
|
738
|
+
__name(isAIMessage, "isAIMessage");
|
|
739
|
+
function isAIMessageChunk(message) {
|
|
740
|
+
return getConstructorName(message) === "AIMessageChunk";
|
|
741
|
+
}
|
|
742
|
+
__name(isAIMessageChunk, "isAIMessageChunk");
|
|
743
|
+
function isBaseMessageChunk(message) {
|
|
744
|
+
return getConstructorName(message) === "BaseMessageChunk";
|
|
745
|
+
}
|
|
746
|
+
__name(isBaseMessageChunk, "isBaseMessageChunk");
|
|
747
|
+
function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution) {
|
|
748
|
+
if (actionExecution) {
|
|
749
|
+
eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, "Sending a message");
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
__name(maybeSendActionExecutionResultIsMessage, "maybeSendActionExecutionResultIsMessage");
|
|
718
753
|
async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
|
|
719
754
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
720
755
|
if (typeof result === "string") {
|
|
721
756
|
if (!actionExecution) {
|
|
722
|
-
eventStream$.sendTextMessage((0,
|
|
757
|
+
eventStream$.sendTextMessage((0, import_nanoid3.nanoid)(), result);
|
|
723
758
|
} else {
|
|
724
759
|
eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);
|
|
725
760
|
}
|
|
726
|
-
} else if (result
|
|
761
|
+
} else if (isAIMessage(result)) {
|
|
762
|
+
maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
|
|
727
763
|
if (result.content) {
|
|
728
|
-
eventStream$.sendTextMessage((0,
|
|
764
|
+
eventStream$.sendTextMessage((0, import_nanoid3.nanoid)(), result.content);
|
|
729
765
|
}
|
|
730
766
|
for (const toolCall of result.tool_calls) {
|
|
731
|
-
eventStream$.sendActionExecution(toolCall.id || (0,
|
|
767
|
+
eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid3.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
|
|
732
768
|
}
|
|
733
|
-
} else if (result
|
|
769
|
+
} else if (isBaseMessageChunk(result)) {
|
|
770
|
+
maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
|
|
734
771
|
if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
|
|
735
|
-
eventStream$.sendTextMessage((0,
|
|
772
|
+
eventStream$.sendTextMessage((0, import_nanoid3.nanoid)(), result.content);
|
|
736
773
|
}
|
|
737
774
|
if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
|
|
738
775
|
for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
|
|
739
|
-
eventStream$.sendActionExecution(toolCall.id || (0,
|
|
776
|
+
eventStream$.sendActionExecution(toolCall.id || (0, import_nanoid3.nanoid)(), toolCall.name, JSON.stringify(toolCall.args));
|
|
740
777
|
}
|
|
741
778
|
}
|
|
742
|
-
} else if ("getReader" in result) {
|
|
779
|
+
} else if (result && "getReader" in result) {
|
|
780
|
+
maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
|
|
743
781
|
let reader = result.getReader();
|
|
744
782
|
let mode = null;
|
|
745
783
|
while (true) {
|
|
@@ -749,14 +787,14 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
|
|
|
749
787
|
let toolCallId = void 0;
|
|
750
788
|
let toolCallArgs = void 0;
|
|
751
789
|
let hasToolCall = false;
|
|
752
|
-
let content = value.content;
|
|
753
|
-
if (value
|
|
790
|
+
let content = value == null ? void 0 : value.content;
|
|
791
|
+
if (isAIMessageChunk(value)) {
|
|
754
792
|
let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
|
|
755
793
|
toolCallName = chunk == null ? void 0 : chunk.name;
|
|
756
794
|
toolCallId = chunk == null ? void 0 : chunk.id;
|
|
757
795
|
toolCallArgs = chunk == null ? void 0 : chunk.args;
|
|
758
796
|
hasToolCall = chunk != void 0;
|
|
759
|
-
} else if (value
|
|
797
|
+
} else if (isBaseMessageChunk(value)) {
|
|
760
798
|
let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
|
|
761
799
|
toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
|
|
762
800
|
toolCallId = chunk == null ? void 0 : chunk.id;
|
|
@@ -779,7 +817,7 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
|
|
|
779
817
|
eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
|
|
780
818
|
} else if (content) {
|
|
781
819
|
mode = "message";
|
|
782
|
-
eventStream$.sendTextMessageStart((0,
|
|
820
|
+
eventStream$.sendTextMessageStart((0, import_nanoid3.nanoid)());
|
|
783
821
|
}
|
|
784
822
|
}
|
|
785
823
|
if (mode === "message" && content) {
|
|
@@ -793,15 +831,26 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
|
|
|
793
831
|
}
|
|
794
832
|
}
|
|
795
833
|
} else if (actionExecution) {
|
|
796
|
-
eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name,
|
|
834
|
+
eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, encodeResult(result));
|
|
797
835
|
} else {
|
|
798
836
|
throw new Error("Invalid return type from LangChain function.");
|
|
799
837
|
}
|
|
800
838
|
eventStream$.complete();
|
|
801
839
|
}
|
|
802
840
|
__name(streamLangChainResponse, "streamLangChainResponse");
|
|
841
|
+
function encodeResult(result) {
|
|
842
|
+
if (result === void 0) {
|
|
843
|
+
return "";
|
|
844
|
+
} else if (typeof result === "string") {
|
|
845
|
+
return result;
|
|
846
|
+
} else {
|
|
847
|
+
return JSON.stringify(result);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
__name(encodeResult, "encodeResult");
|
|
803
851
|
|
|
804
852
|
// src/service-adapters/langchain/langchain-adapter.ts
|
|
853
|
+
var import_nanoid4 = require("nanoid");
|
|
805
854
|
var LangChainAdapter = class {
|
|
806
855
|
options;
|
|
807
856
|
/**
|
|
@@ -810,7 +859,8 @@ var LangChainAdapter = class {
|
|
|
810
859
|
constructor(options) {
|
|
811
860
|
this.options = options;
|
|
812
861
|
}
|
|
813
|
-
async process(
|
|
862
|
+
async process(request) {
|
|
863
|
+
const { eventSource, model, actions, messages, threadId, runId } = request;
|
|
814
864
|
const result = await this.options.chainFn({
|
|
815
865
|
messages: messages.map(convertMessageToLangChainMessage),
|
|
816
866
|
tools: actions.map(convertActionInputToLangChainTool),
|
|
@@ -824,7 +874,9 @@ var LangChainAdapter = class {
|
|
|
824
874
|
eventStream$
|
|
825
875
|
});
|
|
826
876
|
});
|
|
827
|
-
return {
|
|
877
|
+
return {
|
|
878
|
+
threadId: threadId || (0, import_nanoid4.nanoid)()
|
|
879
|
+
};
|
|
828
880
|
}
|
|
829
881
|
};
|
|
830
882
|
__name(LangChainAdapter, "LangChainAdapter");
|
|
@@ -832,6 +884,11 @@ __name(LangChainAdapter, "LangChainAdapter");
|
|
|
832
884
|
// src/service-adapters/langchain/langserve.ts
|
|
833
885
|
var import_remote = require("langchain/runnables/remote");
|
|
834
886
|
var RemoteChain = class {
|
|
887
|
+
name;
|
|
888
|
+
description;
|
|
889
|
+
chainUrl;
|
|
890
|
+
parameters;
|
|
891
|
+
parameterType;
|
|
835
892
|
constructor(options) {
|
|
836
893
|
this.name = options.name;
|
|
837
894
|
this.description = options.description;
|