@copilotkit/runtime 1.71.2 → 1.72.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/dist/agent/index.cjs +1 -1
- package/dist/agent/index.mjs +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs +13 -8
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +13 -8
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/service-adapters/experimental/ollama/ollama-adapter.cjs +16 -0
- package/dist/service-adapters/experimental/ollama/ollama-adapter.cjs.map +1 -1
- package/dist/service-adapters/experimental/ollama/ollama-adapter.d.cts +14 -0
- package/dist/service-adapters/experimental/ollama/ollama-adapter.d.cts.map +1 -1
- package/dist/service-adapters/experimental/ollama/ollama-adapter.d.mts +14 -0
- package/dist/service-adapters/experimental/ollama/ollama-adapter.d.mts.map +1 -1
- package/dist/service-adapters/experimental/ollama/ollama-adapter.mjs +16 -0
- package/dist/service-adapters/experimental/ollama/ollama-adapter.mjs.map +1 -1
- package/dist/service-adapters/google/google-genai-adapter.cjs +17 -0
- package/dist/service-adapters/google/google-genai-adapter.cjs.map +1 -1
- package/dist/service-adapters/google/google-genai-adapter.d.cts +10 -0
- package/dist/service-adapters/google/google-genai-adapter.d.cts.map +1 -1
- package/dist/service-adapters/google/google-genai-adapter.d.mts +10 -0
- package/dist/service-adapters/google/google-genai-adapter.d.mts.map +1 -1
- package/dist/service-adapters/google/google-genai-adapter.mjs +16 -0
- package/dist/service-adapters/google/google-genai-adapter.mjs.map +1 -1
- package/dist/service-adapters/unify/unify-adapter.cjs +14 -2
- package/dist/service-adapters/unify/unify-adapter.cjs.map +1 -1
- package/dist/service-adapters/unify/unify-adapter.d.cts +9 -1
- package/dist/service-adapters/unify/unify-adapter.d.cts.map +1 -1
- package/dist/service-adapters/unify/unify-adapter.d.mts +9 -1
- package/dist/service-adapters/unify/unify-adapter.d.mts.map +1 -1
- package/dist/service-adapters/unify/unify-adapter.mjs +14 -2
- package/dist/service-adapters/unify/unify-adapter.mjs.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-runtime.mjs","names":["telemetry","CopilotRuntimeVNext"],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotKitEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — CopilotRuntime:\n * V2 import and usage:\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * V2 replacement source: packages/runtime/src/v2/runtime/core/runtime.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n * Migration note: V2 uses AG-UI runtime handlers instead of the v1 GraphQL adapter setup.\n *\n * @copilotkit/runtime — CopilotRuntimeConstructorParams_BASE:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — langGraphPlatformEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — resolveEndpointType:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/backend/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n CopilotKitMisuseError,\n readBody,\n getZodParameters,\n isTelemetryDisabled,\n} from \"@copilotkit/shared\";\nimport type {\n Action,\n CopilotErrorHandler,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n PartialBy,\n DebugConfig,\n TelemetryCapture,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n InMemoryAgentRunner,\n} from \"../../../v2/runtime\";\nimport {\n createRuntimeErrorReporter,\n runtimeErrorReporterOption,\n} from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type { RuntimeErrorReporterOptions } from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type {\n CopilotIntelligenceRuntimeOptions,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n AgentRunner,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\nimport telemetry from \"../telemetry-client\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry-disclosure\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport { EndpointType } from \"./types\";\nimport type {\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../../../v2/runtime/telemetry/telemetry-identity\";\n\n// +++ MCP Imports +++\nimport { extractParametersFromSchema } from \"./mcp-tools-utils\";\nimport type { MCPClient, MCPEndpointConfig, MCPTool } from \"./mcp-tools-utils\";\nimport { BuiltInAgent } from \"../../../agent\";\nimport type { BuiltInAgentClassicConfig } from \"../../../agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n\n intelligence?: CopilotIntelligenceRuntimeOptions[\"intelligence\"];\n identifyUser?: CopilotIntelligenceRuntimeOptions[\"identifyUser\"];\n memory?: CopilotIntelligenceRuntimeOptions[\"memory\"];\n channels?: CopilotIntelligenceRuntimeOptions[\"channels\"];\n ɵlearning?: CopilotIntelligenceRuntimeOptions[\"ɵlearning\"];\n generateThreadNames?: CopilotIntelligenceRuntimeOptions[\"generateThreadNames\"];\n maxReconnectMs?: CopilotIntelligenceRuntimeOptions[\"maxReconnectMs\"];\n maxRejoinMs?: CopilotIntelligenceRuntimeOptions[\"maxRejoinMs\"];\n lockTtlSeconds?: CopilotIntelligenceRuntimeOptions[\"lockTtlSeconds\"];\n lockKeyPrefix?: CopilotIntelligenceRuntimeOptions[\"lockKeyPrefix\"];\n lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions[\"lockHeartbeatIntervalSeconds\"];\n}\n\n/**\n * Central runtime object passed to all request handlers.\n * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * ```\n * See https://docs.copilotkit.ai/runtime-server-adapter\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\n private runtimeArgs: CopilotRuntimeOptions & RuntimeErrorReporterOptions;\n private _instance: CopilotRuntimeVNext;\n /** Runtime-bound telemetry identity and sampling authority. */\n public readonly telemetry: TelemetryCapture;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n logRuntimeTelemetryDisclosure();\n\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Resolve identity once and bind it to this compatibility Runtime. The\n // capture scope shares process-level sinks and settings without exposing\n // mutable identity to other live runtimes.\n const resolvedLicenseToken = firstNonBlankLicenseToken(\n params?.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n params?.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n const resolvedTelemetryIdentity =\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : resolvedLicenseToken !== undefined\n ? { licenseToken: resolvedLicenseToken }\n : {};\n this.telemetry = telemetry.createScope(resolvedTelemetryIdentity);\n\n // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner.\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({\n runner: baseRunner,\n telemetry: this.telemetry,\n });\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\n telemetryProperties: params?.telemetryProperties,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),\n forwardHeaders: params?.forwardHeaders,\n exposeMemoryRoutes: params?.exposeMemoryRoutes,\n };\n if (params?.intelligence !== undefined) {\n // The compatibility constructor keeps Intelligence identity optional at\n // compile time, while the v2 runtime checks that callers supply web\n // identity, Channels, or both. Preserve that runtime validation here.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n intelligence: params.intelligence,\n identifyUser: params.identifyUser,\n memory: params.memory,\n channels: params.channels,\n ɵlearning: params.ɵlearning,\n generateThreadNames: params.generateThreadNames,\n maxReconnectMs: params.maxReconnectMs,\n maxRejoinMs: params.maxRejoinMs,\n lockTtlSeconds: params.lockTtlSeconds,\n lockKeyPrefix: params.lockKeyPrefix,\n lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds,\n } as CopilotRuntimeOptions;\n } else {\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n runner,\n };\n }\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n // An AgentsFactory function has no enumerable keys, so it flows through\n // this path the same way an empty record does.\n let agentsList = agents as Record<string, AbstractAgent>;\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (serviceAdapter.provider && serviceAdapter.model) {\n // Adapter exposes provider/model strings\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else {\n throw new CopilotKitMisuseError({\n message:\n `Service adapter \"${serviceAdapter.name ?? \"unknown\"}\" does not provide model information. ` +\n `When using adapters like LangChainAdapter without an explicit agents list, ` +\n `please provide a default agent in the runtime config. Example:\\n` +\n ` new CopilotRuntime({\\n` +\n ` agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o\" }) }\\n` +\n ` })`,\n });\n }\n }\n\n const actions = this.params?.actions;\n if (actions) {\n const mcpTools = await this.getToolsFromMCP();\n agentsList = this.assignToolsToAgents(agentsList, [\n ...this.getToolsFromActions(actions),\n ...mcpTools,\n ]);\n }\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig =\n existingConfig as unknown as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...tools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n this.telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<BuiltInAgentClassicConfig[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n // Cache empty to prevent repeated attempts within lifecycle\n this.mcpToolsCache.set(endpointUrl, []);\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqaA,IAAa,iBAAb,MAAmE;CAWjE,YAAY,QAA6C;uCANvD,IAAI,KAAK;AAOT,iCAA+B;EAE/B,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,WACpB,gBAAe,OAAO,QAAQ;GAC5B,MAAM,WAAW,MAAM,OAAO,IAAI;AAClC,UAAO;IAAE,GAAG;IAAgB,GAAG;IAAU;;MAG3C,gBAAe,QAAQ,QAAQ,OAAO,CAAC,MAAM,cAAc;GACzD,GAAG;GACH,GAAG;GACJ,EAAE;EAML,MAAM,uBAAuB,0BAC3B,QAAQ,cACR,QAAQ,IAAI,yBACb;EACD,MA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AS,KAAK,GAAG,SAAS;YACnB,OAAO;AACd,YAAQ,MACN,4CAA4C,YAAY,qBACxD,MACD;AAED,SAAK,cAAc,IAAI,aAAa,EAAE,CAAC;;;EAK3C,MAAM,gCAAgB,IAAI,KAAwC;AAClE,OAAK,MAAM,QAAQ,SACjB,eAAc,IAAI,KAAK,MAAM,KAAK;AAGpC,SAAO,MAAM,KAAK,cAAc,QAAQ,CAAC;;;AAK7C,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAO,aAAa;KAEpB,QAAO,aAAa;AAIxB,QAAO,SAAS"}
|
|
1
|
+
{"version":3,"file":"copilot-runtime.mjs","names":["telemetry","CopilotRuntimeVNext"],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotKitEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — CopilotRuntime:\n * V2 import and usage:\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * V2 replacement source: packages/runtime/src/v2/runtime/core/runtime.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n * Migration note: V2 uses AG-UI runtime handlers instead of the v1 GraphQL adapter setup.\n *\n * @copilotkit/runtime — CopilotRuntimeConstructorParams_BASE:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — langGraphPlatformEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — resolveEndpointType:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/backend/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n CopilotKitMisuseError,\n readBody,\n getZodParameters,\n isTelemetryDisabled,\n} from \"@copilotkit/shared\";\nimport type {\n Action,\n CopilotErrorHandler,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n PartialBy,\n DebugConfig,\n TelemetryCapture,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n InMemoryAgentRunner,\n} from \"../../../v2/runtime\";\nimport {\n createRuntimeErrorReporter,\n runtimeErrorReporterOption,\n} from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type { RuntimeErrorReporterOptions } from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type {\n CopilotIntelligenceRuntimeOptions,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n AgentRunner,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\nimport telemetry from \"../telemetry-client\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry-disclosure\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport { EndpointType } from \"./types\";\nimport type {\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../../../v2/runtime/telemetry/telemetry-identity\";\n\n// +++ MCP Imports +++\nimport { extractParametersFromSchema } from \"./mcp-tools-utils\";\nimport type { MCPClient, MCPEndpointConfig, MCPTool } from \"./mcp-tools-utils\";\nimport { BuiltInAgent } from \"../../../agent\";\nimport type { BuiltInAgentClassicConfig } from \"../../../agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n\n intelligence?: CopilotIntelligenceRuntimeOptions[\"intelligence\"];\n identifyUser?: CopilotIntelligenceRuntimeOptions[\"identifyUser\"];\n memory?: CopilotIntelligenceRuntimeOptions[\"memory\"];\n channels?: CopilotIntelligenceRuntimeOptions[\"channels\"];\n ɵlearning?: CopilotIntelligenceRuntimeOptions[\"ɵlearning\"];\n generateThreadNames?: CopilotIntelligenceRuntimeOptions[\"generateThreadNames\"];\n maxReconnectMs?: CopilotIntelligenceRuntimeOptions[\"maxReconnectMs\"];\n maxRejoinMs?: CopilotIntelligenceRuntimeOptions[\"maxRejoinMs\"];\n lockTtlSeconds?: CopilotIntelligenceRuntimeOptions[\"lockTtlSeconds\"];\n lockKeyPrefix?: CopilotIntelligenceRuntimeOptions[\"lockKeyPrefix\"];\n lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions[\"lockHeartbeatIntervalSeconds\"];\n}\n\n/**\n * Central runtime object passed to all request handlers.\n * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * ```\n * See https://docs.copilotkit.ai/runtime-server-adapter\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\n private runtimeArgs: CopilotRuntimeOptions & RuntimeErrorReporterOptions;\n private _instance: CopilotRuntimeVNext;\n /** Runtime-bound telemetry identity and sampling authority. */\n public readonly telemetry: TelemetryCapture;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n logRuntimeTelemetryDisclosure();\n\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Resolve identity once and bind it to this compatibility Runtime. The\n // capture scope shares process-level sinks and settings without exposing\n // mutable identity to other live runtimes.\n const resolvedLicenseToken = firstNonBlankLicenseToken(\n params?.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n params?.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n const resolvedTelemetryIdentity =\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : resolvedLicenseToken !== undefined\n ? { licenseToken: resolvedLicenseToken }\n : {};\n this.telemetry = telemetry.createScope(resolvedTelemetryIdentity);\n\n // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner.\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({\n runner: baseRunner,\n telemetry: this.telemetry,\n });\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\n telemetryProperties: params?.telemetryProperties,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),\n forwardHeaders: params?.forwardHeaders,\n exposeMemoryRoutes: params?.exposeMemoryRoutes,\n };\n if (params?.intelligence !== undefined) {\n // The compatibility constructor keeps Intelligence identity optional at\n // compile time, while the v2 runtime checks that callers supply web\n // identity, Channels, or both. Preserve that runtime validation here.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n intelligence: params.intelligence,\n identifyUser: params.identifyUser,\n memory: params.memory,\n channels: params.channels,\n ɵlearning: params.ɵlearning,\n generateThreadNames: params.generateThreadNames,\n maxReconnectMs: params.maxReconnectMs,\n maxRejoinMs: params.maxRejoinMs,\n lockTtlSeconds: params.lockTtlSeconds,\n lockKeyPrefix: params.lockKeyPrefix,\n lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds,\n } as CopilotRuntimeOptions;\n } else {\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n runner,\n };\n }\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n // An AgentsFactory function has no enumerable keys, so it flows through\n // this path the same way an empty record does.\n let agentsList = agents as Record<string, AbstractAgent>;\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (serviceAdapter.provider && serviceAdapter.model) {\n // Adapter exposes provider/model strings\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else {\n throw new CopilotKitMisuseError({\n message:\n `Service adapter \"${serviceAdapter.name ?? \"unknown\"}\" does not provide model information. ` +\n `When using adapters like LangChainAdapter without an explicit agents list, ` +\n `please provide a default agent in the runtime config. Example:\\n` +\n ` new CopilotRuntime({\\n` +\n ` agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o\" }) }\\n` +\n ` })`,\n });\n }\n }\n\n const actions = this.params?.actions;\n\n // `actions` and `mcpServers` are attached independently: a runtime may\n // configure MCP servers without any local actions.\n const mcpTools = await this.getToolsFromMCP();\n const actionTools = actions ? this.getToolsFromActions(actions) : [];\n agentsList = this.assignToolsToAgents(agentsList, [\n ...actionTools,\n ...mcpTools,\n ]);\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n // `handler` is an in-process function and was never part of the remote\n // executor deleted in v1.50.0 — only the wiring to it was lost. Call it.\n //\n // The result must never be `undefined`: `JSON.stringify(undefined)` is\n // not a string, which strips the required `content` off\n // TOOL_CALL_RESULT and surfaces as a Zod error in the browser\n // (#2915, #3198). Both branches below return a string instead.\n execute: async (args: unknown) => {\n if (typeof action.handler !== \"function\") {\n return (\n `The tool \"${action.name}\" was advertised without a handler, so it ` +\n `has no implementation to run. Tell the user this tool is unavailable.`\n );\n }\n const result = await action.handler(args as any);\n return result === undefined\n ? `The tool \"${action.name}\" ran and returned no value.`\n : result;\n },\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig =\n existingConfig as unknown as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n // The endpoint factory runs `handleServiceAdapter` every time it is\n // called, and the documented v1 route builds the endpoint inside the\n // request handler — so a module-scope runtime lands here once per\n // request. Appending unconditionally advertised N copies of every tool\n // to the model. Skip names the agent already carries, which also leaves\n // a tool the agent defines itself in place.\n const existingNames = new Set(existingTools.map((tool) => tool.name));\n const newTools = tools.filter((tool) => !existingNames.has(tool.name));\n if (newTools.length === 0) {\n continue;\n }\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...newTools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n this.telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<BuiltInAgentClassicConfig[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n // The MCP client stays live for the lifetime of the cached tool\n // definitions; `tool.execute` calls the server.\n execute: async (args: unknown) => tool.execute(args),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n // Deliberately not cached. Caching the empty result meant a server\n // that was briefly unreachable when the runtime first resolved stayed\n // toolless for the life of that runtime, even after it recovered.\n // Leaving the entry absent lets a later resolution try again.\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqaA,IAAa,iBAAb,MAAmE;CAWjE,YAAY,QAA6C;uCANvD,IAAI,KAAK;AAOT,iCAA+B;EAE/B,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,WACpB,gBAAe,OAAO,QAAQ;GAC5B,MAAM,WAAW,MAAM,OAAO,IAAI;AAClC,UAAO;IAAE,GAAG;IAAgB,GAAG;IAAU;;MAG3C,gBAAe,QAAQ,QAAQ,OAAO,CAAC,MAAM,cAAc;GACzD,GAAG;GACH,GAAG;GACJ,EAAE;EAML,MAAM,uBAAuB,0BAC3B,QAAQ,cACR,QAAQ,IAAI,yBACb;EACD,MAAM,sBAAsB,yBAC1B,QAAQ,aACR,QAAQ,IAAI,iBACb;EACD,MAAM,4BACJ,wBAAwB,SACpB,EAAE,aAAa,qBAAqB,GACpC,yBAAyB,SACvB,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U,UAA6B;KAE7C,MAAM,YAAY,iBADU,4BAA4B,KAAK,CACnB;AAC1C,YAAO;MACL,MAAM;MACN,aACE,KAAK,eAAe,aAAa,SAAS,SAAS,YAAY;MACjE,YAAY;MAGZ,SAAS,OAAO,SAAkB,KAAK,QAAQ,KAAK;MACrD;MACD;AAGF,SAAK,cAAc,IAAI,aAAa,SAAS;AAC7C,aAAS,KAAK,GAAG,SAAS;YACnB,OAAO;AACd,YAAQ,MACN,4CAA4C,YAAY,qBACxD,MACD;;;EASL,MAAM,gCAAgB,IAAI,KAAwC;AAClE,OAAK,MAAM,QAAQ,SACjB,eAAc,IAAI,KAAK,MAAM,KAAK;AAGpC,SAAO,MAAM,KAAK,cAAc,QAAQ,CAAC;;;AAK7C,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAO,aAAa;KAEpB,QAAO,aAAa;AAIxB,QAAO,SAAS"}
|
package/dist/package.cjs
CHANGED
|
@@ -5,7 +5,7 @@ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
|
5
5
|
var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
|
|
6
6
|
module.exports = {
|
|
7
7
|
"name": "@copilotkit/runtime",
|
|
8
|
-
"version": "1.
|
|
8
|
+
"version": "1.72.0",
|
|
9
9
|
"private": false,
|
|
10
10
|
"keywords": [
|
|
11
11
|
"ai",
|
package/dist/package.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { __commonJSMin } from "./_virtual/_rolldown/runtime.mjs";
|
|
|
5
5
|
var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
6
6
|
module.exports = {
|
|
7
7
|
"name": "@copilotkit/runtime",
|
|
8
|
-
"version": "1.
|
|
8
|
+
"version": "1.72.0",
|
|
9
9
|
"private": false,
|
|
10
10
|
"keywords": [
|
|
11
11
|
"ai",
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
let _ai_sdk_openai = require("@ai-sdk/openai");
|
|
3
4
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
5
|
|
|
5
6
|
//#region src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts
|
|
6
7
|
const DEFAULT_MODEL = "llama3:latest";
|
|
8
|
+
const DEFAULT_BASE_URL = "http://127.0.0.1:11434";
|
|
7
9
|
var ExperimentalOllamaAdapter = class {
|
|
8
10
|
get name() {
|
|
9
11
|
return "OllamaAdapter";
|
|
10
12
|
}
|
|
11
13
|
constructor(options) {
|
|
12
14
|
this.provider = "ollama";
|
|
15
|
+
this.baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
|
|
13
16
|
if (options?.model) this.model = options.model;
|
|
14
17
|
else this.model = DEFAULT_MODEL;
|
|
15
18
|
}
|
|
@@ -31,6 +34,19 @@ var ExperimentalOllamaAdapter = class {
|
|
|
31
34
|
});
|
|
32
35
|
return { threadId: request.threadId || (0, _copilotkit_shared.randomUUID)() };
|
|
33
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Ollama exposes an OpenAI-compatible API at `/v1`, so the model is built
|
|
39
|
+
* from the OpenAI provider pointed at the Ollama server. Without it the
|
|
40
|
+
* runtime rebuilds a bare "ollama/<model>" string and fails with
|
|
41
|
+
* `Unknown provider "ollama"`. Ollama ignores the key; a non-empty value is
|
|
42
|
+
* required only because the OpenAI client insists on one.
|
|
43
|
+
*/
|
|
44
|
+
getLanguageModel() {
|
|
45
|
+
return (0, _ai_sdk_openai.createOpenAI)({
|
|
46
|
+
baseURL: `${this.baseUrl.replace(/\/$/, "")}/v1`,
|
|
47
|
+
apiKey: "ollama"
|
|
48
|
+
})(this.model);
|
|
49
|
+
}
|
|
34
50
|
};
|
|
35
51
|
|
|
36
52
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ollama-adapter.cjs","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — ExperimentalOllamaAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * CopilotKit Adapter for Ollama\n *\n * <RequestExample>\n * ```jsx CopilotRuntime Example\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new OllamaAdapter());\n * ```\n * </RequestExample>\n *\n * You can easily set the model to use by passing it to the constructor.\n * ```jsx\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(\n * req,\n * new OllamaAdapter({ model: \"llama3-70b-8192\" }),\n * );\n * ```\n */\nimport type { TextMessage } from \"../../../graphql/types/converted\";\nimport type {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../../service-adapter\";\nimport { randomId, randomUUID } from \"@copilotkit/shared\";\n\nconst DEFAULT_MODEL = \"llama3:latest\";\n\ninterface OllamaAdapterOptions {\n model?: string;\n}\n\nexport class ExperimentalOllamaAdapter implements CopilotServiceAdapter {\n public model: string;\n public provider = \"ollama\";\n public get name() {\n return \"OllamaAdapter\";\n }\n\n constructor(options?: OllamaAdapterOptions) {\n if (options?.model) {\n this.model = options.model;\n } else {\n this.model = DEFAULT_MODEL;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource } = request;\n // const messages = this.transformMessages(forwardedProps.messages);\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Ollama } = require(\"@langchain/community/llms/ollama\");\n const ollama = new Ollama({\n model: this.model,\n });\n const contents = (\n messages.filter((m) => m.isTextMessage()) as TextMessage[]\n ).map((m) => m.content);\n const _stream = await ollama.stream(contents); // [TODO] role info is dropped...\n\n eventSource.stream(async (eventStream$) => {\n const currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n for await (const chunkText of _stream) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: chunkText,\n });\n }\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n // we may need to add this later.. [nc]\n // let calls = (await result.response).functionCalls();\n\n eventStream$.complete();\n });\n return {\n threadId: request.threadId || randomUUID(),\n };\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ollama-adapter.cjs","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — ExperimentalOllamaAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * CopilotKit Adapter for Ollama\n *\n * <RequestExample>\n * ```jsx CopilotRuntime Example\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new OllamaAdapter());\n * ```\n * </RequestExample>\n *\n * You can easily set the model to use by passing it to the constructor.\n * ```jsx\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(\n * req,\n * new OllamaAdapter({ model: \"llama3-70b-8192\" }),\n * );\n * ```\n */\nimport type { TextMessage } from \"../../../graphql/types/converted\";\nimport type {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../../service-adapter\";\nimport { randomId, randomUUID } from \"@copilotkit/shared\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport type { LanguageModel } from \"ai\";\n\nconst DEFAULT_MODEL = \"llama3:latest\";\n\nconst DEFAULT_BASE_URL = \"http://127.0.0.1:11434\";\n\ninterface OllamaAdapterOptions {\n model?: string;\n /**\n * Base URL of the Ollama server. Defaults to `http://127.0.0.1:11434`.\n */\n baseUrl?: string;\n}\n\nexport class ExperimentalOllamaAdapter implements CopilotServiceAdapter {\n public model: string;\n public provider = \"ollama\";\n private baseUrl: string;\n public get name() {\n return \"OllamaAdapter\";\n }\n\n constructor(options?: OllamaAdapterOptions) {\n this.baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;\n if (options?.model) {\n this.model = options.model;\n } else {\n this.model = DEFAULT_MODEL;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource } = request;\n // const messages = this.transformMessages(forwardedProps.messages);\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Ollama } = require(\"@langchain/community/llms/ollama\");\n const ollama = new Ollama({\n model: this.model,\n });\n const contents = (\n messages.filter((m) => m.isTextMessage()) as TextMessage[]\n ).map((m) => m.content);\n const _stream = await ollama.stream(contents); // [TODO] role info is dropped...\n\n eventSource.stream(async (eventStream$) => {\n const currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n for await (const chunkText of _stream) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: chunkText,\n });\n }\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n // we may need to add this later.. [nc]\n // let calls = (await result.response).functionCalls();\n\n eventStream$.complete();\n });\n return {\n threadId: request.threadId || randomUUID(),\n };\n }\n\n /**\n * Ollama exposes an OpenAI-compatible API at `/v1`, so the model is built\n * from the OpenAI provider pointed at the Ollama server. Without it the\n * runtime rebuilds a bare \"ollama/<model>\" string and fails with\n * `Unknown provider \"ollama\"`. Ollama ignores the key; a non-empty value is\n * required only because the OpenAI client insists on one.\n */\n getLanguageModel(): LanguageModel {\n const provider = createOpenAI({\n baseURL: `${this.baseUrl.replace(/\\/$/, \"\")}/v1`,\n apiKey: \"ollama\",\n });\n return provider(this.model);\n }\n}\n"],"mappings":";;;;;;AAgDA,MAAM,gBAAgB;AAEtB,MAAM,mBAAmB;AAUzB,IAAa,4BAAb,MAAwE;CAItE,IAAW,OAAO;AAChB,SAAO;;CAGT,YAAY,SAAgC;kBAN1B;AAOhB,OAAK,UAAU,SAAS,WAAW;AACnC,MAAI,SAAS,MACX,MAAK,QAAQ,QAAQ;MAErB,MAAK,QAAQ;;CAIjB,MAAM,QACJ,SAC+C;EAC/C,MAAM,EAAE,UAAU,SAAS,gBAAgB;EAI3C,MAAM,EAAE,WAAW,QAAQ,mCAAmC;EAC9D,MAAM,SAAS,IAAI,OAAO,EACxB,OAAO,KAAK,OACb,CAAC;EACF,MAAM,WACJ,SAAS,QAAQ,MAAM,EAAE,eAAe,CAAC,CACzC,KAAK,MAAM,EAAE,QAAQ;EACvB,MAAM,UAAU,MAAM,OAAO,OAAO,SAAS;AAE7C,cAAY,OAAO,OAAO,iBAAiB;GACzC,MAAM,qDAA6B;AACnC,gBAAa,qBAAqB,EAAE,WAAW,kBAAkB,CAAC;AAClE,cAAW,MAAM,aAAa,QAC5B,cAAa,uBAAuB;IAClC,WAAW;IACX,SAAS;IACV,CAAC;AAEJ,gBAAa,mBAAmB,EAAE,WAAW,kBAAkB,CAAC;AAIhE,gBAAa,UAAU;IACvB;AACF,SAAO,EACL,UAAU,QAAQ,gDAAwB,EAC3C;;;;;;;;;CAUH,mBAAkC;AAKhC,0CAJ8B;GAC5B,SAAS,GAAG,KAAK,QAAQ,QAAQ,OAAO,GAAG,CAAC;GAC5C,QAAQ;GACT,CAAC,CACc,KAAK,MAAM"}
|
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
|
|
2
2
|
import { CopilotRuntimeChatCompletionRequest, CopilotRuntimeChatCompletionResponse, CopilotServiceAdapter } from "../../service-adapter.cjs";
|
|
3
|
+
import { LanguageModel } from "ai";
|
|
3
4
|
|
|
4
5
|
//#region src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.d.ts
|
|
5
6
|
interface OllamaAdapterOptions {
|
|
6
7
|
model?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Base URL of the Ollama server. Defaults to `http://127.0.0.1:11434`.
|
|
10
|
+
*/
|
|
11
|
+
baseUrl?: string;
|
|
7
12
|
}
|
|
8
13
|
declare class ExperimentalOllamaAdapter implements CopilotServiceAdapter {
|
|
9
14
|
model: string;
|
|
10
15
|
provider: string;
|
|
16
|
+
private baseUrl;
|
|
11
17
|
get name(): string;
|
|
12
18
|
constructor(options?: OllamaAdapterOptions);
|
|
13
19
|
process(request: CopilotRuntimeChatCompletionRequest): Promise<CopilotRuntimeChatCompletionResponse>;
|
|
20
|
+
/**
|
|
21
|
+
* Ollama exposes an OpenAI-compatible API at `/v1`, so the model is built
|
|
22
|
+
* from the OpenAI provider pointed at the Ollama server. Without it the
|
|
23
|
+
* runtime rebuilds a bare "ollama/<model>" string and fails with
|
|
24
|
+
* `Unknown provider "ollama"`. Ollama ignores the key; a non-empty value is
|
|
25
|
+
* required only because the OpenAI client insists on one.
|
|
26
|
+
*/
|
|
27
|
+
getLanguageModel(): LanguageModel;
|
|
14
28
|
}
|
|
15
29
|
//#endregion
|
|
16
30
|
export { ExperimentalOllamaAdapter };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ollama-adapter.d.cts","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ollama-adapter.d.cts","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"mappings":";;;;;UAoDU,oBAAA;EACR,KAAA;EADQ;;;EAKR,OAAA;AAAA;AAAA,cAGW,yBAAA,YAAqC,qBAAA;EACzC,KAAA;EACA,QAAA;EAAA,QACC,OAAA;EAAA,IACG,IAAA,CAAA;cAIC,OAAA,GAAU,oBAAA;EAShB,OAAA,CACJ,OAAA,EAAS,mCAAA,GACR,OAAA,CAAQ,oCAAA;EAyCS;;;;;;;EAApB,gBAAA,CAAA,GAAoB,aAAA;AAAA"}
|
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
|
|
2
2
|
import { CopilotRuntimeChatCompletionRequest, CopilotRuntimeChatCompletionResponse, CopilotServiceAdapter } from "../../service-adapter.mjs";
|
|
3
|
+
import { LanguageModel } from "ai";
|
|
3
4
|
|
|
4
5
|
//#region src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.d.ts
|
|
5
6
|
interface OllamaAdapterOptions {
|
|
6
7
|
model?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Base URL of the Ollama server. Defaults to `http://127.0.0.1:11434`.
|
|
10
|
+
*/
|
|
11
|
+
baseUrl?: string;
|
|
7
12
|
}
|
|
8
13
|
declare class ExperimentalOllamaAdapter implements CopilotServiceAdapter {
|
|
9
14
|
model: string;
|
|
10
15
|
provider: string;
|
|
16
|
+
private baseUrl;
|
|
11
17
|
get name(): string;
|
|
12
18
|
constructor(options?: OllamaAdapterOptions);
|
|
13
19
|
process(request: CopilotRuntimeChatCompletionRequest): Promise<CopilotRuntimeChatCompletionResponse>;
|
|
20
|
+
/**
|
|
21
|
+
* Ollama exposes an OpenAI-compatible API at `/v1`, so the model is built
|
|
22
|
+
* from the OpenAI provider pointed at the Ollama server. Without it the
|
|
23
|
+
* runtime rebuilds a bare "ollama/<model>" string and fails with
|
|
24
|
+
* `Unknown provider "ollama"`. Ollama ignores the key; a non-empty value is
|
|
25
|
+
* required only because the OpenAI client insists on one.
|
|
26
|
+
*/
|
|
27
|
+
getLanguageModel(): LanguageModel;
|
|
14
28
|
}
|
|
15
29
|
//#endregion
|
|
16
30
|
export { ExperimentalOllamaAdapter };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ollama-adapter.d.mts","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ollama-adapter.d.mts","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"mappings":";;;;;UAoDU,oBAAA;EACR,KAAA;EADQ;;;EAKR,OAAA;AAAA;AAAA,cAGW,yBAAA,YAAqC,qBAAA;EACzC,KAAA;EACA,QAAA;EAAA,QACC,OAAA;EAAA,IACG,IAAA,CAAA;cAIC,OAAA,GAAU,oBAAA;EAShB,OAAA,CACJ,OAAA,EAAS,mCAAA,GACR,OAAA,CAAQ,oCAAA;EAyCS;;;;;;;EAApB,gBAAA,CAAA,GAAoB,aAAA;AAAA"}
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
import { __require } from "../../../_virtual/_rolldown/runtime.mjs";
|
|
3
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
3
4
|
import { randomId, randomUUID } from "@copilotkit/shared";
|
|
4
5
|
|
|
5
6
|
//#region src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts
|
|
6
7
|
const DEFAULT_MODEL = "llama3:latest";
|
|
8
|
+
const DEFAULT_BASE_URL = "http://127.0.0.1:11434";
|
|
7
9
|
var ExperimentalOllamaAdapter = class {
|
|
8
10
|
get name() {
|
|
9
11
|
return "OllamaAdapter";
|
|
10
12
|
}
|
|
11
13
|
constructor(options) {
|
|
12
14
|
this.provider = "ollama";
|
|
15
|
+
this.baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
|
|
13
16
|
if (options?.model) this.model = options.model;
|
|
14
17
|
else this.model = DEFAULT_MODEL;
|
|
15
18
|
}
|
|
@@ -31,6 +34,19 @@ var ExperimentalOllamaAdapter = class {
|
|
|
31
34
|
});
|
|
32
35
|
return { threadId: request.threadId || randomUUID() };
|
|
33
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Ollama exposes an OpenAI-compatible API at `/v1`, so the model is built
|
|
39
|
+
* from the OpenAI provider pointed at the Ollama server. Without it the
|
|
40
|
+
* runtime rebuilds a bare "ollama/<model>" string and fails with
|
|
41
|
+
* `Unknown provider "ollama"`. Ollama ignores the key; a non-empty value is
|
|
42
|
+
* required only because the OpenAI client insists on one.
|
|
43
|
+
*/
|
|
44
|
+
getLanguageModel() {
|
|
45
|
+
return createOpenAI({
|
|
46
|
+
baseURL: `${this.baseUrl.replace(/\/$/, "")}/v1`,
|
|
47
|
+
apiKey: "ollama"
|
|
48
|
+
})(this.model);
|
|
49
|
+
}
|
|
34
50
|
};
|
|
35
51
|
|
|
36
52
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ollama-adapter.mjs","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — ExperimentalOllamaAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * CopilotKit Adapter for Ollama\n *\n * <RequestExample>\n * ```jsx CopilotRuntime Example\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new OllamaAdapter());\n * ```\n * </RequestExample>\n *\n * You can easily set the model to use by passing it to the constructor.\n * ```jsx\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(\n * req,\n * new OllamaAdapter({ model: \"llama3-70b-8192\" }),\n * );\n * ```\n */\nimport type { TextMessage } from \"../../../graphql/types/converted\";\nimport type {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../../service-adapter\";\nimport { randomId, randomUUID } from \"@copilotkit/shared\";\n\nconst DEFAULT_MODEL = \"llama3:latest\";\n\ninterface OllamaAdapterOptions {\n model?: string;\n}\n\nexport class ExperimentalOllamaAdapter implements CopilotServiceAdapter {\n public model: string;\n public provider = \"ollama\";\n public get name() {\n return \"OllamaAdapter\";\n }\n\n constructor(options?: OllamaAdapterOptions) {\n if (options?.model) {\n this.model = options.model;\n } else {\n this.model = DEFAULT_MODEL;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource } = request;\n // const messages = this.transformMessages(forwardedProps.messages);\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Ollama } = require(\"@langchain/community/llms/ollama\");\n const ollama = new Ollama({\n model: this.model,\n });\n const contents = (\n messages.filter((m) => m.isTextMessage()) as TextMessage[]\n ).map((m) => m.content);\n const _stream = await ollama.stream(contents); // [TODO] role info is dropped...\n\n eventSource.stream(async (eventStream$) => {\n const currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n for await (const chunkText of _stream) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: chunkText,\n });\n }\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n // we may need to add this later.. [nc]\n // let calls = (await result.response).functionCalls();\n\n eventStream$.complete();\n });\n return {\n threadId: request.threadId || randomUUID(),\n };\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ollama-adapter.mjs","names":[],"sources":["../../../../../src/v1-deprecated/service-adapters/experimental/ollama/ollama-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — ExperimentalOllamaAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * CopilotKit Adapter for Ollama\n *\n * <RequestExample>\n * ```jsx CopilotRuntime Example\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new OllamaAdapter());\n * ```\n * </RequestExample>\n *\n * You can easily set the model to use by passing it to the constructor.\n * ```jsx\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(\n * req,\n * new OllamaAdapter({ model: \"llama3-70b-8192\" }),\n * );\n * ```\n */\nimport type { TextMessage } from \"../../../graphql/types/converted\";\nimport type {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../../service-adapter\";\nimport { randomId, randomUUID } from \"@copilotkit/shared\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport type { LanguageModel } from \"ai\";\n\nconst DEFAULT_MODEL = \"llama3:latest\";\n\nconst DEFAULT_BASE_URL = \"http://127.0.0.1:11434\";\n\ninterface OllamaAdapterOptions {\n model?: string;\n /**\n * Base URL of the Ollama server. Defaults to `http://127.0.0.1:11434`.\n */\n baseUrl?: string;\n}\n\nexport class ExperimentalOllamaAdapter implements CopilotServiceAdapter {\n public model: string;\n public provider = \"ollama\";\n private baseUrl: string;\n public get name() {\n return \"OllamaAdapter\";\n }\n\n constructor(options?: OllamaAdapterOptions) {\n this.baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;\n if (options?.model) {\n this.model = options.model;\n } else {\n this.model = DEFAULT_MODEL;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource } = request;\n // const messages = this.transformMessages(forwardedProps.messages);\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Ollama } = require(\"@langchain/community/llms/ollama\");\n const ollama = new Ollama({\n model: this.model,\n });\n const contents = (\n messages.filter((m) => m.isTextMessage()) as TextMessage[]\n ).map((m) => m.content);\n const _stream = await ollama.stream(contents); // [TODO] role info is dropped...\n\n eventSource.stream(async (eventStream$) => {\n const currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n for await (const chunkText of _stream) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: chunkText,\n });\n }\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n // we may need to add this later.. [nc]\n // let calls = (await result.response).functionCalls();\n\n eventStream$.complete();\n });\n return {\n threadId: request.threadId || randomUUID(),\n };\n }\n\n /**\n * Ollama exposes an OpenAI-compatible API at `/v1`, so the model is built\n * from the OpenAI provider pointed at the Ollama server. Without it the\n * runtime rebuilds a bare \"ollama/<model>\" string and fails with\n * `Unknown provider \"ollama\"`. Ollama ignores the key; a non-empty value is\n * required only because the OpenAI client insists on one.\n */\n getLanguageModel(): LanguageModel {\n const provider = createOpenAI({\n baseURL: `${this.baseUrl.replace(/\\/$/, \"\")}/v1`,\n apiKey: \"ollama\",\n });\n return provider(this.model);\n }\n}\n"],"mappings":";;;;;;AAgDA,MAAM,gBAAgB;AAEtB,MAAM,mBAAmB;AAUzB,IAAa,4BAAb,MAAwE;CAItE,IAAW,OAAO;AAChB,SAAO;;CAGT,YAAY,SAAgC;kBAN1B;AAOhB,OAAK,UAAU,SAAS,WAAW;AACnC,MAAI,SAAS,MACX,MAAK,QAAQ,QAAQ;MAErB,MAAK,QAAQ;;CAIjB,MAAM,QACJ,SAC+C;EAC/C,MAAM,EAAE,UAAU,SAAS,gBAAgB;EAI3C,MAAM,EAAE,qBAAmB,mCAAmC;EAC9D,MAAM,SAAS,IAAI,OAAO,EACxB,OAAO,KAAK,OACb,CAAC;EACF,MAAM,WACJ,SAAS,QAAQ,MAAM,EAAE,eAAe,CAAC,CACzC,KAAK,MAAM,EAAE,QAAQ;EACvB,MAAM,UAAU,MAAM,OAAO,OAAO,SAAS;AAE7C,cAAY,OAAO,OAAO,iBAAiB;GACzC,MAAM,mBAAmB,UAAU;AACnC,gBAAa,qBAAqB,EAAE,WAAW,kBAAkB,CAAC;AAClE,cAAW,MAAM,aAAa,QAC5B,cAAa,uBAAuB;IAClC,WAAW;IACX,SAAS;IACV,CAAC;AAEJ,gBAAa,mBAAmB,EAAE,WAAW,kBAAkB,CAAC;AAIhE,gBAAa,UAAU;IACvB;AACF,SAAO,EACL,UAAU,QAAQ,YAAY,YAAY,EAC3C;;;;;;;;;CAUH,mBAAkC;AAKhC,SAJiB,aAAa;GAC5B,SAAS,GAAG,KAAK,QAAQ,QAAQ,OAAO,GAAG,CAAC;GAC5C,QAAQ;GACT,CAAC,CACc,KAAK,MAAM"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
|
+
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
2
3
|
const require_langchain_adapter = require('../langchain/langchain-adapter.cjs');
|
|
4
|
+
let _ai_sdk_google = require("@ai-sdk/google");
|
|
3
5
|
|
|
4
6
|
//#region src/v1-deprecated/service-adapters/google/google-genai-adapter.ts
|
|
5
7
|
/**
|
|
@@ -44,6 +46,21 @@ var GoogleGenerativeAIAdapter = class extends require_langchain_adapter.LangChai
|
|
|
44
46
|
} });
|
|
45
47
|
this.provider = "google";
|
|
46
48
|
this.model = DEFAULT_MODEL;
|
|
49
|
+
this._apiKey = options?.apiKey;
|
|
50
|
+
this._apiVersion = options?.apiVersion;
|
|
51
|
+
this.model = options?.model ?? DEFAULT_MODEL;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Hands `BuiltInAgent` a model built from this adapter's own credentials.
|
|
55
|
+
* Without it the runtime rebuilds a bare "google/<model>" string and the
|
|
56
|
+
* provider falls back to environment variables, dropping the `apiKey`
|
|
57
|
+
* passed to this constructor.
|
|
58
|
+
*/
|
|
59
|
+
getLanguageModel() {
|
|
60
|
+
return (0, _ai_sdk_google.createGoogleGenerativeAI)({
|
|
61
|
+
apiKey: this._apiKey ?? process.env.GOOGLE_API_KEY,
|
|
62
|
+
...this._apiVersion && { baseURL: `https://generativelanguage.googleapis.com/${this._apiVersion}` }
|
|
63
|
+
})(this.model);
|
|
47
64
|
}
|
|
48
65
|
};
|
|
49
66
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-genai-adapter.cjs","names":["LangChainAdapter"],"sources":["../../../../src/v1-deprecated/service-adapters/google/google-genai-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — GoogleGenerativeAIAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * Copilot Runtime adapter for Google Generative AI (e.g. Gemini).\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, GoogleGenerativeAIAdapter } from \"@copilotkit/runtime\";\n * const { GoogleGenerativeAI } = require(\"@google/generative-ai\");\n *\n * const genAI = new GoogleGenerativeAI(process.env[\"GOOGLE_API_KEY\"]);\n *\n * const copilotKit = new CopilotRuntime();\n *\n * return new GoogleGenerativeAIAdapter({ model: \"gemini-2.5-flash\", apiVersion: \"v1\" });\n * ```\n */\nimport { LangChainAdapter } from \"../langchain/langchain-adapter\";\n\ninterface GoogleGenerativeAIAdapterOptions {\n /**\n * A custom Google Generative AI model to use.\n */\n model?: string;\n /**\n * The API version to use (e.g. \"v1\" or \"v1beta\"). Defaults to \"v1\".\n */\n apiVersion?: \"v1\" | \"v1beta\";\n /**\n * The API key to use.\n */\n apiKey?: string;\n}\n\nconst DEFAULT_MODEL = \"gemini-2.5-flash\";\nconst DEFAULT_API_VERSION: GoogleGenerativeAIAdapterOptions[\"apiVersion\"] =\n \"v1\";\nlet hasWarnedDefaultGoogleModel = false;\n\nexport class GoogleGenerativeAIAdapter extends LangChainAdapter {\n public provider = \"google\";\n public model: string = DEFAULT_MODEL;\n\n constructor(options?: GoogleGenerativeAIAdapterOptions) {\n if (\n !hasWarnedDefaultGoogleModel &&\n !options?.model &&\n !options?.apiVersion\n ) {\n console.warn(\n `You are using the GoogleGenerativeAIAdapter without explicitly setting a model or apiVersion. ` +\n `CopilotKit will default to apiVersion=\"v1\" and model=\"${DEFAULT_MODEL}\". ` +\n `To silence this warning, pass model and apiVersion when constructing the adapter.`,\n );\n hasWarnedDefaultGoogleModel = true;\n }\n\n super({\n chainFn: async ({ messages, tools, threadId }) => {\n // Lazy require for optional peer dependencies\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { ChatGoogle } = require(\"@langchain/google-gauth\");\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { AIMessage } = require(\"@langchain/core/messages\");\n\n // Filter out empty assistant messages to prevent Gemini validation errors\n // Gemini specifically rejects conversations containing AIMessages with empty content\n const filteredMessages = messages.filter((message) => {\n // Keep all non-AI messages (HumanMessage, SystemMessage, ToolMessage, etc.)\n if (!(message instanceof AIMessage)) {\n return true;\n }\n\n // For AIMessages, only keep those with non-empty content\n // Also keep AIMessages with tool_calls even if content is empty\n const aiMsg = message as any;\n return (\n (aiMsg.content && String(aiMsg.content).trim().length > 0) ||\n (aiMsg.tool_calls && aiMsg.tool_calls.length > 0)\n );\n });\n\n this.model = options?.model ?? DEFAULT_MODEL;\n const model = new ChatGoogle({\n apiKey: options?.apiKey ?? process.env.GOOGLE_API_KEY,\n modelName: this.model,\n apiVersion: options?.apiVersion ?? DEFAULT_API_VERSION,\n }).bindTools(tools);\n\n return model.stream(filteredMessages, {\n metadata: { conversation_id: threadId },\n });\n },\n });\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"google-genai-adapter.cjs","names":["LangChainAdapter"],"sources":["../../../../src/v1-deprecated/service-adapters/google/google-genai-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — GoogleGenerativeAIAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * Copilot Runtime adapter for Google Generative AI (e.g. Gemini).\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, GoogleGenerativeAIAdapter } from \"@copilotkit/runtime\";\n * const { GoogleGenerativeAI } = require(\"@google/generative-ai\");\n *\n * const genAI = new GoogleGenerativeAI(process.env[\"GOOGLE_API_KEY\"]);\n *\n * const copilotKit = new CopilotRuntime();\n *\n * return new GoogleGenerativeAIAdapter({ model: \"gemini-2.5-flash\", apiVersion: \"v1\" });\n * ```\n */\nimport { LangChainAdapter } from \"../langchain/langchain-adapter\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport type { LanguageModel } from \"ai\";\n\ninterface GoogleGenerativeAIAdapterOptions {\n /**\n * A custom Google Generative AI model to use.\n */\n model?: string;\n /**\n * The API version to use (e.g. \"v1\" or \"v1beta\"). Defaults to \"v1\".\n */\n apiVersion?: \"v1\" | \"v1beta\";\n /**\n * The API key to use.\n */\n apiKey?: string;\n}\n\nconst DEFAULT_MODEL = \"gemini-2.5-flash\";\nconst DEFAULT_API_VERSION: GoogleGenerativeAIAdapterOptions[\"apiVersion\"] =\n \"v1\";\nlet hasWarnedDefaultGoogleModel = false;\n\nexport class GoogleGenerativeAIAdapter extends LangChainAdapter {\n public provider = \"google\";\n private _apiKey?: string;\n private _apiVersion?: GoogleGenerativeAIAdapterOptions[\"apiVersion\"];\n public model: string = DEFAULT_MODEL;\n\n constructor(options?: GoogleGenerativeAIAdapterOptions) {\n if (\n !hasWarnedDefaultGoogleModel &&\n !options?.model &&\n !options?.apiVersion\n ) {\n console.warn(\n `You are using the GoogleGenerativeAIAdapter without explicitly setting a model or apiVersion. ` +\n `CopilotKit will default to apiVersion=\"v1\" and model=\"${DEFAULT_MODEL}\". ` +\n `To silence this warning, pass model and apiVersion when constructing the adapter.`,\n );\n hasWarnedDefaultGoogleModel = true;\n }\n\n super({\n chainFn: async ({ messages, tools, threadId }) => {\n // Lazy require for optional peer dependencies\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { ChatGoogle } = require(\"@langchain/google-gauth\");\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { AIMessage } = require(\"@langchain/core/messages\");\n\n // Filter out empty assistant messages to prevent Gemini validation errors\n // Gemini specifically rejects conversations containing AIMessages with empty content\n const filteredMessages = messages.filter((message) => {\n // Keep all non-AI messages (HumanMessage, SystemMessage, ToolMessage, etc.)\n if (!(message instanceof AIMessage)) {\n return true;\n }\n\n // For AIMessages, only keep those with non-empty content\n // Also keep AIMessages with tool_calls even if content is empty\n const aiMsg = message as any;\n return (\n (aiMsg.content && String(aiMsg.content).trim().length > 0) ||\n (aiMsg.tool_calls && aiMsg.tool_calls.length > 0)\n );\n });\n\n this.model = options?.model ?? DEFAULT_MODEL;\n const model = new ChatGoogle({\n apiKey: options?.apiKey ?? process.env.GOOGLE_API_KEY,\n modelName: this.model,\n apiVersion: options?.apiVersion ?? DEFAULT_API_VERSION,\n }).bindTools(tools);\n\n return model.stream(filteredMessages, {\n metadata: { conversation_id: threadId },\n });\n },\n });\n\n // `this.model` is otherwise only assigned inside the chain closure, which\n // does not run until a request arrives — so `getLanguageModel()` would\n // report the default model instead of the configured one.\n this._apiKey = options?.apiKey;\n this._apiVersion = options?.apiVersion;\n this.model = options?.model ?? DEFAULT_MODEL;\n }\n\n /**\n * Hands `BuiltInAgent` a model built from this adapter's own credentials.\n * Without it the runtime rebuilds a bare \"google/<model>\" string and the\n * provider falls back to environment variables, dropping the `apiKey`\n * passed to this constructor.\n */\n getLanguageModel(): LanguageModel {\n // `createGoogleGenerativeAI` has no `apiVersion` option, so the version is\n // carried on the base URL. Only when the caller asked for one: the\n // provider's own default is v1beta, and that has been the live default\n // ever since this method started routing around `process()`. Forcing the\n // adapter's documented \"v1\" here would strand models v1 does not serve.\n const provider = createGoogleGenerativeAI({\n apiKey: this._apiKey ?? process.env.GOOGLE_API_KEY,\n ...(this._apiVersion && {\n baseURL: `https://generativelanguage.googleapis.com/${this._apiVersion}`,\n }),\n });\n return provider(this.model);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,gBAAgB;AACtB,MAAM,sBACJ;AACF,IAAI,8BAA8B;AAElC,IAAa,4BAAb,cAA+CA,2CAAiB;CAM9D,YAAY,SAA4C;AACtD,MACE,CAAC,+BACD,CAAC,SAAS,SACV,CAAC,SAAS,YACV;AACA,WAAQ,KACN,uJAC2D,cAAc,sFAE1E;AACD,iCAA8B;;AAGhC,QAAM,EACJ,SAAS,OAAO,EAAE,UAAU,OAAO,eAAe;GAGhD,MAAM,EAAE,eAAe,QAAQ,0BAA0B;GAEzD,MAAM,EAAE,cAAc,QAAQ,2BAA2B;GAIzD,MAAM,mBAAmB,SAAS,QAAQ,YAAY;AAEpD,QAAI,EAAE,mBAAmB,WACvB,QAAO;IAKT,MAAM,QAAQ;AACd,WACG,MAAM,WAAW,OAAO,MAAM,QAAQ,CAAC,MAAM,CAAC,SAAS,KACvD,MAAM,cAAc,MAAM,WAAW,SAAS;KAEjD;AAEF,QAAK,QAAQ,SAAS,SAAS;AAO/B,UANc,IAAI,WAAW;IAC3B,QAAQ,SAAS,UAAU,QAAQ,IAAI;IACvC,WAAW,KAAK;IAChB,YAAY,SAAS,cAAc;IACpC,CAAC,CAAC,UAAU,MAAM,CAEN,OAAO,kBAAkB,EACpC,UAAU,EAAE,iBAAiB,UAAU,EACxC,CAAC;KAEL,CAAC;kBAvDc;eAGK;AAyDrB,OAAK,UAAU,SAAS;AACxB,OAAK,cAAc,SAAS;AAC5B,OAAK,QAAQ,SAAS,SAAS;;;;;;;;CASjC,mBAAkC;AAYhC,sDAN0C;GACxC,QAAQ,KAAK,WAAW,QAAQ,IAAI;GACpC,GAAI,KAAK,eAAe,EACtB,SAAS,6CAA6C,KAAK,eAC5D;GACF,CAAC,CACc,KAAK,MAAM"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
|
|
2
2
|
import { LangChainAdapter } from "../langchain/langchain-adapter.cjs";
|
|
3
|
+
import { LanguageModel } from "ai";
|
|
3
4
|
|
|
4
5
|
//#region src/v1-deprecated/service-adapters/google/google-genai-adapter.d.ts
|
|
5
6
|
interface GoogleGenerativeAIAdapterOptions {
|
|
@@ -18,8 +19,17 @@ interface GoogleGenerativeAIAdapterOptions {
|
|
|
18
19
|
}
|
|
19
20
|
declare class GoogleGenerativeAIAdapter extends LangChainAdapter {
|
|
20
21
|
provider: string;
|
|
22
|
+
private _apiKey?;
|
|
23
|
+
private _apiVersion?;
|
|
21
24
|
model: string;
|
|
22
25
|
constructor(options?: GoogleGenerativeAIAdapterOptions);
|
|
26
|
+
/**
|
|
27
|
+
* Hands `BuiltInAgent` a model built from this adapter's own credentials.
|
|
28
|
+
* Without it the runtime rebuilds a bare "google/<model>" string and the
|
|
29
|
+
* provider falls back to environment variables, dropping the `apiKey`
|
|
30
|
+
* passed to this constructor.
|
|
31
|
+
*/
|
|
32
|
+
getLanguageModel(): LanguageModel;
|
|
23
33
|
}
|
|
24
34
|
//#endregion
|
|
25
35
|
export { GoogleGenerativeAIAdapter };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-genai-adapter.d.cts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/google/google-genai-adapter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"google-genai-adapter.d.cts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/google/google-genai-adapter.ts"],"mappings":";;;;;UAuCU,gCAAA;EAoBqD;;;EAhB7D,KAAA;EAkBQ;;;EAdR,UAAA;EAkBsB;;;EAdtB,MAAA;AAAA;AAAA,cAQW,yBAAA,SAAkC,gBAAA;EACtC,QAAA;EAAA,QACC,OAAA;EAAA,QACA,WAAA;EACD,KAAA;cAEK,OAAA,GAAU,gCAAA;;;;;;;EAkEtB,gBAAA,CAAA,GAAoB,aAAA;AAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
|
|
2
2
|
import { LangChainAdapter } from "../langchain/langchain-adapter.mjs";
|
|
3
|
+
import { LanguageModel } from "ai";
|
|
3
4
|
|
|
4
5
|
//#region src/v1-deprecated/service-adapters/google/google-genai-adapter.d.ts
|
|
5
6
|
interface GoogleGenerativeAIAdapterOptions {
|
|
@@ -18,8 +19,17 @@ interface GoogleGenerativeAIAdapterOptions {
|
|
|
18
19
|
}
|
|
19
20
|
declare class GoogleGenerativeAIAdapter extends LangChainAdapter {
|
|
20
21
|
provider: string;
|
|
22
|
+
private _apiKey?;
|
|
23
|
+
private _apiVersion?;
|
|
21
24
|
model: string;
|
|
22
25
|
constructor(options?: GoogleGenerativeAIAdapterOptions);
|
|
26
|
+
/**
|
|
27
|
+
* Hands `BuiltInAgent` a model built from this adapter's own credentials.
|
|
28
|
+
* Without it the runtime rebuilds a bare "google/<model>" string and the
|
|
29
|
+
* provider falls back to environment variables, dropping the `apiKey`
|
|
30
|
+
* passed to this constructor.
|
|
31
|
+
*/
|
|
32
|
+
getLanguageModel(): LanguageModel;
|
|
23
33
|
}
|
|
24
34
|
//#endregion
|
|
25
35
|
export { GoogleGenerativeAIAdapter };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-genai-adapter.d.mts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/google/google-genai-adapter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"google-genai-adapter.d.mts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/google/google-genai-adapter.ts"],"mappings":";;;;;UAuCU,gCAAA;EAoBqD;;;EAhB7D,KAAA;EAkBQ;;;EAdR,UAAA;EAkBsB;;;EAdtB,MAAA;AAAA;AAAA,cAQW,yBAAA,SAAkC,gBAAA;EACtC,QAAA;EAAA,QACC,OAAA;EAAA,QACA,WAAA;EACD,KAAA;cAEK,OAAA,GAAU,gCAAA;;;;;;;EAkEtB,gBAAA,CAAA,GAAoB,aAAA;AAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
import { __require } from "../../_virtual/_rolldown/runtime.mjs";
|
|
3
3
|
import { LangChainAdapter } from "../langchain/langchain-adapter.mjs";
|
|
4
|
+
import { createGoogleGenerativeAI } from "@ai-sdk/google";
|
|
4
5
|
|
|
5
6
|
//#region src/v1-deprecated/service-adapters/google/google-genai-adapter.ts
|
|
6
7
|
/**
|
|
@@ -45,6 +46,21 @@ var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
|
|
|
45
46
|
} });
|
|
46
47
|
this.provider = "google";
|
|
47
48
|
this.model = DEFAULT_MODEL;
|
|
49
|
+
this._apiKey = options?.apiKey;
|
|
50
|
+
this._apiVersion = options?.apiVersion;
|
|
51
|
+
this.model = options?.model ?? DEFAULT_MODEL;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Hands `BuiltInAgent` a model built from this adapter's own credentials.
|
|
55
|
+
* Without it the runtime rebuilds a bare "google/<model>" string and the
|
|
56
|
+
* provider falls back to environment variables, dropping the `apiKey`
|
|
57
|
+
* passed to this constructor.
|
|
58
|
+
*/
|
|
59
|
+
getLanguageModel() {
|
|
60
|
+
return createGoogleGenerativeAI({
|
|
61
|
+
apiKey: this._apiKey ?? process.env.GOOGLE_API_KEY,
|
|
62
|
+
...this._apiVersion && { baseURL: `https://generativelanguage.googleapis.com/${this._apiVersion}` }
|
|
63
|
+
})(this.model);
|
|
48
64
|
}
|
|
49
65
|
};
|
|
50
66
|
|