From a94c178126709c0109c631f99a012f4d1cbee746 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 31 Mar 2025 16:15:40 -0700 Subject: [PATCH 01/92] optional-context-name --- core/config/yaml/loadYaml.ts | 5 ++++- .../providers/ContinueProxyContextProvider.ts | 1 + core/context/providers/HttpContextProvider.ts | 14 ++++++++------ docs/docs/reference.md | 7 ++++++- packages/config-yaml/src/schemas/index.ts | 1 + 5 files changed, 20 insertions(+), 8 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f2fefbb39..55db94692 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -374,7 +374,10 @@ async function configYamlToContinueConfig( } return undefined; } - const instance: IContextProvider = new cls(context.params ?? {}); + const instance: IContextProvider = new cls({ + name: context.name, + ...context.params, + }); return instance; }) .filter((p) => !!p) ?? []) as IContextProvider[]; diff --git a/core/context/providers/ContinueProxyContextProvider.ts b/core/context/providers/ContinueProxyContextProvider.ts index 278a12678..77e47c9f3 100644 --- a/core/context/providers/ContinueProxyContextProvider.ts +++ b/core/context/providers/ContinueProxyContextProvider.ts @@ -24,6 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider { this.options.title || ContinueProxyContextProvider.description.title, displayTitle: this.options.displayTitle || + this.options.name || ContinueProxyContextProvider.description.displayTitle, description: this.options.description || diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 067035806..bcca31177 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -16,18 +16,20 @@ class HttpContextProvider extends BaseContextProvider { override get description(): ContextProviderDescription { return { - title: this.options.title || "http", - displayTitle: this.options.displayTitle || "HTTP", + title: this.options.title || HttpContextProvider.description.title, + displayTitle: + this.options.displayTitle || + this.options.name || + HttpContextProvider.description.displayTitle, description: - this.options.description || - "Retrieve a context item from a custom server", - type: "normal", + this.options.description || HttpContextProvider.description.description, + type: HttpContextProvider.description.type, renderInlineAs: this.options.renderInlineAs || HttpContextProvider.description.renderInlineAs, }; } - + async getContextItems( query: string, extras: ContextProviderExtras, diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 69f301366..217c460dd 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -220,7 +220,8 @@ More information about usage/params for each context provider can be found [here **Properties:** -- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). +- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`) +- `name`: Optional name for the provider - `params`: Optional parameters to configure the context provider's behavior. **Example:** @@ -234,6 +235,10 @@ context: nFinal: 10 - provider: docs - provider: diff + - provider: http + name: Context Server 1 + params: + url: "https://api.example.com/server1" - provider: folder - provider: terminal ``` diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1ca03b0b6..c33d02fc4 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -3,6 +3,7 @@ import { dataSchema } from "./data/index.js"; import { modelSchema, partialModelSchema } from "./models.js"; export const contextSchema = z.object({ + name: z.string().optional(), provider: z.string(), params: z.any().optional(), }); From c59c834790011d27558fb983d40171f70e522b59 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 31 Mar 2025 20:42:17 -0700 Subject: [PATCH 02/92] bump config-yaml --- core/package-lock.json | 8 ++++---- core/package.json | 2 +- gui/package-lock.json | 10 +++++----- gui/package.json | 2 +- packages/config-yaml/package.json | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index 50df2a6f3..3283e219e 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -2974,9 +2974,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.68", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.68.tgz", + "integrity": "sha512-rCegSGkv7Ws7LLnYVVGwXsoVZFpNFJnG6b1dVrj/u+2ZsFdA2leQUNtFGoeE/ixyfhUfBpMlgjEyPrmmy7gLjw==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index 205e3b778..b6193d221 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index 78eb2e61d..23fd77734 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -111,7 +111,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -554,9 +554,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.68", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.68.tgz", + "integrity": "sha512-rCegSGkv7Ws7LLnYVVGwXsoVZFpNFJnG6b1dVrj/u+2ZsFdA2leQUNtFGoeE/ixyfhUfBpMlgjEyPrmmy7gLjw==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/gui/package.json b/gui/package.json index 3210a55f5..4df8cbec8 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index d7d96c4f0..e3d62aeef 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.67", + "version": "1.0.68", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From 68d4c261966d3e87b5f3d2f1e0e5c97c973fd44b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 11 Apr 2025 17:08:34 -0700 Subject: [PATCH 03/92] clear-sessions --- core/core.ts | 8 +- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 1 + core/util/history.ts | 10 +- .../constants/MessageTypes.kt | 1 + .../components/History/HistoryTableRow.tsx | 141 +++++++------- gui/src/components/History/index.tsx | 174 ++++++++++++------ gui/src/pages/history/index.tsx | 5 +- 8 files changed, 201 insertions(+), 140 deletions(-) diff --git a/core/core.ts b/core/core.ts index 68aa605ac..71521fa60 100644 --- a/core/core.ts +++ b/core/core.ts @@ -271,7 +271,6 @@ export class Core { } }); - // Special on("abort", (msg) => { this.abortedMessageIds.add(msg.messageId); }); @@ -300,12 +299,14 @@ export class Core { historyManager.save(msg.data); }); - // Dev data + on("history/clear", (msg) => { + historyManager.clearAll(); + }); + on("devdata/log", async (msg) => { void DataLogger.getInstance().logDevData(msg.data); }); - // Edit config on("config/addModel", (msg) => { const model = msg.data.model; addModel(model, msg.data.role); @@ -386,7 +387,6 @@ export class Core { if (!config) { return []; } - const items = await config.contextProviders ?.find((provider) => provider.description.title === msg.data.title) ?.loadSubmenuItems({ diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 7f29c2e25..6581e1607 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -49,6 +49,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, Session]; "history/save": [Session, void]; + "history/clear": [undefined, void]; "devdata/log": [DevDataLogEvent, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1d854f948..ffdbb52fe 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -14,6 +14,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "history/delete", "history/load", "history/save", + "history/clear", "devdata/log", "config/addModel", "config/newPromptFile", diff --git a/core/util/history.ts b/core/util/history.ts index 622c2c9ce..ab332a11b 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -4,7 +4,11 @@ import { Session, SessionMetadata } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { NEW_SESSION_TITLE } from "./constants.js"; -import { getSessionFilePath, getSessionsListPath } from "./paths.js"; +import { + getSessionFilePath, + getSessionsFolderPath, + getSessionsListPath, +} from "./paths.js"; function safeParseArray( value: string, errorMessage: string = "Error parsing array", @@ -67,6 +71,10 @@ class HistoryManager { ); } + clearAll() { + fs.rmSync(getSessionsFolderPath(), { recursive: true, force: true }); + } + load(sessionId: string): Session { try { const sessionFile = getSessionFilePath(sessionId); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 100ee2aad..7f0557c57 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -79,6 +79,7 @@ class MessageTypes { "history/delete", "history/load", "history/save", + "history/clear", "devdata/log", "config/addModel", "config/newPromptFile", diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 11a5a36df..8b7f3ba38 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,5 +1,6 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; +import { getUriPathBasename } from "core/util/uri"; import React, { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; @@ -12,10 +13,6 @@ import { updateSession, } from "../../redux/thunks/session"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { - getLastNUriRelativePathParts, - getUriPathBasename, -} from "core/util/uri"; export function HistoryTableRow({ sessionMetadata, @@ -65,52 +62,48 @@ export function HistoryTableRow({ }; return ( - - setHovered(true)} - onMouseLeave={() => setHovered(false)} - > -
{ - if (sessionMetadata.sessionId !== currentSessionId) { - await dispatch( - loadSession({ - sessionId: sessionMetadata.sessionId, - saveCurrentSession: true, - }), - ); - } - navigate("/"); - }} - > -
- {editing ? ( -
- titleInput && titleInput.focus()} - value={sessionTitleEditValue} - onChange={(e) => setSessionTitleEditValue(e.target.value)} - onKeyUp={(e) => handleKeyUp(e)} - onBlur={() => setEditing(false)} - /> -
- ) : ( - - {sessionMetadata.title} - - )} + setHovered(true)} + onMouseLeave={() => setHovered(false)} + data-testid={`history-row-${index}`} + className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3" + onClick={async () => { + if (sessionMetadata.sessionId !== currentSessionId) { + await dispatch( + loadSession({ + sessionId: sessionMetadata.sessionId, + saveCurrentSession: true, + }), + ); + } + navigate("/"); + }} + > +
+ {editing ? ( +
+ titleInput && titleInput.focus()} + value={sessionTitleEditValue} + onChange={(e) => setSessionTitleEditValue(e.target.value)} + onKeyUp={(e) => handleKeyUp(e)} + onBlur={() => setEditing(false)} + /> +
+ ) : ( + + {sessionMetadata.title} + + )} -
- - {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} - - {/* Uncomment to show the date */} - {/* +
+ + {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} + + {/* Uncomment to show the date */} + {/* {date.toLocaleString("en-US", { year: "2-digit", month: "2-digit", @@ -120,33 +113,31 @@ export function HistoryTableRow({ hour12: true, })} */} -
-
- - {hovered && !editing && ( -
- { - e.stopPropagation(); - setEditing(true); - }} - > - - - { - e.stopPropagation(); - await dispatch(deleteSession(sessionMetadata.sessionId)); - }} - > - - -
- )}
- +
+ + {hovered && !editing && ( +
+ { + e.stopPropagation(); + setEditing(true); + }} + > + + + { + e.stopPropagation(); + await dispatch(deleteSession(sessionMetadata.sessionId)); + }} + > + + +
+ )} ); } diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index e8d6ef2fd..2ceeea09b 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -1,12 +1,29 @@ import { SessionMetadata } from "core"; import MiniSearch from "minisearch"; -import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; -import Shortcut from '../gui/Shortcut'; +import React, { + Fragment, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import Shortcut from "../gui/Shortcut"; -import { getFontSize, getMetaKeyLabel } from "../../util"; -import { HistoryTableRow } from "./HistoryTableRow"; import { XMarkIcon } from "@heroicons/react/24/solid"; -import { useAppSelector } from "../../redux/hooks"; +import { useNavigate } from "react-router-dom"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + newSession, + setAllSessionMetadata, +} from "../../redux/slices/sessionSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { refreshSessionMetadata } from "../../redux/thunks/session"; +import { getFontSize, getPlatform } from "../../util"; +import { ROUTES } from "../../util/navigation"; +import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import { HistoryTableRow } from "./HistoryTableRow"; const parseDate = (date: string): Date => { let dateObj = new Date(date); @@ -20,7 +37,10 @@ const HEADER_CLASS = "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6"; export function History() { + const dispatch = useAppDispatch(); + const navigate = useNavigate(); const searchInputRef = React.useRef(null); + const ideMessenger = useContext(IdeMessengerContext); const [searchTerm, setSearchTerm] = useState(""); @@ -50,6 +70,8 @@ export function History() { } }, [allSessionMetadata]); + const platform = useMemo(() => getPlatform(), []); + const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => { const sessionIds = minisearch .search(searchTerm, { @@ -73,11 +95,38 @@ export function History() { const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); const earlier = new Date(0); + const showClearSessionsDialog = () => { + dispatch( + setDialogMessage( + { + // optimistic update + dispatch(setAllSessionMetadata([])); + + // actual update + refresh + await ideMessenger.request("history/clear", undefined); + dispatch(refreshSessionMetadata({})); + + // start a new session + dispatch(newSession()); + navigate(ROUTES.HOME); + }} + />, + ), + ); + dispatch(setShowDialog(true)); + }; + return ( -
-
+
+
)}
+
+ {filteredAndSortedSessions.length === 0 && ( +
+ No past sessions found. To start a new session, either click the "+" + button or use the keyboard shortcut: meta L +
+ )} - {filteredAndSortedSessions.length === 0 && ( -
- No past sessions found. To start a new session, either click the "+" - button or use the keyboard shortcut: meta L -
- - )} - - - - {filteredAndSortedSessions.map((session, index) => { - const prevDate = - index > 0 - ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) - : earlier; - const date = parseDate(session.dateCreated); - return ( - - {index === 0 && date > yesterday && ( - - - - )} - {date < yesterday && - date > lastWeek && - prevDate > yesterday && ( +
Today
+ + {filteredAndSortedSessions.map((session, index) => { + const prevDate = + index > 0 + ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) + : earlier; + const date = parseDate(session.dateCreated); + return ( + + {index === 0 && date > yesterday && ( - + )} - {date < lastWeek && date > lastMonth && prevDate > lastWeek && ( - - - - )} - {date < lastMonth && prevDate > lastMonth && ( - - - - )} + {date < yesterday && + date > lastWeek && + prevDate > yesterday && ( +
+
+ + )} + {date < lastWeek && + date > lastMonth && + prevDate > lastWeek && ( +
+
+ + )} + {date < lastMonth && prevDate > lastMonth && ( +
+
+ + )} - - - ); - })} - -
This WeekToday
This Month
Older
This WeekThis MonthOlder
-
- - All session data is saved in ~/.continue/sessions - + + + ); + })} + + +
+
+ {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} + + Clear session history + +
); } diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx index f59da5509..a8be3d92f 100644 --- a/gui/src/pages/history/index.tsx +++ b/gui/src/pages/history/index.tsx @@ -8,7 +8,10 @@ export default function HistoryPage() { const navigate = useNavigate(); return ( -
+
navigate("/")} From 785e174086ba6b6913914c94a4a541fed1edda96 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 12 Apr 2025 21:34:20 -0700 Subject: [PATCH 04/92] fix history test --- gui/src/components/History/index.tsx | 5 ++++- gui/src/pages/history/history.test.tsx | 4 +--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index 2ceeea09b..e51dc45eb 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -200,7 +200,10 @@ export function History() {
- {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} + {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} { describe("history Page test", () => { it("History text is existed after render", () => { renderWithProviders(); - expect( - screen.getByText("All session data is saved in ~/.continue/sessions"), - ).toBeInTheDocument(); + expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); }); From 8eb1ccaf509f04852a6c8e142dc6585cfc47f7db Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 13:39:05 -0700 Subject: [PATCH 05/92] gemini json conversions --- core/llm/llms/Gemini.ts | 80 +-------- core/llm/llms/gemini-types.ts | 164 ++++++++++++++++-- packages/openai-adapters/src/apis/Gemini.ts | 75 ++------ .../openai-adapters/src/util/gemini-types.ts | 164 ++++++++++++++++-- 4 files changed, 323 insertions(+), 160 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1c5d24aee..1f810723a 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -12,12 +12,13 @@ import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; import { + convertContinueToolToGeminiFunction, GeminiChatContentPart, GeminiChatRequestBody, GeminiChatResponse, GeminiGenerationConfig, GeminiToolFunctionDeclaration, -} from "./gemini-types.js"; +} from "./gemini-types"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -276,77 +277,12 @@ class Gemini extends BaseLLM { // Same difference const functions: GeminiToolFunctionDeclaration[] = []; options.tools.forEach((tool) => { - if (tool.function.description && tool.function.name) { - const fn: GeminiToolFunctionDeclaration = { - description: tool.function.description, - name: tool.function.name, - }; - - if ( - tool.function.parameters && - "type" in tool.function.parameters - // && typeof tool.function.parameters.type === "string" - ) { - // const paramType = "TYPE_UNSPECIFIED" - // | "STRING" - // | "NUMBER" - // | "INTEGER" - // | "BOOLEAN" - // | "ARRAY" - // | "OBJECT" - - if (tool.function.parameters.type === "object") { - // Gemini can't take an empty object - // So if empty object param is present just don't add parameters - if ( - JSON.stringify(tool.function.parameters.properties) === "{}" - ) { - functions.push(fn); - return; - } - } - // Helper function to recursively clean JSON Schema objects - const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== "object") return schema; - - if (Array.isArray(schema)) { - return schema.map(cleanJsonSchema); - } - - const { - $schema, - additionalProperties, - default: defaultValue, - ...rest - } = schema; - - // Recursively clean nested properties - if (rest.properties) { - rest.properties = Object.entries(rest.properties).reduce( - (acc, [key, value]) => ({ - ...acc, - [key]: cleanJsonSchema(value), - }), - {}, - ); - } - - // Clean items in arrays - if (rest.items) { - rest.items = cleanJsonSchema(rest.items); - } - - return rest; - }; - - // Clean the parameters and convert type to uppercase - const cleanedParams = cleanJsonSchema(tool.function.parameters); - fn.parameters = { - ...cleanedParams, - type: tool.function.parameters.type.toUpperCase(), - }; - } - functions.push(fn); + try { + functions.push(convertContinueToolToGeminiFunction(tool)); + } catch (e) { + console.warn( + `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`, + ); } }); if (functions.length) { diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts index b9fb52c1d..d37fad121 100644 --- a/core/llm/llms/gemini-types.ts +++ b/core/llm/llms/gemini-types.ts @@ -1,4 +1,5 @@ import { JSONSchema7Object } from "json-schema"; +import { Tool } from "../.."; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -16,24 +17,162 @@ export interface GeminiGenerationConfig { // responseSchema?: object; // https://ai.google.dev/api/caching#Schema } -export interface GeminiFunctionSchema { - type: - | "TYPE_UNSPECIFIED" - | "STRING" - | "NUMBER" - | "INTEGER" - | "BOOLEAN" - | "ARRAY" - | "OBJECT"; +export type GeminiObjectSchemaType = + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + +export interface GeminiObjectSchema { + type: GeminiObjectSchemaType; format?: string; + title?: string; description?: string; nullable?: boolean; enum?: string[]; maxItems?: string; minItems?: string; - properties?: Record; + properties?: Record; required?: string[]; - items?: GeminiFunctionSchema; + anyOf?: GeminiObjectSchema[]; + propertyOrdering?: string[]; + items?: GeminiObjectSchema; + minimum?: number; + maximum?: number; +} + +const jsonSchemaTypeToGeminiType = ( + jsonSchemaType: string, +): GeminiObjectSchemaType => { + switch (jsonSchemaType.toLowerCase()) { + case "string": + return "STRING"; + case "object": + return "OBJECT"; + case "number": + return "NUMBER"; + case "integer": + return "INTEGER"; + case "array": + return "ARRAY"; + case "boolean": + return "BOOLEAN"; + default: + return "TYPE_UNSPECIFIED"; + } +}; + +function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { + const jsonSchemaType = jsonSchema["type"]; + if (!jsonSchemaType || typeof jsonSchema.type !== "string") { + throw new Error( + `Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`, + ); + } + const geminiSchema: GeminiObjectSchema = { + type: jsonSchemaTypeToGeminiType(jsonSchemaType), + }; + + // if (jsonSchema.format) geminiSchema.format = jsonSchema.format; + if (jsonSchema.title) geminiSchema.title = jsonSchema.title; + if (jsonSchema.description) geminiSchema.description = jsonSchema.description; + + // Handle nullable + if (jsonSchemaType === "null" || jsonSchema.nullable) { + geminiSchema.nullable = true; + } + + // Handle enum values + if (Array.isArray(jsonSchema.enum)) { + geminiSchema.enum = jsonSchema.enum.map(String); + } + + // Handle array constraints + if (jsonSchemaType === "array") { + if (typeof jsonSchema.maxItems !== "undefined") { + geminiSchema.maxItems = String(jsonSchema.maxItems); + } + if (typeof jsonSchema.minItems !== "undefined") { + geminiSchema.minItems = String(jsonSchema.minItems); + } + // Handle array items + if (jsonSchema.items) { + geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items); + } + } + + // Handle numeric constraints + if (typeof jsonSchema.minimum !== "undefined") { + geminiSchema.minimum = Number(jsonSchema.minimum); + } + if (typeof jsonSchema.maximum !== "undefined") { + geminiSchema.maximum = Number(jsonSchema.maximum); + } + + // Handle properties for objects + if (jsonSchema.properties) { + geminiSchema.properties = {}; + for (const [key, value] of Object.entries(jsonSchema.properties)) { + geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value); + } + } + + // Handle required properties + if (Array.isArray(jsonSchema.required)) { + geminiSchema.required = jsonSchema.required; + } + + // Handle anyOf + if (Array.isArray(jsonSchema.anyOf)) { + geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema); + } + + // TODO/UNSUPPORTED: + // format + // property ordering: + // if (Array.isArray(jsonSchema.propertyOrdering)) { + // geminiSchema.propertyOrdering = jsonSchema.propertyOrdering; + // } + + return geminiSchema; +} + +// https://ai.google.dev/api/caching#FunctionDeclaration +// Note "reponse" field (schema showing function output structure) is not supported at the moment +export function convertContinueToolToGeminiFunction( + tool: Tool, +): GeminiToolFunctionDeclaration { + if (!tool.function.name) { + throw new Error("Function name required"); + } + const description = tool.function.description ?? ""; + const name = tool.function.name; + + const fn: GeminiToolFunctionDeclaration = { + description, + name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters && + typeof tool.function.parameters.type === "string" + ) { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if (tool.function.parameters.type === "object") { + if (JSON.stringify(tool.function.parameters.properties) === "{}") { + return fn; + } + } + + fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters); + } + + return fn; } export type GeminiChatContentPart = @@ -88,7 +227,8 @@ export interface GeminiChatContent { export interface GeminiToolFunctionDeclaration { name: string; description: string; - parameters?: GeminiFunctionSchema; + parameters?: GeminiObjectSchema; + response?: GeminiObjectSchema; } export interface GeminiTool { functionDeclarations?: GeminiToolFunctionDeclaration[]; diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index c17527674..336dee644 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -21,7 +21,10 @@ import { customFetch, embedding, } from "../util.js"; -import { GeminiToolFunctionDeclaration } from "../util/gemini-types.js"; +import { + convertOpenAIToolToGeminiFunction, + GeminiToolFunctionDeclaration, +} from "../util/gemini-types.js"; import { BaseLlmApi, CreateRerankResponse, @@ -164,71 +167,15 @@ export class GeminiApi implements BaseLlmApi { // Same difference const functions: GeminiToolFunctionDeclaration[] = []; oaiBody.tools.forEach((tool) => { - if (tool.function.description && tool.function.name) { - const fn: GeminiToolFunctionDeclaration = { - description: tool.function.description, - name: tool.function.name, - }; - - if ( - tool.function.parameters && - "type" in tool.function.parameters - // && typeof tool.function.parameters.type === "string" - ) { - if (tool.function.parameters.type === "object") { - // Gemini can't take an empty object - // So if empty object param is present just don't add parameters - if ( - JSON.stringify(tool.function.parameters.properties) === "{}" - ) { - functions.push(fn); - return; - } - } - // Helper function to recursively clean JSON Schema objects - const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== "object") return schema; - - if (Array.isArray(schema)) { - return schema.map(cleanJsonSchema); - } - - const { - $schema, - additionalProperties, - default: defaultValue, - ...rest - } = schema; - - // Recursively clean nested properties - if (rest.properties) { - rest.properties = Object.entries(rest.properties).reduce( - (acc, [key, value]) => ({ - ...acc, - [key]: cleanJsonSchema(value), - }), - {}, - ); - } - - // Clean items in arrays - if (rest.items) { - rest.items = cleanJsonSchema(rest.items); - } - - return rest; - }; - - // Clean the parameters and convert type to uppercase - const cleanedParams = cleanJsonSchema(tool.function.parameters); - fn.parameters = { - ...cleanedParams, - type: (tool.function.parameters as any)?.type?.toUpperCase(), - }; - } - functions.push(fn); + try { + functions.push(convertOpenAIToolToGeminiFunction(tool)); + } catch (e) { + console.warn( + `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`, + ); } }); + if (functions.length) { finalBody.tools = [ { diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index b9fb52c1d..4dbae03a7 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -1,4 +1,5 @@ import { JSONSchema7Object } from "json-schema"; +import { Tool } from "../../../../core/index.js"; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -16,24 +17,162 @@ export interface GeminiGenerationConfig { // responseSchema?: object; // https://ai.google.dev/api/caching#Schema } -export interface GeminiFunctionSchema { - type: - | "TYPE_UNSPECIFIED" - | "STRING" - | "NUMBER" - | "INTEGER" - | "BOOLEAN" - | "ARRAY" - | "OBJECT"; +export type GeminiObjectSchemaType = + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + +export interface GeminiObjectSchema { + type: GeminiObjectSchemaType; format?: string; + title?: string; description?: string; nullable?: boolean; enum?: string[]; maxItems?: string; minItems?: string; - properties?: Record; + properties?: Record; required?: string[]; - items?: GeminiFunctionSchema; + anyOf?: GeminiObjectSchema[]; + propertyOrdering?: string[]; + items?: GeminiObjectSchema; + minimum?: number; + maximum?: number; +} + +const jsonSchemaTypeToGeminiType = ( + jsonSchemaType: string, +): GeminiObjectSchemaType => { + switch (jsonSchemaType.toLowerCase()) { + case "string": + return "STRING"; + case "object": + return "OBJECT"; + case "number": + return "NUMBER"; + case "integer": + return "INTEGER"; + case "array": + return "ARRAY"; + case "boolean": + return "BOOLEAN"; + default: + return "TYPE_UNSPECIFIED"; + } +}; + +function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { + const jsonSchemaType = jsonSchema["type"]; + if (!jsonSchemaType || typeof jsonSchema.type !== "string") { + throw new Error( + `Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`, + ); + } + const geminiSchema: GeminiObjectSchema = { + type: jsonSchemaTypeToGeminiType(jsonSchemaType), + }; + + // if (jsonSchema.format) geminiSchema.format = jsonSchema.format; + if (jsonSchema.title) geminiSchema.title = jsonSchema.title; + if (jsonSchema.description) geminiSchema.description = jsonSchema.description; + + // Handle nullable + if (jsonSchemaType === "null" || jsonSchema.nullable) { + geminiSchema.nullable = true; + } + + // Handle enum values + if (Array.isArray(jsonSchema.enum)) { + geminiSchema.enum = jsonSchema.enum.map(String); + } + + // Handle array constraints + if (jsonSchemaType === "array") { + if (typeof jsonSchema.maxItems !== "undefined") { + geminiSchema.maxItems = String(jsonSchema.maxItems); + } + if (typeof jsonSchema.minItems !== "undefined") { + geminiSchema.minItems = String(jsonSchema.minItems); + } + // Handle array items + if (jsonSchema.items) { + geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items); + } + } + + // Handle numeric constraints + if (typeof jsonSchema.minimum !== "undefined") { + geminiSchema.minimum = Number(jsonSchema.minimum); + } + if (typeof jsonSchema.maximum !== "undefined") { + geminiSchema.maximum = Number(jsonSchema.maximum); + } + + // Handle properties for objects + if (jsonSchema.properties) { + geminiSchema.properties = {}; + for (const [key, value] of Object.entries(jsonSchema.properties)) { + geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value); + } + } + + // Handle required properties + if (Array.isArray(jsonSchema.required)) { + geminiSchema.required = jsonSchema.required; + } + + // Handle anyOf + if (Array.isArray(jsonSchema.anyOf)) { + geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema); + } + + // TODO/UNSUPPORTED: + // format + // property ordering: + // if (Array.isArray(jsonSchema.propertyOrdering)) { + // geminiSchema.propertyOrdering = jsonSchema.propertyOrdering; + // } + + return geminiSchema; +} + +// https://ai.google.dev/api/caching#FunctionDeclaration +// Note "reponse" field (schema showing function output structure) is not supported at the moment +export function convertContinueToolToGeminiFunction( + tool: Tool, +): GeminiToolFunctionDeclaration { + if (!tool.function.name) { + throw new Error("Function name required"); + } + const description = tool.function.description ?? ""; + const name = tool.function.name; + + const fn: GeminiToolFunctionDeclaration = { + description, + name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters && + typeof tool.function.parameters.type === "string" + ) { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if (tool.function.parameters.type === "object") { + if (JSON.stringify(tool.function.parameters.properties) === "{}") { + return fn; + } + } + + fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters); + } + + return fn; } export type GeminiChatContentPart = @@ -88,7 +227,8 @@ export interface GeminiChatContent { export interface GeminiToolFunctionDeclaration { name: string; description: string; - parameters?: GeminiFunctionSchema; + parameters?: GeminiObjectSchema; + response?: GeminiObjectSchema; } export interface GeminiTool { functionDeclarations?: GeminiToolFunctionDeclaration[]; From 30f009b8d0509dcedd076387605ff3cecc629aa3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 13:40:24 -0700 Subject: [PATCH 06/92] types --- packages/openai-adapters/src/util/gemini-types.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index 4dbae03a7..d1921302e 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -1,5 +1,5 @@ import { JSONSchema7Object } from "json-schema"; -import { Tool } from "../../../../core/index.js"; +import { ChatCompletionTool } from "openai/resources/index.mjs"; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -142,8 +142,8 @@ function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { // https://ai.google.dev/api/caching#FunctionDeclaration // Note "reponse" field (schema showing function output structure) is not supported at the moment -export function convertContinueToolToGeminiFunction( - tool: Tool, +export function convertOpenAIToolToGeminiFunction( + tool: ChatCompletionTool, ): GeminiToolFunctionDeclaration { if (!tool.function.name) { throw new Error("Function name required"); From ff177721cb5504e94b1eefa5438872d8e2c19dbf Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 14:45:49 -0700 Subject: [PATCH 07/92] gemini tool ids --- core/llm/llms/Gemini.ts | 30 ++--- core/llm/llms/gemini-types.ts | 103 ++++++++++-------- packages/openai-adapters/package-lock.json | 13 +++ packages/openai-adapters/package.json | 1 + packages/openai-adapters/src/apis/Gemini.ts | 41 +++++-- .../openai-adapters/src/util/gemini-types.ts | 103 ++++++++++-------- 6 files changed, 181 insertions(+), 110 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1f810723a..254afd6fa 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,5 +1,5 @@ +import { v4 as uuidv4 } from "uuid"; import { - AssistantChatMessage, ChatMessage, CompletionOptions, LLMOptions, @@ -7,7 +7,6 @@ import { TextMessagePart, ToolCallDelta, } from "../../index.js"; -import { findLast } from "../../util/findLast.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -205,20 +204,24 @@ class Gemini extends BaseLLM { options: CompletionOptions, isV1API: boolean, ): GeminiChatRequestBody { + const toolCallIdToNameMap = new Map(); + messages.forEach((msg) => { + if (msg.role === "assistant" && msg.toolCalls) { + msg.toolCalls.forEach((call) => { + if (call.id && call.function?.name) { + toolCallIdToNameMap.set(call.id, call.function.name); + } + }); + } + }); + const body: GeminiChatRequestBody = { contents: messages .filter((msg) => !(msg.role === "system" && isV1API)) .map((msg) => { if (msg.role === "tool") { - let fn_name = ""; - const lastToolCallMessage = findLast( - messages, - (msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name, - ) as AssistantChatMessage; - if (lastToolCallMessage) { - fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!; - } - if (!fn_name) { + let functionName = toolCallIdToNameMap.get(msg.toolCallId); + if (!functionName) { console.warn( "Sending tool call response for unidentified tool call", ); @@ -228,7 +231,8 @@ class Gemini extends BaseLLM { parts: [ { functionResponse: { - name: fn_name || "unknown", + id: msg.toolCallId, + name: functionName || "unknown", response: { output: msg.content, // "output" key is opinionated - not all functions will output objects }, @@ -358,7 +362,7 @@ class Gemini extends BaseLLM { type: "toolCall", data: { type: "function", - id: "", // Not supported by gemini + id: part.functionCall.id ?? uuidv4(), function: { name: part.functionCall.name, arguments: diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts index d37fad121..355d1c942 100644 --- a/core/llm/llms/gemini-types.ts +++ b/core/llm/llms/gemini-types.ts @@ -175,50 +175,67 @@ export function convertContinueToolToGeminiFunction( return fn; } +export type GeminiTextContentPart = { + text: string; +}; + +export type GeminiInlineDataContentPart = { + inlineData: { + mimeType: string; + data: string; + }; +}; + +export type GeminiFunctionCallContentPart = { + functionCall: { + id?: string; + name: string; + args: JSONSchema7Object; + }; +}; + +export type GeminiFunctionResponseContentPart = { + functionResponse: { + id?: string; + name: string; + response: JSONSchema7Object; + }; +}; + +export type GeminiFileDataContentPart = { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; +}; + +export type GeminiExecutableCodeContentPart = { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; +}; + +export type GeminiCodeExecutionResultContentPart = { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; +}; + export type GeminiChatContentPart = - | { - text: string; - } - | { - inlineData: { - mimeType: string; - data: string; - }; - } - | { - functionCall: { - name: string; - args: JSONSchema7Object; - }; - } - | { - functionResponse: { - name: string; - response: JSONSchema7Object; - }; - } - | { - fileData: { - fileUri: string; - mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata - }; - } - | { - executableCode: { - language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; - code: string; - }; - } - | { - codeExecutionResult: { - outcome: - | "OUTCOME_UNSPECIFIED" - | "OUTCOME_OK" - | "OUTCOME_FAILED" - | "OUTCOME_DEADLINE_EXCEEDED"; - output: string; - }; - }; + | GeminiTextContentPart + | GeminiInlineDataContentPart + | GeminiFunctionCallContentPart + | GeminiFunctionResponseContentPart + | GeminiFileDataContentPart + | GeminiExecutableCodeContentPart + | GeminiCodeExecutionResultContentPart; + export interface GeminiChatContent { role?: "user" | "model"; parts: GeminiChatContentPart[]; diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 1fa921da5..08d52d3b9 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -16,6 +16,7 @@ "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" }, "devDependencies": { @@ -4356,6 +4357,18 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 478b50f0d..82ba2509b 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -19,6 +19,7 @@ "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" }, "devDependencies": { diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index 336dee644..ab76a28d0 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -14,6 +14,7 @@ import { Model, } from "openai/resources/index"; +import { v4 as uuidv4 } from "uuid"; import { GeminiConfig } from "../types.js"; import { chatChunk, @@ -23,6 +24,8 @@ import { } from "../util.js"; import { convertOpenAIToolToGeminiFunction, + GeminiChatContent, + GeminiChatContentPart, GeminiToolFunctionDeclaration, } from "../util/gemini-types.js"; import { @@ -51,9 +54,15 @@ export class GeminiApi implements BaseLlmApi { } private _oaiPartToGeminiPart( - part: OpenAI.Chat.Completions.ChatCompletionContentPart, - ) { + part: + | OpenAI.Chat.Completions.ChatCompletionContentPart + | OpenAI.Chat.Completions.ChatCompletionContentPartRefusal, + ): GeminiChatContentPart { switch (part.type) { + case "refusal": + return { + text: part.refusal, + }; case "text": return { text: part.text, @@ -91,7 +100,15 @@ export class GeminiApi implements BaseLlmApi { const isV1API = url.includes("/v1/"); const toolCallIdToNameMap = new Map(); - const contents = oaiBody.messages + oaiBody.messages.forEach((msg) => { + if (msg.role === "assistant" && msg.tool_calls) { + msg.tool_calls.forEach((call) => { + toolCallIdToNameMap.set(call.id, call.function.name); + }); + } + }); + + const contents: (GeminiChatContent | null)[] = oaiBody.messages .map((msg) => { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents @@ -103,9 +120,10 @@ export class GeminiApi implements BaseLlmApi { } return { - role: "model", + role: "model" as const, parts: msg.tool_calls.map((toolCall) => ({ functionCall: { + id: toolCall.id, name: toolCall.function.name, args: JSON.parse(toolCall.function.arguments || "{}"), }, @@ -114,14 +132,15 @@ export class GeminiApi implements BaseLlmApi { } if (msg.role === "tool") { + const functionName = toolCallIdToNameMap.get(msg.tool_call_id); return { - role: "user", + role: "user" as const, parts: [ { functionResponse: { - name: msg.tool_call_id, + id: msg.tool_call_id, + name: functionName ?? "unknown", response: { - name: toolCallIdToNameMap.get(msg.tool_call_id), content: typeof msg.content === "string" ? msg.content @@ -138,12 +157,12 @@ export class GeminiApi implements BaseLlmApi { } return { - role: msg.role === "assistant" ? "model" : "user", + role: + msg.role === "assistant" ? ("model" as const) : ("user" as const), parts: typeof msg.content === "string" ? [{ text: msg.content }] - : // @ts-ignore - msg.content.map(this._oaiPartToGeminiPart), + : msg.content.map(this._oaiPartToGeminiPart), }; }) .filter((c) => c !== null); @@ -283,7 +302,7 @@ export class GeminiApi implements BaseLlmApi { tool_calls: [ { index: 0, - id: "", // Not supported by Gemini + id: part.functionCall.id ?? uuidv4(), type: "function", function: { name: part.functionCall.name, diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index d1921302e..44f752f40 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -175,50 +175,67 @@ export function convertOpenAIToolToGeminiFunction( return fn; } +export type GeminiTextContentPart = { + text: string; +}; + +export type GeminiInlineDataContentPart = { + inlineData: { + mimeType: string; + data: string; + }; +}; + +export type GeminiFunctionCallContentPart = { + functionCall: { + id?: string; + name: string; + args: JSONSchema7Object; + }; +}; + +export type GeminiFunctionResponseContentPart = { + functionResponse: { + id?: string; + name: string; + response: JSONSchema7Object; + }; +}; + +export type GeminiFileDataContentPart = { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; +}; + +export type GeminiExecutableCodeContentPart = { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; +}; + +export type GeminiCodeExecutionResultContentPart = { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; +}; + export type GeminiChatContentPart = - | { - text: string; - } - | { - inlineData: { - mimeType: string; - data: string; - }; - } - | { - functionCall: { - name: string; - args: JSONSchema7Object; - }; - } - | { - functionResponse: { - name: string; - response: JSONSchema7Object; - }; - } - | { - fileData: { - fileUri: string; - mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata - }; - } - | { - executableCode: { - language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; - code: string; - }; - } - | { - codeExecutionResult: { - outcome: - | "OUTCOME_UNSPECIFIED" - | "OUTCOME_OK" - | "OUTCOME_FAILED" - | "OUTCOME_DEADLINE_EXCEEDED"; - output: string; - }; - }; + | GeminiTextContentPart + | GeminiInlineDataContentPart + | GeminiFunctionCallContentPart + | GeminiFunctionResponseContentPart + | GeminiFileDataContentPart + | GeminiExecutableCodeContentPart + | GeminiCodeExecutionResultContentPart; + export interface GeminiChatContent { role?: "user" | "model"; parts: GeminiChatContentPart[]; From 397be9daa24dd8c86e5a9514186ddc7bf308db96 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 14 Apr 2025 15:20:51 -0700 Subject: [PATCH 08/92] bump version number --- packages/config-yaml/package-lock.json | 4 ++-- packages/config-yaml/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 4e5b8df05..58250c2d5 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.87", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.87", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index f32235580..ab9bbd2af 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.87", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From 91043f6f2c4341f0bb1959908f4138c304b91c45 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 16:10:36 -0700 Subject: [PATCH 09/92] fix parallel parts not working --- core/llm/llms/Gemini.ts | 77 +++++++++++------------------------------ 1 file changed, 21 insertions(+), 56 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 254afd6fa..b912564dc 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,5 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import { + AssistantChatMessage, ChatMessage, CompletionOptions, LLMOptions, @@ -337,75 +338,39 @@ class Gemini extends BaseLLM { // Check for existence of each level before accessing the final 'text' property const content = data?.candidates?.[0]?.content; if (content) { - const supportedParts: MessagePart[] = []; + const textParts: MessagePart[] = []; const toolCalls: ToolCallDelta[] = []; - // Process all parts first to maintain order - const processedParts: Array<{ - type: "content" | "tool" | "toolCall"; - data: any; - }> = []; - for (const part of content.parts) { if ("text" in part) { - supportedParts.push({ type: "text", text: part.text }); - } else if ("inlineData" in part) { - supportedParts.push({ - type: "imageUrl", - imageUrl: { - url: `data:image/jpeg;base64,${part.inlineData.data}`, - }, - }); + textParts.push({ type: "text", text: part.text }); } else if ("functionCall" in part) { - // Queue function call - processedParts.push({ - type: "toolCall", - data: { - type: "function", - id: part.functionCall.id ?? uuidv4(), - function: { - name: part.functionCall.name, - arguments: - typeof part.functionCall.args === "string" - ? part.functionCall.args - : JSON.stringify(part.functionCall.args), - }, - }, - }); - } else if ("functionResponse" in part) { - // Queue function response - processedParts.push({ - type: "tool", - data: { - role: "tool", - content: part.functionResponse.response.output as string, - toolCallId: part.functionResponse.name, + toolCalls.push({ + type: "function", + id: part.functionCall.id ?? uuidv4(), + function: { + name: part.functionCall.name, + arguments: + typeof part.functionCall.args === "string" + ? part.functionCall.args + : JSON.stringify(part.functionCall.args), }, }); } else { + // Note: function responses shouldn't be streamed, images not supported console.warn("Unsupported gemini part type received", part); } } - // If we have supported content parts, yield them first - if (supportedParts.length) { - yield { - role: "assistant", - content: supportedParts, - }; + const assistantMessage: AssistantChatMessage = { + role: "assistant", + content: textParts.length ? textParts : "", + }; + if (toolCalls.length > 0) { + assistantMessage.toolCalls = toolCalls; } - - // Then process tool calls and responses in order - for (const part of processedParts) { - if (part.type === "toolCall") { - yield { - role: "assistant", - content: "", - toolCalls: [part.data], - }; - } else if (part.type === "tool") { - yield part.data; - } + if (textParts.length || toolCalls.length) { + yield assistantMessage; } } else { // Handle the case where the expected data structure is not found From 12b3ed9291b4f46e920f8417f1e6585e45b7edd9 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 14 Apr 2025 22:55:24 -0700 Subject: [PATCH 10/92] feat: apply e2e tests --- .../vscode/e2e/actions/Apply.actions.ts | 16 ++++ .../vscode/e2e/actions/Global.actions.ts | 50 +++++++++- .../e2e/actions/KeyboardShortcuts.actions.ts | 25 ++++- .../vscode/e2e/selectors/Apply.selectors.ts | 15 +++ extensions/vscode/e2e/tests/Apply.test.ts | 92 +++++++++++++++++++ .../vscode/e2e/tests/Autocomplete.test.ts | 7 +- extensions/vscode/e2e/tests/Edit.test.ts | 6 +- .../e2e/tests/KeyboardShortcuts.test.ts | 21 +++-- .../StepContainerPreToolbar/ApplyActions.tsx | 3 + .../CreateFileButton.tsx | 1 + .../ToolbarButtonWithTooltip.tsx | 3 + .../StepContainerPreToolbar/index.tsx | 2 +- 12 files changed, 219 insertions(+), 22 deletions(-) create mode 100644 extensions/vscode/e2e/actions/Apply.actions.ts create mode 100644 extensions/vscode/e2e/selectors/Apply.selectors.ts create mode 100644 extensions/vscode/e2e/tests/Apply.test.ts diff --git a/extensions/vscode/e2e/actions/Apply.actions.ts b/extensions/vscode/e2e/actions/Apply.actions.ts new file mode 100644 index 000000000..44aa87e85 --- /dev/null +++ b/extensions/vscode/e2e/actions/Apply.actions.ts @@ -0,0 +1,16 @@ +import { WebView } from "vscode-extension-tester"; + +import { ApplySelectors } from "../selectors/Apply.selectors"; +import { TestUtils } from "../TestUtils"; + +export class ApplyActions { + static async performAction( + view: WebView, + action: "apply" | "accept" | "reject" | "create", + ) { + let applyButton = await TestUtils.waitForSuccess( + async () => await ApplySelectors.getCodeblockToolbarAction(view, action), + ); + applyButton.click(); + } +} diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index aafd1040a..d418fece3 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -7,12 +7,18 @@ import { } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; +import { TestUtils } from "../TestUtils"; export class GlobalActions { public static async openTestWorkspace() { - return VSBrowser.instance.openResources("e2e/test-continue"); + await VSBrowser.instance.openResources("e2e/test-continue"); + await new Workbench().executeCommand( + "Notifications: Clear All Notifications", + ); } + public static defaultNewFilename = "test.py"; + public static async createAndOpenNewTextFile(): Promise<{ editor: TextEditor; }> { @@ -26,4 +32,46 @@ export class GlobalActions { return { editor }; } + + public static async createAndSaveNewFile( + filename = GlobalActions.defaultNewFilename, + ): Promise<{ + editor: TextEditor; + }> { + let { editor } = await GlobalActions.createAndOpenNewTextFile(); + + await new Workbench().executeCommand("File: Save As..."); + const inputBox = await InputBox.create(DEFAULT_TIMEOUT.MD); + + // Get current path and replace filename + const currentPath = await inputBox.getText(); + const pathParts = currentPath.split(/[\/\\]/); + pathParts[pathParts.length - 1] = filename; + const newPath = pathParts.join("/"); + + await inputBox.setText(newPath); + + await inputBox.confirm(); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + editor = (await new EditorView().openEditor(filename)) as TextEditor; + + return { editor }; + } + + public static async deleteFile( + filename = GlobalActions.defaultNewFilename, + ): Promise { + const fs = require("fs"); + const path = require("path"); + + const workspacePath = path.join(process.cwd(), "e2e", "test-continue"); + const filePath = path.join(workspacePath, filename); + + try { + await fs.promises.unlink(filePath); + } catch (error) { + console.warn(`Failed to delete file ${filePath}:`, error); + } + } } diff --git a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts index 358d883bd..cac1097c7 100644 --- a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts +++ b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts @@ -1,4 +1,4 @@ -import { TextEditor } from "vscode-extension-tester"; +import { Key, TextEditor, WebElement } from "vscode-extension-tester"; export class KeyboardShortcutsActions { /** @@ -10,4 +10,27 @@ export class KeyboardShortcutsActions { await editor.selectText(text); await editor.typeText(text); } + + /** + * Types each string in the array with a newline (Shift+Enter) between them. + * Optionally adds a final Enter key press to submit. + */ + public static async typeWithNewlines({ + input, + lines, + submit, + }: { + input: TextEditor | WebElement; + lines: string[]; + submit?: boolean; + }) { + for (let i = 0; i < lines.length - 1; i++) { + await input.sendKeys(lines[i]); + await input.sendKeys(Key.chord(Key.SHIFT, Key.ENTER)); + } + await input.sendKeys(lines[lines.length - 1]); + if (submit) { + await input.sendKeys(Key.ENTER); + } + } } diff --git a/extensions/vscode/e2e/selectors/Apply.selectors.ts b/extensions/vscode/e2e/selectors/Apply.selectors.ts new file mode 100644 index 000000000..4d14f7ff5 --- /dev/null +++ b/extensions/vscode/e2e/selectors/Apply.selectors.ts @@ -0,0 +1,15 @@ +import { WebView } from "vscode-extension-tester"; + +import { SelectorUtils } from "./SelectorUtils"; + +export class ApplySelectors { + static getCodeblockToolbarAction( + view: WebView, + action: "apply" | "accept" | "reject" | "create", + ) { + return SelectorUtils.getElementByDataTestId( + view, + `codeblock-toolbar-${action}`, + ); + } +} diff --git a/extensions/vscode/e2e/tests/Apply.test.ts b/extensions/vscode/e2e/tests/Apply.test.ts new file mode 100644 index 000000000..6d893c835 --- /dev/null +++ b/extensions/vscode/e2e/tests/Apply.test.ts @@ -0,0 +1,92 @@ +import { TextEditor, VSBrowser, WebView } from "vscode-extension-tester"; + +import { ApplyActions } from "../actions/Apply.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { GUIActions } from "../actions/GUI.actions"; +import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import { TestUtils } from "../TestUtils"; + +describe("Apply Test", () => { + let view: WebView; + let editor: TextEditor; + let fileContent = "hello = 'world'"; + + before(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver); + await GlobalActions.openTestWorkspace(); + + ({ editor } = await GlobalActions.createAndSaveNewFile()); + }); + + beforeEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.typeTextAt(1, 1, fileContent); + await GUIActions.toggleGui(); + + ({ view } = await GUIActions.switchToReactIframe()); + await GUIActions.selectModelFromDropdown(view, "TEST LLM"); + }); + + afterEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.clearText(); + + ({ view } = await GUIActions.switchToReactIframe()); + const tipTapEditor = await GUISelectors.getMessageInputFieldAtIndex( + view, + 0, + ); + await tipTapEditor.clear(); + }); + + after(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await GlobalActions.deleteFile(); + }); + + it("Can reject and apply changes from sidebar", async () => { + const newFileContent = fileContent + "!"; + + const [messageInput] = await GUISelectors.getMessageInputFields(view); + + await KeyboardShortcutsActions.typeWithNewlines({ + submit: true, + input: messageInput, + lines: [ + "```py " + GlobalActions.defaultNewFilename, + newFileContent, + "```", + "_", // To avoid extra lines getting included in the block + ], + }); + + await ApplyActions.performAction(view, "apply"); + await ApplyActions.performAction(view, "reject"); + await view.switchBack(); + + let editorText = await editor.getText(); + + await TestUtils.waitForSuccess(async () => editorText === fileContent); + // expect(editorText).to.equal(fileContent); + + ({ view } = await GUIActions.switchToReactIframe()); + + await ApplyActions.performAction(view, "apply"); + await ApplyActions.performAction(view, "accept"); + await view.switchBack(); + + // Note that the editor after accpeting contains additional text + // from the default output of the test LLM, so instead of checking + // for an exact text match on the new content we just do a `.includes()` + editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => + editorText.includes(newFileContent), + ); + }).timeout(DEFAULT_TIMEOUT.XL); +}); diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index e6444c80c..836c2c60e 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,9 +1,4 @@ -import { - EditorView, - InputBox, - TextEditor, - Workbench, -} from "vscode-extension-tester"; +import { EditorView, TextEditor } from "vscode-extension-tester"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; import { GlobalActions } from "../actions/Global.actions"; diff --git a/extensions/vscode/e2e/tests/Edit.test.ts b/extensions/vscode/e2e/tests/Edit.test.ts index 66b82aaf3..6d8812ff1 100644 --- a/extensions/vscode/e2e/tests/Edit.test.ts +++ b/extensions/vscode/e2e/tests/Edit.test.ts @@ -1,9 +1,9 @@ import { expect } from "chai"; import { - WebView, - VSBrowser, - TextEditor, CodeLens, + TextEditor, + VSBrowser, + WebView, } from "vscode-extension-tester"; import { EditActions } from "../actions/Edit.actions"; diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index 0191d1d63..e9b79472f 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -1,21 +1,22 @@ +import { expect } from "chai"; import { - WebDriver, - VSBrowser, EditorView, InputBox, - TextEditor, - Workbench, - WebView, - WebElement, - until, Key, + TextEditor, + VSBrowser, + WebDriver, + WebElement, + WebView, + Workbench, + until, } from "vscode-extension-tester"; + +import { GUIActions } from "../actions/GUI.actions"; +import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; -import { GUIActions } from "../actions/GUI.actions"; -import { expect } from "chai"; import { TestUtils } from "../TestUtils"; -import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; describe("Keyboard Shortcuts", () => { let driver: WebDriver; diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index e645e68c9..7131e6ad9 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -36,6 +36,7 @@ export function ApplyActions(props: ApplyActionsProps) { const applyButton = (text: string) => (