-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathservice.ts
More file actions
164 lines (140 loc) · 4.03 KB
/
service.ts
File metadata and controls
164 lines (140 loc) · 4.03 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
import {
getGatewayUsageUrl,
getLlmGatewayUrl,
} from "@posthog/agent/posthog-api";
import { net } from "electron";
import { inject, injectable } from "inversify";
import { MAIN_TOKENS } from "../../di/tokens";
import { logger } from "../../utils/logger";
import type { AuthService } from "../auth/service";
import type {
AnthropicErrorResponse,
AnthropicMessagesRequest,
AnthropicMessagesResponse,
LlmMessage,
PromptOutput,
UsageOutput,
} from "./schemas";
const log = logger.scope("llm-gateway");
export class LlmGatewayError extends Error {
constructor(
message: string,
public readonly type: string,
public readonly code?: string,
public readonly statusCode?: number,
) {
super(message);
this.name = "LlmGatewayError";
}
}
@injectable()
export class LlmGatewayService {
constructor(
@inject(MAIN_TOKENS.AuthService)
private readonly authService: AuthService,
) {}
async prompt(
messages: LlmMessage[],
options: {
system?: string;
maxTokens?: number;
model?: string;
} = {},
): Promise<PromptOutput> {
const { system, maxTokens, model = "claude-haiku-4-5" } = options;
const auth = await this.authService.getValidAccessToken();
const gatewayUrl = getLlmGatewayUrl(auth.apiHost);
const messagesUrl = `${gatewayUrl}/v1/messages`;
const requestBody: AnthropicMessagesRequest = {
model,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
stream: false,
};
if (maxTokens !== undefined) {
requestBody.max_tokens = maxTokens;
}
if (system) {
requestBody.system = system;
}
log.debug("Sending request to LLM gateway", {
url: messagesUrl,
model,
messageCount: messages.length,
});
const response = await this.authService.authenticatedFetch(
net.fetch,
messagesUrl,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
},
);
if (!response.ok) {
const errorBody = await response.text();
let errorData: AnthropicErrorResponse | null = null;
try {
errorData = JSON.parse(errorBody) as AnthropicErrorResponse;
} catch {
log.error("Failed to parse error response", {
errorBody,
status: response.status,
});
}
const errorMessage =
errorData?.error?.message ||
`HTTP ${response.status}: ${response.statusText}`;
const errorType = errorData?.error?.type || "unknown_error";
const errorCode = errorData?.error?.code;
log.error("LLM gateway request failed", {
status: response.status,
errorType,
errorMessage,
});
throw new LlmGatewayError(
errorMessage,
errorType,
errorCode,
response.status,
);
}
const data = (await response.json()) as AnthropicMessagesResponse;
const textContent = data.content.find((c) => c.type === "text");
const content = textContent?.text || "";
log.debug("LLM gateway response received", {
model: data.model,
stopReason: data.stop_reason,
inputTokens: data.usage.input_tokens,
outputTokens: data.usage.output_tokens,
});
return {
content,
model: data.model,
stopReason: data.stop_reason,
usage: {
inputTokens: data.usage.input_tokens,
outputTokens: data.usage.output_tokens,
},
};
}
async fetchUsage(): Promise<UsageOutput> {
const auth = await this.authService.getValidAccessToken();
const usageUrl = getGatewayUsageUrl(auth.apiHost);
log.debug("Fetching usage from gateway", { url: usageUrl });
const response = await this.authService.authenticatedFetch(
net.fetch,
usageUrl,
);
if (!response.ok) {
throw new LlmGatewayError(
`Failed to fetch usage: HTTP ${response.status}`,
"usage_error",
undefined,
response.status,
);
}
return (await response.json()) as UsageOutput;
}
}