-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini.service.ts
More file actions
240 lines (221 loc) · 8.55 KB
/
Copy pathgemini.service.ts
File metadata and controls
240 lines (221 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import { Service, computed, inject } from '@angular/core';
import { Observable } from 'rxjs';
import type { GoogleGenAI, ThinkingLevel as SdkThinkingLevel } from '@google/genai';
import { ApiKeyService } from './api-key.service';
import {
GEMINI_MODELS,
DEFAULT_MODEL,
ModelSelectionService,
type GeminiModelId,
} from './model-selection.service';
import { runAgentTurn, type AgentLoopDeps, type StreamRoundRequest } from './agent-loop';
import type { AgentEvent } from '../streaming/agent-event';
import { AgentEventStore } from '../streaming/agent-event.store';
import type { UserTurnInput } from '../media/attachment.types';
import type { GeminiChunk } from '../streaming/to-agent-event.operator';
import { InterruptService } from '../registry/interrupt.service';
import { ToolRegistry } from '../registry/tool-registry';
import { TokenAccountantService } from '../observability/token-accountant.service';
import { BudgetService } from '../observability/budget.service';
import { AgentRegistry } from '../agents/agent-registry.service';
import { CustomToolsService } from '../custom-tools/custom-tools.service';
import { ToolSynthesisSettings } from '../settings/tool-synthesis.settings';
import { AuthError, type AppError } from '../errors/app-error';
import { normalizeError } from '../errors/normalize-error';
import { retryWithBackoff } from '../errors/retry';
import { LoggerService } from '../logging/logger.service';
export { GEMINI_MODELS, DEFAULT_MODEL };
export type { GeminiModelId };
type ThinkingLevel = 'minimal' | 'low' | 'medium' | 'high';
// Hard-coded map keeps @google/genai out of the initial bundle (SDK enum uses the same lowercase strings).
const THINKING_LEVEL_MAP: Record<ThinkingLevel, SdkThinkingLevel> = {
minimal: 'minimal' as SdkThinkingLevel,
low: 'low' as SdkThinkingLevel,
medium: 'medium' as SdkThinkingLevel,
high: 'high' as SdkThinkingLevel,
};
let sdkModulePromise: Promise<typeof import('@google/genai')> | null = null;
function loadSdk(): Promise<typeof import('@google/genai')> {
if (!sdkModulePromise) {
sdkModulePromise = import('@google/genai');
}
return sdkModulePromise;
}
interface StreamOptions {
readonly model?: GeminiModelId;
readonly thinkingLevel?: ThinkingLevel;
readonly includeThoughts?: boolean;
readonly signal?: AbortSignal;
}
class MissingApiKeyError extends AuthError {
constructor() {
super({
code: 'missing_api_key',
userMessage: 'No Gemini API key set. Open Settings to add your key.',
technicalMessage: 'No Gemini API key set. Complete the onboarding flow first.',
});
this.name = 'MissingApiKeyError';
}
}
@Service()
export class GeminiService {
private readonly apiKey = inject(ApiKeyService);
private readonly store = inject(AgentEventStore);
private readonly registry = inject(ToolRegistry);
private readonly interrupts = inject(InterruptService);
private readonly tokenAccountant = inject(TokenAccountantService);
private readonly budget = inject(BudgetService);
private readonly modelSelection = inject(ModelSelectionService);
private readonly agents = inject(AgentRegistry);
private readonly customTools = inject(CustomToolsService);
private readonly toolSynthesis = inject(ToolSynthesisSettings);
private readonly logger = inject(LoggerService);
readonly selectedModel = this.modelSelection.selectedModel;
readonly ready = computed(() => this.apiKey.hasKey());
selectModel(model: GeminiModelId): void {
this.modelSelection.selectModel(model);
}
async testConnection(candidateKey: string): Promise<true> {
const trimmed = candidateKey?.trim();
if (!trimmed) throw new Error('Enter a key first.');
const { GoogleGenAI: GenAI } = await loadSdk();
const ai = new GenAI({ apiKey: trimmed });
try {
// Setup-only retry: one-shot probe with no partial output to duplicate.
const stream = await retryWithBackoff(
() =>
ai.models.generateContentStream({
model: 'gemini-3.5-flash',
contents: 'Reply with one word: ok',
config: { thinkingConfig: { thinkingLevel: 'minimal' as SdkThinkingLevel } },
}),
{
onRetry: (error, attempt, delayMs) =>
this.logRetry('testConnection', error, attempt, delayMs),
},
);
// Drain iterator so the HTTP connection closes cleanly.
for await (const _chunk of stream) {
void _chunk;
}
return true;
} catch (err) {
// Normalize at the SDK boundary so callers get a typed, redacted error.
throw normalizeError(err, { op: 'testConnection' });
}
}
streamAgentTurn(
input: string | UserTurnInput,
turnId: string,
options: StreamOptions = {},
): Observable<AgentEvent> {
return new Observable<AgentEvent>((subscriber) => {
const abort = new AbortController();
const externalSignal = options.signal;
// Named ref so teardown can removeEventListener — avoids leaking one listener per subscription.
let onExternalAbort: (() => void) | null = null;
if (externalSignal) {
if (externalSignal.aborted) {
abort.abort();
} else {
onExternalAbort = () => abort.abort();
externalSignal.addEventListener('abort', onExternalAbort);
}
}
(async () => {
try {
const ai = await this.createClient();
const deps = this.buildDeps(ai, turnId, abort.signal);
const loopOptions = {
model: options.model ?? this.selectedModel(),
thinkingConfig: buildThinkingConfig(options),
};
for await (const event of runAgentTurn(input, turnId, loopOptions, abort.signal, deps)) {
if (abort.signal.aborted) {
// External abort between iterations — complete subscriber so Observable does not hang.
subscriber.complete();
return;
}
subscriber.next(event);
}
subscriber.complete();
} catch (err) {
if (abort.signal.aborted) subscriber.complete();
else subscriber.error(err);
}
})();
return () => {
abort.abort();
if (externalSignal && onExternalAbort) {
externalSignal.removeEventListener('abort', onExternalAbort);
}
};
});
}
private buildDeps(ai: GoogleGenAI, turnId: string, signal: AbortSignal): AgentLoopDeps {
return {
streamChunks: async (req: StreamRoundRequest) => {
try {
// Setup-only retry: wraps stream establishment before any chunk is consumed.
const stream = await retryWithBackoff(
() =>
ai.models.generateContentStream({
model: req.model,
contents: req.contents as Parameters<
typeof ai.models.generateContentStream
>[0]['contents'],
config: req.config as Parameters<
typeof ai.models.generateContentStream
>[0]['config'],
}),
{
signal,
onRetry: (error, attempt, delayMs) =>
this.logRetry('streamChunks', error, attempt, delayMs, turnId),
},
);
return stream as AsyncIterable<GeminiChunk>;
} catch (err) {
// Normalize at the SDK boundary and stamp turn id for correlated errors upstream.
throw normalizeError(err, { op: 'streamChunks', model: req.model }).enrich({
correlationId: turnId,
});
}
},
store: this.store,
registry: this.registry,
interrupts: this.interrupts,
tokenAccountant: this.tokenAccountant,
budget: this.budget,
agents: this.agents,
customToolNames: () => this.customTools.customToolNames(),
allowToolSynthesis: () => this.toolSynthesis.enabled(),
logger: this.logger,
};
}
private logRetry(
op: string,
error: AppError,
attempt: number,
delayMs: number,
turnId?: string,
): void {
this.logger.warn(`Gemini ${op} failed; retrying (attempt ${attempt}).`, {
category: error.category,
correlationId: turnId,
context: { op, attempt, delayMs, code: error.code },
});
}
private async createClient(): Promise<GoogleGenAI> {
const key = this.apiKey.key();
if (!key) throw new MissingApiKeyError();
const { GoogleGenAI: GenAI } = await loadSdk();
return new GenAI({ apiKey: key });
}
}
function buildThinkingConfig(options: StreamOptions) {
return {
includeThoughts: options.includeThoughts ?? true,
thinkingLevel: THINKING_LEVEL_MAP[options.thinkingLevel ?? 'high'],
};
}