|
| 1 | +import { warn } from 'node:console'; |
| 2 | +import { isNativeError } from 'node:util/types'; |
| 3 | + |
| 4 | +import { ChatVertexAI, type ChatVertexAIInput } from '@langchain/google-vertexai-web'; |
| 5 | +import { zodResponseFormat } from 'openai/helpers/zod'; |
| 6 | +import { z } from 'zod'; |
| 7 | + |
| 8 | +import Trajectory from '../lib/trajectory'; |
| 9 | +import Message from '../message'; |
| 10 | +import CompletionService, { |
| 11 | + CompleteOptions, |
| 12 | + Completion, |
| 13 | + CompletionRetries, |
| 14 | + CompletionRetryDelay, |
| 15 | + convertToMessage, |
| 16 | + mergeSystemMessages, |
| 17 | + Usage, |
| 18 | +} from './completion-service'; |
| 19 | + |
| 20 | +export default class GoogleVertexAICompletionService implements CompletionService { |
| 21 | + constructor( |
| 22 | + public readonly modelName: string, |
| 23 | + public readonly temperature: number, |
| 24 | + private trajectory: Trajectory |
| 25 | + ) {} |
| 26 | + |
| 27 | + // Construct a model with non-default options. There doesn't seem to be a way to configure |
| 28 | + // the model parameters at invocation time like with OpenAI. |
| 29 | + private buildModel(options?: ChatVertexAIInput): ChatVertexAI { |
| 30 | + return new ChatVertexAI({ |
| 31 | + model: this.modelName, |
| 32 | + temperature: this.temperature, |
| 33 | + streaming: true, |
| 34 | + ...options, |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + get miniModelName(): string { |
| 39 | + const miniModel = process.env.APPMAP_NAVIE_MINI_MODEL; |
| 40 | + return miniModel ?? 'gemini-1.5-flash-002'; |
| 41 | + } |
| 42 | + |
| 43 | + // Request a JSON object with a given JSON schema. |
| 44 | + async json<Schema extends z.ZodType>( |
| 45 | + messages: Message[], |
| 46 | + schema: Schema, |
| 47 | + options?: CompleteOptions |
| 48 | + ): Promise<z.infer<Schema> | undefined> { |
| 49 | + const model = this.buildModel({ |
| 50 | + ...options, |
| 51 | + streaming: false, |
| 52 | + responseMimeType: 'application/json', |
| 53 | + }); |
| 54 | + const sentMessages = mergeSystemMessages([ |
| 55 | + ...messages, |
| 56 | + { |
| 57 | + role: 'system', |
| 58 | + content: `Use the following JSON schema for your response:\n\n${JSON.stringify( |
| 59 | + zodResponseFormat(schema, 'requestedObject').json_schema.schema, |
| 60 | + null, |
| 61 | + 2 |
| 62 | + )}`, |
| 63 | + }, |
| 64 | + ]); |
| 65 | + |
| 66 | + for (const message of sentMessages) this.trajectory.logSentMessage(message); |
| 67 | + |
| 68 | + const response = await model.invoke(sentMessages.map(convertToMessage)); |
| 69 | + |
| 70 | + this.trajectory.logReceivedMessage({ |
| 71 | + role: 'assistant', |
| 72 | + content: JSON.stringify(response), |
| 73 | + }); |
| 74 | + |
| 75 | + const sanitizedContent = response.content.toString().replace(/^`{3,}[^\s]*?$/gm, ''); |
| 76 | + const parsed = JSON.parse(sanitizedContent) as unknown; |
| 77 | + schema.parse(parsed); |
| 78 | + return parsed; |
| 79 | + } |
| 80 | + |
| 81 | + async *complete(messages: readonly Message[], options?: { temperature?: number }): Completion { |
| 82 | + const usage = new Usage(); |
| 83 | + const model = this.buildModel(options); |
| 84 | + const sentMessages: Message[] = mergeSystemMessages(messages); |
| 85 | + const tokens = new Array<string>(); |
| 86 | + for (const message of sentMessages) this.trajectory.logSentMessage(message); |
| 87 | + |
| 88 | + const maxAttempts = CompletionRetries; |
| 89 | + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { |
| 90 | + try { |
| 91 | + // eslint-disable-next-line no-await-in-loop |
| 92 | + const response = await model.stream(sentMessages.map(convertToMessage)); |
| 93 | + |
| 94 | + // eslint-disable-next-line @typescript-eslint/naming-convention, no-await-in-loop |
| 95 | + for await (const { content, usage_metadata } of response) { |
| 96 | + yield content.toString(); |
| 97 | + tokens.push(content.toString()); |
| 98 | + if (usage_metadata) { |
| 99 | + usage.promptTokens += usage_metadata.input_tokens; |
| 100 | + usage.completionTokens += usage_metadata.output_tokens; |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + this.trajectory.logReceivedMessage({ |
| 105 | + role: 'assistant', |
| 106 | + content: tokens.join(''), |
| 107 | + }); |
| 108 | + |
| 109 | + break; |
| 110 | + } catch (cause) { |
| 111 | + if (attempt < maxAttempts - 1 && tokens.length === 0) { |
| 112 | + const nextAttempt = CompletionRetryDelay * 2 ** attempt; |
| 113 | + warn(`Received ${JSON.stringify(cause)}, retrying in ${nextAttempt}ms`); |
| 114 | + await new Promise<void>((resolve) => { |
| 115 | + setTimeout(resolve, nextAttempt); |
| 116 | + }); |
| 117 | + continue; |
| 118 | + } |
| 119 | + throw new Error( |
| 120 | + `Failed to complete after ${attempt + 1} attempt(s): ${errorMessage(cause)}`, |
| 121 | + { |
| 122 | + cause, |
| 123 | + } |
| 124 | + ); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + warn(usage.toString()); |
| 129 | + return usage; |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +function errorMessage(err: unknown): string { |
| 134 | + if (isNativeError(err)) return err.cause ? errorMessage(err.cause) : err.message; |
| 135 | + return String(err); |
| 136 | +} |
0 commit comments