-
Notifications
You must be signed in to change notification settings - Fork 17
feat: Support Gemini via Vertex AI #2030
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2f08336
feat: Support Gemini via Vertex AI
dividedmind 278546b
dev: Allow full-file lint exclusions
dividedmind b703226
dev: Add configuration for navie for VSCode Jest plugin
dividedmind 7c82fbd
chore: Type InteractionHistory.on correctly
dividedmind 9199f63
chore: Type Trajectory.on correctly
dividedmind 9ec919f
chore: Refactor mocking completions in tests
dividedmind f1e6372
Use structured output for the vector terms service
dividedmind File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,17 @@ | ||
{ | ||
"editor.rulers": [100], | ||
"editor.rulers": [ | ||
100 | ||
], | ||
"editor.formatOnSave": true, | ||
"editor.defaultFormatter": "esbenp.prettier-vscode", | ||
"jest.virtualFolders": [ | ||
{ | ||
"name": "cli", | ||
"rootPath": "packages/cli" | ||
}, | ||
{ | ||
"name": "navie", | ||
"rootPath": "packages/navie" | ||
} | ||
], | ||
} | ||
] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,5 +43,8 @@ | |
"packageManager": "[email protected]", | ||
"dependencies": { | ||
"puppeteer": "^19.7.2" | ||
}, | ||
"resolutions": { | ||
"web-auth-library": "getappmap/web-auth-library#v1.0.3-cjs" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
packages/navie/src/services/google-vertexai-completion-service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import { warn } from 'node:console'; | ||
import { isNativeError } from 'node:util/types'; | ||
|
||
import { ChatVertexAI, type ChatVertexAIInput } from '@langchain/google-vertexai-web'; | ||
import { zodResponseFormat } from 'openai/helpers/zod'; | ||
import { z } from 'zod'; | ||
|
||
import Trajectory from '../lib/trajectory'; | ||
import Message from '../message'; | ||
import CompletionService, { | ||
CompleteOptions, | ||
Completion, | ||
CompletionRetries, | ||
CompletionRetryDelay, | ||
convertToMessage, | ||
mergeSystemMessages, | ||
Usage, | ||
} from './completion-service'; | ||
|
||
export default class GoogleVertexAICompletionService implements CompletionService { | ||
constructor( | ||
public readonly modelName: string, | ||
public readonly temperature: number, | ||
private trajectory: Trajectory | ||
) {} | ||
|
||
// Construct a model with non-default options. There doesn't seem to be a way to configure | ||
// the model parameters at invocation time like with OpenAI. | ||
private buildModel(options?: ChatVertexAIInput): ChatVertexAI { | ||
return new ChatVertexAI({ | ||
model: this.modelName, | ||
temperature: this.temperature, | ||
streaming: true, | ||
maxOutputTokens: 8192, | ||
...options, | ||
}); | ||
} | ||
|
||
get miniModelName(): string { | ||
const miniModel = process.env.APPMAP_NAVIE_MINI_MODEL; | ||
return miniModel ?? 'gemini-1.5-flash-002'; | ||
} | ||
|
||
// Request a JSON object with a given JSON schema. | ||
async json<Schema extends z.ZodType>( | ||
messages: Message[], | ||
schema: Schema, | ||
options?: CompleteOptions | ||
): Promise<z.infer<Schema> | undefined> { | ||
const model = this.buildModel({ | ||
...options, | ||
streaming: false, | ||
responseMimeType: 'application/json', | ||
}); | ||
const sentMessages = mergeSystemMessages([ | ||
...messages, | ||
{ | ||
role: 'system', | ||
content: `Use the following JSON schema for your response:\n\n${JSON.stringify( | ||
zodResponseFormat(schema, 'requestedObject').json_schema.schema, | ||
null, | ||
2 | ||
)}`, | ||
}, | ||
]); | ||
|
||
for (const message of sentMessages) this.trajectory.logSentMessage(message); | ||
|
||
const response = await model.invoke(sentMessages.map(convertToMessage)); | ||
|
||
this.trajectory.logReceivedMessage({ | ||
role: 'assistant', | ||
content: JSON.stringify(response), | ||
}); | ||
|
||
const sanitizedContent = response.content.toString().replace(/^`{3,}[^\s]*?$/gm, ''); | ||
const parsed = JSON.parse(sanitizedContent) as unknown; | ||
schema.parse(parsed); | ||
return parsed; | ||
} | ||
|
||
async *complete(messages: readonly Message[], options?: { temperature?: number }): Completion { | ||
const usage = new Usage(); | ||
const model = this.buildModel(options); | ||
const sentMessages: Message[] = mergeSystemMessages(messages); | ||
const tokens = new Array<string>(); | ||
for (const message of sentMessages) this.trajectory.logSentMessage(message); | ||
|
||
const maxAttempts = CompletionRetries; | ||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) { | ||
try { | ||
// eslint-disable-next-line no-await-in-loop | ||
const response = await model.stream(sentMessages.map(convertToMessage)); | ||
|
||
// eslint-disable-next-line @typescript-eslint/naming-convention, no-await-in-loop | ||
for await (const { content, usage_metadata } of response) { | ||
yield content.toString(); | ||
tokens.push(content.toString()); | ||
if (usage_metadata) { | ||
usage.promptTokens += usage_metadata.input_tokens; | ||
usage.completionTokens += usage_metadata.output_tokens; | ||
} | ||
} | ||
|
||
this.trajectory.logReceivedMessage({ | ||
role: 'assistant', | ||
content: tokens.join(''), | ||
}); | ||
|
||
break; | ||
} catch (cause) { | ||
if (attempt < maxAttempts - 1 && tokens.length === 0) { | ||
const nextAttempt = CompletionRetryDelay * 2 ** attempt; | ||
warn(`Received ${JSON.stringify(cause)}, retrying in ${nextAttempt}ms`); | ||
await new Promise<void>((resolve) => { | ||
setTimeout(resolve, nextAttempt); | ||
}); | ||
continue; | ||
} | ||
Comment on lines
+112
to
+119
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note that this doesn't attempt to prune input tokens There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, I figured it's unlikely to be necessary with 2M token input limit... |
||
throw new Error( | ||
`Failed to complete after ${attempt + 1} attempt(s): ${errorMessage(cause)}`, | ||
{ | ||
cause, | ||
} | ||
); | ||
} | ||
} | ||
|
||
warn(usage.toString()); | ||
return usage; | ||
} | ||
} | ||
|
||
function errorMessage(err: unknown): string { | ||
if (isNativeError(err)) return err.cause ? errorMessage(err.cause) : err.message; | ||
return String(err); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.