|
| 1 | +import { |
| 2 | + CachedContent, |
| 3 | + createPartFromUri, |
| 4 | + createUserContent, |
| 5 | + GenerateContentResponse, |
| 6 | + GoogleGenAI, |
| 7 | +} from "@google/genai"; |
| 8 | +import * as path from "path"; |
| 9 | +import { BaseAiAgent } from "./base"; |
| 10 | +import { Orchestrator } from "./orchestrator"; |
| 11 | + |
| 12 | +export class FileUploadAgent extends BaseAiAgent { |
| 13 | + private readonly ai: GoogleGenAI; |
| 14 | + protected readonly orchestrator: Orchestrator; |
| 15 | + private static readonly PROCESSING_WAIT_TIME_MS = 6000; |
| 16 | + private static readonly MAX_CACHE_PAGE_SIZE = 10; |
| 17 | + private static readonly CACHE_MODEL = "gemini-1.5-flash-002"; |
| 18 | + constructor(private readonly apiKey: string) { |
| 19 | + super(); |
| 20 | + this.ai = new GoogleGenAI({ apiKey: this.apiKey }); |
| 21 | + this.orchestrator = Orchestrator.getInstance(); |
| 22 | + } |
| 23 | + |
| 24 | + private async uploadFile(filePath: string, displayName: string) { |
| 25 | + try { |
| 26 | + return await this.ai.files.upload({ |
| 27 | + file: filePath, |
| 28 | + config: { displayName }, |
| 29 | + }); |
| 30 | + } catch (error) { |
| 31 | + console.error(`Failed to upload file: ${filePath}`, error); |
| 32 | + throw new Error( |
| 33 | + `File upload failed: ${error instanceof Error ? error.message : String(error)}`, |
| 34 | + ); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + async uploadAndProcessFile( |
| 39 | + filePath: string, |
| 40 | + displayName: string, |
| 41 | + prompt: string = "Summarize this document", |
| 42 | + ): Promise<string | undefined> { |
| 43 | + let file; |
| 44 | + try { |
| 45 | + file = (await this.uploadFile(filePath, displayName)) as any; |
| 46 | + const processedFile = await this.waitForProcessing(file.name); |
| 47 | + |
| 48 | + const result = await this.generateContentWithFile(processedFile, prompt); |
| 49 | + if (result.response) { |
| 50 | + this.orchestrator.publish("onResponse", JSON.stringify(result)); |
| 51 | + } |
| 52 | + return result.response; |
| 53 | + } catch (error) { |
| 54 | + this.logger.info(`Failed to process file: ${file.name}`); |
| 55 | + throw new Error( |
| 56 | + `File processing pipeline failed: ${error instanceof Error ? error.message : String(error)}`, |
| 57 | + ); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private delay(ms: number): Promise<void> { |
| 62 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 63 | + } |
| 64 | + |
| 65 | + private async waitForProcessing(fileName: string, maxRetries = 10) { |
| 66 | + try { |
| 67 | + let getFile = await this.ai.files.get({ name: fileName }); |
| 68 | + let retries = 0; |
| 69 | + while (getFile.state === "PROCESSING" && retries < maxRetries) { |
| 70 | + this.logger.info("☕ File upload in progress, grab a cup of coffee"); |
| 71 | + await this.delay(FileUploadAgent.PROCESSING_WAIT_TIME_MS); |
| 72 | + getFile = await this.ai.files.get({ name: fileName }); |
| 73 | + retries++; |
| 74 | + } |
| 75 | + if (getFile.state === "FAILED") { |
| 76 | + this.logger.info("File processing failed"); |
| 77 | + } |
| 78 | + return getFile; |
| 79 | + } catch (error: any) { |
| 80 | + console.error("File processing failed.", error); |
| 81 | + throw new Error(error.message); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + private async generateContentWithFile( |
| 86 | + file: any, |
| 87 | + prompt: string, |
| 88 | + cacheName?: string, |
| 89 | + ): Promise<{ |
| 90 | + response: string | undefined; |
| 91 | + fileName: string; |
| 92 | + cache: string | undefined; |
| 93 | + }> { |
| 94 | + try { |
| 95 | + const fileContent = createPartFromUri(file.uri, file.mimeType); |
| 96 | + let cached = cacheName |
| 97 | + ? await this.findOrCreateCache(cacheName, fileContent) |
| 98 | + : await this.createNewCache(fileContent); |
| 99 | + |
| 100 | + const response = await this.generateContentWithCache( |
| 101 | + prompt, |
| 102 | + cached.name ?? "", |
| 103 | + ); |
| 104 | + const fileName = file.fsPath ? path.basename(file.fsPath) : ""; |
| 105 | + |
| 106 | + return { |
| 107 | + response: response.text, |
| 108 | + fileName, |
| 109 | + cache: cached.name, |
| 110 | + }; |
| 111 | + } catch (error) { |
| 112 | + this.logger.error("Failed to generate content with file", error); |
| 113 | + return { |
| 114 | + response: undefined, |
| 115 | + fileName: "", |
| 116 | + cache: undefined, |
| 117 | + }; |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + private async findOrCreateCache( |
| 122 | + cacheName: string, |
| 123 | + fileContent: any, |
| 124 | + ): Promise<CachedContent> { |
| 125 | + try { |
| 126 | + return await this.getDocCache(cacheName); |
| 127 | + } catch (error) { |
| 128 | + return await this.createNewCache(fileContent); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + private async createNewCache(fileContent: any): Promise<CachedContent> { |
| 133 | + const cached = await this.ai.caches.create({ |
| 134 | + model: FileUploadAgent.CACHE_MODEL, |
| 135 | + config: { |
| 136 | + contents: createUserContent(fileContent), |
| 137 | + systemInstruction: "You are an expert analyzing documents", |
| 138 | + }, |
| 139 | + }); |
| 140 | + this.logger.info("Cache created:", cached); |
| 141 | + return cached; |
| 142 | + } |
| 143 | + |
| 144 | + private async generateContentWithCache( |
| 145 | + prompt: string, |
| 146 | + cacheName: string, |
| 147 | + ): Promise<GenerateContentResponse> { |
| 148 | + return await this.ai.models.generateContent({ |
| 149 | + model: FileUploadAgent.CACHE_MODEL, |
| 150 | + contents: prompt, |
| 151 | + config: { cachedContent: cacheName }, |
| 152 | + }); |
| 153 | + } |
| 154 | + |
| 155 | + private async getDocCache(name: string): Promise<CachedContent> { |
| 156 | + try { |
| 157 | + const cache = await this.ai.caches.get({ name }); |
| 158 | + this.logger.info("Cache found:", cache); |
| 159 | + return cache; |
| 160 | + } catch (error: any) { |
| 161 | + throw new Error("Cache not found or error occurred:", error); |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + async getCaches(): Promise<CachedContent[]> { |
| 166 | + this.logger.info("Retrieving caches"); |
| 167 | + const caches: CachedContent[] = []; |
| 168 | + |
| 169 | + try { |
| 170 | + const pager = await this.ai.caches.list({ |
| 171 | + config: { pageSize: FileUploadAgent.MAX_CACHE_PAGE_SIZE }, |
| 172 | + }); |
| 173 | + |
| 174 | + let page = pager.page; |
| 175 | + |
| 176 | + do { |
| 177 | + caches.push(...page); |
| 178 | + if (!pager.hasNextPage()) break; |
| 179 | + page = await pager.nextPage(); |
| 180 | + } while (true); |
| 181 | + |
| 182 | + return caches; |
| 183 | + } catch (error) { |
| 184 | + console.log("Failed to retrieve caches", error); |
| 185 | + throw new Error( |
| 186 | + `Failed to retrieve caches: ${error instanceof Error ? error.message : String(error)}`, |
| 187 | + ); |
| 188 | + } |
| 189 | + } |
| 190 | +} |
0 commit comments