diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index c25826cdf..e21663eef 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -13,12 +13,14 @@ "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.31", "@continuedev/fetch": "^1.0.3", + "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", "zod": "^3.23.8" }, "devDependencies": { "@types/follow-redirects": "^1.14.4", + "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", "ts-jest": "^29.2.3", "ts-node": "^10.9.2" @@ -1259,6 +1261,12 @@ "@types/istanbul-lib-report": "*" } }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, "node_modules/@types/node": { "version": "18.19.39", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.39.tgz", @@ -3307,6 +3315,11 @@ "dev": true, "peer": true }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index b1c6fb5ea..284d0bbc8 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -16,12 +16,14 @@ "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.31", "@continuedev/fetch": "^1.0.3", + "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", "zod": "^3.23.8" }, "devDependencies": { "@types/follow-redirects": "^1.14.4", + "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", "ts-jest": "^29.2.3", "ts-node": "^10.9.2" diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index 716d8d582..ae2235d25 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -15,7 +15,13 @@ import { } from "openai/resources/index"; import { GeminiConfig } from "../types.js"; -import { customFetch, embedding } from "../util.js"; +import { + chatChunk, + chatChunkFromDelta, + customFetch, + embedding, +} from "../util.js"; +import { GeminiToolFunctionDeclaration } from "../util/gemini-types.js"; import { BaseLlmApi, CreateRerankResponse, @@ -101,7 +107,7 @@ export class GeminiApi implements BaseLlmApi { .filter((c) => c !== null); const sysMsg = oaiBody.messages.find((msg) => msg.role === "system"); - const finalBody = { + const finalBody: any = { generationConfig, contents, // if this.systemMessage is defined, reformat it for Gemini API @@ -110,6 +116,90 @@ export class GeminiApi implements BaseLlmApi { systemInstruction: { parts: [{ text: sysMsg.content }] }, }), }; + + if (!isV1API) { + // Convert and add tools if present + if (oaiBody.tools?.length) { + // Choosing to map all tools to the functionDeclarations of one tool + // Rather than map each tool to its own tool + functionDeclaration + // 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); + } + }); + if (functions.length) { + finalBody.tools = [ + { + functionDeclarations: functions, + }, + ]; + } + } + } + return finalBody; } @@ -190,28 +280,35 @@ export class GeminiApi implements BaseLlmApi { if (data.error) { throw new Error(data.error.message); } - // Check for existence of each level before accessing the final 'text' property - if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { - yield { - id: "", - object: "chat.completion.chunk", - model: body.model, - created: Date.now(), - choices: [ - { - index: 0, - logprobs: undefined, - finish_reason: null, + + const content = data?.candidates?.[0]?.content; + if (content) { + for (const part of content.parts) { + if ("text" in part) { + yield chatChunk({ + content: part.text, + model: body.model, + }); + } else if ("functionCall" in part) { + yield chatChunkFromDelta({ + model: body.model, delta: { - role: "assistant", - content: data.candidates[0].content.parts[0].text, + tool_calls: [ + { + index: 0, + id: "", // Not supported by Gemini + type: "function", + function: { + name: part.functionCall.name, + arguments: JSON.stringify(part.functionCall.args), + }, + }, + ], }, - }, - ], - usage: undefined, - }; + }); + } + } } else { - // Handle the case where the expected data structure is not found console.warn("Unexpected response format:", data); } } diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index 3ac1354b5..4222216ff 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -46,12 +46,12 @@ const TESTS: Omit[] = [ apiKey: process.env.ANTHROPIC_API_KEY!, roles: ["chat"], }, - // { - // provider: "gemini", - // model: "gemini-1.5-flash-latest", - // apiKey: process.env.GEMINI_API_KEY!, - // roles: ["chat"], - // }, + { + provider: "gemini", + model: "gemini-1.5-flash-latest", + apiKey: process.env.GEMINI_API_KEY!, + roles: ["chat"], + }, { provider: "mistral", model: "codestral-latest", diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index 50bf133ff..5b1b52ab1 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -201,12 +201,18 @@ export function testChat(api: BaseLlmApi, model: string) { expect(completion?.startsWith("RESPONSE: ")).toBe(true); }); - test.only("Tool Call works", async () => { + test("Tool Call works", async () => { let args = ""; let isFirstChunk = true; for await (const chunk of api.chatCompletionStream( { - messages: [{ role: "user", content: "Hi, my name is Nate." }], + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me.", + }, + ], tools: [ { function: { @@ -251,7 +257,6 @@ export function testChat(api: BaseLlmApi, model: string) { } } - console.log("args", args); const parsedArgs = JSON.parse(args); expect(parsedArgs.name).toBe("Nate"); }); diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts new file mode 100644 index 000000000..b9fb52c1d --- /dev/null +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -0,0 +1,268 @@ +import { JSONSchema7Object } from "json-schema"; + +// https://ai.google.dev/api/generate-content +export interface GeminiGenerationConfig { + stopSequences?: string[]; + responseMimeType?: string; + candidateCount?: number; + maxOutputTokens?: number; + temperature?: number; + topP?: number; + topK?: number; + presencePenalty?: number; + frequencyPenalty?: number; + responseLogprobs?: boolean; + logprobs?: number; + // responseSchema?: object; // https://ai.google.dev/api/caching#Schema +} + +export interface GeminiFunctionSchema { + type: + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: Record; + required?: string[]; + items?: GeminiFunctionSchema; +} + +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; + }; + }; +export interface GeminiChatContent { + role?: "user" | "model"; + parts: GeminiChatContentPart[]; +} + +export interface GeminiToolFunctionDeclaration { + name: string; + description: string; + parameters?: GeminiFunctionSchema; +} +export interface GeminiTool { + functionDeclarations?: GeminiToolFunctionDeclaration[]; + googleSearchRetrieval?: { + dynamicRetrievalConfig: { + mode?: "MODE_DYNAMIC" | "MODE_UNSPECIFIED"; + dynamicThreshold?: number; + }; + }; + codeExecution?: {}; +} + +export interface GeminiToolConfig { + functionCallingConfig?: { + mode?: "NONE" | "ANY" | "AUTO"; + allowedFunctionNames?: string[]; + }; +} + +// https://ai.google.dev/api/generate-content#request-body +export interface GeminiChatRequestBody { + contents: GeminiChatContent[]; + tools?: GeminiTool[]; + toolConfig?: GeminiToolConfig; + systemInstruction?: GeminiChatContent; + generationConfig?: GeminiGenerationConfig; + // cachedContent?: string; +} + +export interface GeminiChatResponseSuccess { + candidates: Candidate[]; + promptFeedback: PromptFeedback; + usageMetadata: UsageMetadata; +} + +export interface GeminiChatResponseError { + error: { + message: string; + }; +} + +export type GeminiChatResponse = + | GeminiChatResponseError + | GeminiChatResponseSuccess; + +interface PromptFeedback { + blockReason?: BlockReason; + safetyRatings: SafetyRating[]; +} + +enum BlockReason { + BLOCK_REASON_UNSPECIFIED = "BLOCK_REASON_UNSPECIFIED", + SAFETY = "SAFETY", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", +} + +interface SafetyRating { + harmCategory: HarmCategory; + harmProbability: HarmProbability; + blocked: boolean; +} + +enum HarmCategory { + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + HARM_CATEGORY_DEROGATORY = "HARM_CATEGORY_DEROGATORY", + HARM_CATEGORY_TOXICITY = "HARM_CATEGORY_TOXICITY", + HARM_CATEGORY_VIOLENCE = "HARM_CATEGORY_VIOLENCE", + HARM_CATEGORY_SEXUAL = "HARM_CATEGORY_SEXUAL", + HARM_CATEGORY_MEDICAL = "HARM_CATEGORY_MEDICAL", + HARM_CATEGORY_DANGEROUS = "HARM_CATEGORY_DANGEROUS", + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", +} + +enum HarmProbability { + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + NEGLIGIBLE = "NEGLIGIBLE", + LOW = "LOW", + MEDIUM = "MEDIUM", + HIGH = "HIGH", +} + +interface UsageMetadata { + promptTokenCount: number; + cachedContentTokenCount: number; + candidatesTokenCount: number; + totalTokenCount: number; +} + +interface Candidate { + content: GeminiChatContent; + finishReason: FinishReason; + safetyRatings: SafetyRating[]; + tokenCount: number; + groundingAttribution?: GroundingAttribution; + groundingMetadata?: GroundingMetadata; + avgLogprobs?: number; + logprobs?: LogprobsResult; + index: number; +} + +enum FinishReason { + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + STOP = "STOP", + MAX_TOKENS = "MAX_TOKENS", + SAFETY = "SAFETY", + RECITATION = "RECITATION", + LANGUAGE = "LANGUAGE", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + SPII = "SPII", + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", +} + +interface GroundingAttribution { + attributionSourceId: AttributionSourceId; + groundingSourceContent: string; +} + +interface AttributionSourceId { + groundingPassage?: GroundingPassageId; + semanticRetrieverChunk?: SemanticRetrieverChunk; +} + +interface GroundingPassageId { + passageId: string; + partIndex: number; +} + +interface SemanticRetrieverChunk { + source: string; + chunk: string; +} + +interface GroundingMetadata { + groundingSupport?: GroundingSupport[]; + webSearchQueries?: string[]; + searchEntryPoint?: SearchEntryPoint; + retrievalMetadata?: RetrievalMetadata; +} + +interface SearchEntryPoint { + renderedContent?: string; + sdkBlob?: string; +} + +interface RetrievalMetadata { + googleSearchDynamicRetrievalScore?: number; +} + +interface GroundingSupport { + groundingChunkIndices: number[]; + confidenceScores: number[]; + segment: Segment; +} + +interface Segment { + partIndex: number; + startIndex: number; + endIndex: number; + text: string; +} + +interface LogprobsResult { + topCandidates: TopCandidates[]; + chosenCandidates: Candidate[]; +} + +interface TopCandidates { + candidates: Candidate[]; +}