From 6da94c48646ca13d9a8a23cfeef3f8731c01b075 Mon Sep 17 00:00:00 2001 From: Lester Hairston Date: Sun, 29 Sep 2024 20:33:48 -0500 Subject: [PATCH] updated the provider for multichannel support --- core/context/providers/DiscordContext.ts | 147 --------------- .../providers/DiscordContextProvider.ts | 168 ++++++++++++++++++ core/context/providers/index.ts | 2 + .../src/main/resources/config_schema.json | 73 ++++++++ extensions/vscode/config_schema.json | 66 +++++++ extensions/vscode/continue_rc_schema.json | 83 +++++++++ 6 files changed, 392 insertions(+), 147 deletions(-) delete mode 100644 core/context/providers/DiscordContext.ts create mode 100644 core/context/providers/DiscordContextProvider.ts diff --git a/core/context/providers/DiscordContext.ts b/core/context/providers/DiscordContext.ts deleted file mode 100644 index 6a3615e09..000000000 --- a/core/context/providers/DiscordContext.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { AxiosError, AxiosInstance } from "axios"; -import { - ContextItem, - ContextProviderDescription, - ContextProviderExtras, -} from "../../index.js"; -import { BaseContextProvider } from "../index.js"; - -// Define helper interfaces for Discord responses -export interface DiscordChannel { - id: string; - name?: string; - icon?: string; - topic?: string; - guild_id?: string; // The ID of the guild (server) that the channel belongs to -} - -interface DiscordMessage { - id: string; - content: string; - author: { - id: string; - username: string; - }; - timestamp: string; -} - -class DiscordContextProvider extends BaseContextProvider { - // Description for the context provider - static description: ContextProviderDescription = { - title: "discord-messages", - displayTitle: "Discord Messages", - description: "Reference messages from a Discord channel", - type: "normal", - }; - - // Helper function to get the Axios instance with proper authorization - private async getApi(): Promise { - const { default: Axios } = await import("axios"); - const token = this.options.token; - if (!token) { - throw new Error("Discord Bot Token is required!"); - } - - return Axios.create({ - baseURL: "https://discord.com/api/v10", - headers: { - Authorization: `Bot ${token}`, - }, - }); - } - - // Reusable error handling method - private handleApiError(ex: unknown): string { - let content = "# Discord API Error\n\nFailed to retrieve data. "; - if (ex instanceof AxiosError) { - if (ex.response) { - const errorMessage = ex.response?.data - ? (ex.response.data.message ?? JSON.stringify(ex.response?.data)) - : `${ex.response.status}: ${ex.response.statusText}`; - content += `Discord API Error: ${errorMessage}`; - } else { - content += `Discord API Request Error ${ex.request}`; - } - } else { - content += `Unknown error: ${ex instanceof Error ? ex.message : JSON.stringify(ex)}`; - } - return content; - } - - // Fetch Discord channels - private async fetchChannels( - extras: ContextProviderExtras, - ): Promise> { - const api = await this.getApi(); - - try { - const response = await api.get>( - `/guilds/${this.options.guildId}/channels`, - ); - return response.data; - } catch (ex) { - throw new Error(this.handleApiError(ex)); - } - } - - // Fetch messages from a specific channel - private async fetchMessages( - channelId: string, - extras: ContextProviderExtras, - ): Promise> { - const api = await this.getApi(); - try { - const response = await api.get>( - `/channels/${channelId}/messages`, - { params: { limit: 10 } }, - ); - return response.data; - } catch (ex) { - throw new Error(this.handleApiError(ex)); - } - } - - // Main function to get context items (channels and messages) - async getContextItems( - query: string, - extras: ContextProviderExtras, - ): Promise { - const result = [] as Array; - - try { - // Fetch channels - const channels = await this.fetchChannels(extras); - - // Fetch messages for each channel in parallel - const channelMessagePromises = channels.map(async (channel) => { - const messages = await this.fetchMessages(channel.id, extras); - const parts = [ - `# Discord Channel: ${channel.name}`, - ...messages.map( - (message) => - `- ${message.author.username}: ${message.content} (at ${message.timestamp})`, - ), - ]; - - return { - name: `Messages from ${channel.name}`, - content: parts.join("\n"), - description: `Latest messages from the channel ${channel.name}`, - }; - }); - - const channelMessageItems = await Promise.all(channelMessagePromises); - result.push(...channelMessageItems); - } catch (ex) { - result.push({ - name: "Discord Error", - content: this.handleApiError(ex), - description: "Error fetching data from Discord.", - }); - } - - return result; - } -} - -export default DiscordContextProvider; diff --git a/core/context/providers/DiscordContextProvider.ts b/core/context/providers/DiscordContextProvider.ts new file mode 100644 index 000000000..f1282070a --- /dev/null +++ b/core/context/providers/DiscordContextProvider.ts @@ -0,0 +1,168 @@ +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../index.js"; +import { BaseContextProvider } from "../index.js"; +import axios, { AxiosInstance } from "axios"; + +// Define helper interfaces for Discord responses +export interface DiscordChannel { + id: string; + name?: string; // Optional field + icon?: string; + topic?: string; + type?: number; + guild_id?: string; // The ID of the guild (server) that the channel belongs to +} + +interface DiscordMessage { + id: string; + content: string; + author: { + id: string; + username: string; + }; + timestamp: string; +} + +class DiscordContextProvider extends BaseContextProvider { + // Description for the context provider + static description: ContextProviderDescription = { + title: "discord", + displayTitle: "Discord", + description: "Reference Discord messages from a channel", + type: "submenu", + }; + + private baseUrl = "https://discord.com/api/v10"; + + // Helper function to get the Axios instance with proper authorization + private getApi(): AxiosInstance { + const token = this.options.discordKey; + if (!token) { + throw new Error("Discord Bot Token is required!"); + } + + return axios.create({ + baseURL: this.baseUrl, + headers: { + Authorization: `Bot ${token}`, + "Content-Type": "application/json", + }, + }); + } + + // Fetch Discord messages from a specific channel using Axios + async fetchMessages(channelId: string): Promise> { + const api = this.getApi(); + + try { + const response = await api.get>( + `/channels/${channelId}/messages`, + ); + return response.data; + } catch (error) { + console.error("Error fetching messages:", error); + throw new Error(`Failed to fetch messages: ${error}`); + } + } + + // Fetch Discord channels using Axios + async fetchChannels(): Promise> { + // If channels (with id and optional name) are already provided, skip the API call + if (this.options.channels && this.options.channels.length > 0) { + // Return the channel details using the provided channel objects + return this.options.channels.map( + (channel: { id: string; name?: string }) => ({ + id: channel.id, + name: channel.name ?? `Channel ${channel.id}`, // Fall back to "Channel {id}" if name is not provided + }), + ); + } + + // If no channels are provided, fetch them from the API using guildId + const api = this.getApi(); + + try { + const response = await api.get>( + `/guilds/${this.options.guildId}/channels`, + ); + + // Filter for text channels (type 0 represents text channels) + const filteredChannels = response.data.filter( + (channel) => channel.type === 0, + ); + + return filteredChannels; + } catch (error) { + console.error("Error fetching channels:", error); + throw new Error(`Failed to fetch channels: ${error}`); + } + } + + // Main function to get context items (messages) + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + // Ensure channels are fetched if only guildId is provided + const channels = await this.fetchChannels(); + + // Determine the channel ID from the selected channel (either from query or the first in the options) + let channelId: string; + const selectedChannel = channels.find( + (channel) => channel.id === query || channel.name === query, + ); + + channelId = selectedChannel ? selectedChannel.id : channels[0].id; // Use the first channel if no match is found + + // Prepare parts for rendering the message content + const parts = ["# Discord Channel Messages", `Channel ID: ${channelId}`]; + const messages = await this.fetchMessages(channelId); + + // Check if there are messages + if (messages.length > 0) { + parts.push("## Messages"); + + messages.forEach((message) => { + // Log each message and the username to confirm access + parts.push( + `### ${message.author?.username ?? "Unknown User"} on ${ + message.timestamp + }\n\n${message.content}`, + ); + }); + } else { + parts.push("No messages found."); + } + + const content = parts.join("\n\n"); + + return [ + { + name: `Messages from Channel ${channelId}`, + content, + description: "Latest messages from the channel", + }, + ]; + } + + // Submenu to load the list of channels + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const channels = await this.fetchChannels(); + + // Map over the channels and return them as submenu items + return channels.map((channel) => ({ + id: channel.id, + title: channel.name || `Channel ${channel.id}`, // Fallback to ID if name is missing + description: channel.topic ?? "", + })); + } +} + +export default DiscordContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 9c2ab4303..110ed066b 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider"; import TerminalContextProvider from "./TerminalContextProvider"; import URLContextProvider from "./URLContextProvider"; import RepoMapContextProvider from "./RepoMapContextProvider"; +import DiscordContextProvider from "./DiscordContextProvider"; /** * Note: We are currently omitting the following providers due to bugs: @@ -53,6 +54,7 @@ export const Providers: (typeof BaseContextProvider)[] = [ URLContextProvider, ContinueProxyContextProvider, RepoMapContextProvider, + DiscordContextProvider, ]; export function contextProviderClassFromName( diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 5a20c6daf..333edeb25 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1570,6 +1570,72 @@ } }, "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": ["discord"] + } + } + }, + "then": { + "allOf": [ + { + "properties": { + "params": { + "properties": { + "discordKey": { + "type": "string", + "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." + }, + "guildId": { + "type": "string", + "description": "The ID of the guild (server) from which to fetch channels and messages." + }, + "channels": { + "type": "array", + "description": "A list of channel objects to search for messages", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the channel" + }, + "name": { + "type": "string", + "description": "The name of the channel" + } + }, + "required": ["id"] + } + } + }, + "required": ["discordKey"] + } + } + }, + { + "oneOf": [ + { + "properties": { + "params": { + "required": ["guildId"] + } + } + }, + { + "properties": { + "params": { + "required": ["channels"] + } + } + } + ] + } + ] + } + }, { "if": { "properties": { @@ -2115,6 +2181,13 @@ "minimum": 128, "exclusiveMaximum": 2147483647 }, + "maxBatchSize": { + "title": "Maximum Batch Size", + "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", + "type": "integer", + "minimum": 1, + "exclusiveMaximum": 2147483647 + }, "region": { "title": "Region", "description": "The region where the model is hosted", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 176bbd295..333edeb25 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1570,6 +1570,72 @@ } }, "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": ["discord"] + } + } + }, + "then": { + "allOf": [ + { + "properties": { + "params": { + "properties": { + "discordKey": { + "type": "string", + "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." + }, + "guildId": { + "type": "string", + "description": "The ID of the guild (server) from which to fetch channels and messages." + }, + "channels": { + "type": "array", + "description": "A list of channel objects to search for messages", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the channel" + }, + "name": { + "type": "string", + "description": "The name of the channel" + } + }, + "required": ["id"] + } + } + }, + "required": ["discordKey"] + } + } + }, + { + "oneOf": [ + { + "properties": { + "params": { + "required": ["guildId"] + } + } + }, + { + "properties": { + "params": { + "required": ["channels"] + } + } + } + ] + } + ] + } + }, { "if": { "properties": { diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 7a7e54764..f7bff8284 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1741,6 +1741,82 @@ } }, "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": [ + "discord" + ] + } + } + }, + "then": { + "allOf": [ + { + "properties": { + "params": { + "properties": { + "discordKey": { + "type": "string", + "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." + }, + "guildId": { + "type": "string", + "description": "The ID of the guild (server) from which to fetch channels and messages." + }, + "channels": { + "type": "array", + "description": "A list of channel objects to search for messages", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the channel" + }, + "name": { + "type": "string", + "description": "The name of the channel" + } + }, + "required": [ + "id" + ] + } + } + }, + "required": [ + "discordKey" + ] + } + } + }, + { + "oneOf": [ + { + "properties": { + "params": { + "required": [ + "guildId" + ] + } + } + }, + { + "properties": { + "params": { + "required": [ + "channels" + ] + } + } + } + ] + } + ] + } + }, { "if": { "properties": { @@ -2356,6 +2432,13 @@ "minimum": 128, "exclusiveMaximum": 2147483647 }, + "maxBatchSize": { + "title": "Maximum Batch Size", + "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", + "type": "integer", + "minimum": 1, + "exclusiveMaximum": 2147483647 + }, "region": { "title": "Region", "description": "The region where the model is hosted",