-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopik-client.ts
More file actions
327 lines (279 loc) · 12.1 KB
/
Copy pathopik-client.ts
File metadata and controls
327 lines (279 loc) · 12.1 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import axios, { AxiosInstance, AxiosError } from 'axios';
import { OpikConfig, OpikSpan, OpikTrace } from '../types';
import { createLogger } from '../utils/logger';
export interface OpikCreateTracesRequest {
traces: OpikTrace[];
}
export interface OpikCreateTracesResponse {
traces?: Array<{
id: string;
project_id?: string;
}>;
[key: string]: any; // Allow additional properties
}
export interface OpikCreateSpansRequest {
spans: OpikSpan[];
}
export interface OpikCreateSpansResponse {
spans?: Array<{
id: string;
project_id?: string;
}>;
}
export class OpikApiClient {
private client: AxiosInstance;
private config: OpikConfig;
private logger: ReturnType<typeof createLogger>;
constructor(config: OpikConfig) {
this.config = config;
this.logger = createLogger({ verbose: false });
// Normalize the base URL - remove trailing /api/ if present since we'll add the full path
let baseURL = config.base_url;
if (baseURL.endsWith('/api/')) {
baseURL = baseURL.slice(0, -5); // Remove '/api/'
} else if (baseURL.endsWith('/api')) {
baseURL = baseURL.slice(0, -4); // Remove '/api'
}
this.client = axios.create({
baseURL: baseURL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
...(config.api_key && { 'authorization': config.api_key }),
...(config.workspace && { 'Comet-Workspace': config.workspace })
},
timeout: 30000 // 30 second timeout
});
this.logger.debug(`Opik API client configured with base URL: ${baseURL}`);
}
async createTraces(traces: OpikTrace[]): Promise<OpikCreateTracesResponse> {
// Don't call API if there are no traces to create
if (traces.length === 0) {
return { traces: [] };
}
const request: OpikCreateTracesRequest = { traces };
try {
this.logger.debug(`Sending ${traces.length} traces to Opik at ${this.config.base_url}`);
const response = await this.client.post<OpikCreateTracesResponse>(
'/api/v1/private/traces/batch',
request
);
this.logger.debug(`Status Code: ${response.status}`);
this.logger.debug(`API Response:`, response.data);
this.logger.debug(`Successfully created ${response.data?.traces?.length || 'unknown number of'} traces`);
return response.data;
} catch (error) {
if (error instanceof AxiosError) {
// If workspace doesn't exist, try with "default"
if (error.response?.status === 403 &&
error.response?.data?.message?.includes('Workspace') &&
this.config.workspace !== 'default') {
this.logger.warning(`Workspace '${this.config.workspace}' not found, trying 'default'`);
// Create a new client with default workspace
const defaultClient = axios.create({
...this.client.defaults,
headers: {
...this.client.defaults.headers,
'Comet-Workspace': 'default'
}
});
try {
const response = await defaultClient.post<OpikCreateTracesResponse>(
'/api/v1/private/traces/batch',
request
);
this.logger.debug(`Fallback Status Code: ${response.status}`);
this.logger.debug(`Fallback API Response:`, response.data);
this.logger.debug(`Successfully created ${response.data?.traces?.length || 'unknown number of'} traces in default workspace`);
return response.data;
} catch (fallbackError) {
this.logger.error(`Fallback to default workspace also failed`);
}
}
this.logger.debug(`Request details:`, {
url: error.config?.url,
method: error.config?.method,
baseURL: error.config?.baseURL,
headers: error.config?.headers
});
const status = error.response?.status || 'no response';
const statusText = error.response?.statusText || 'unknown error';
const errorMsg = `Failed to create traces: ${status} ${statusText}`;
const errorDetails = error.response?.data ? JSON.stringify(error.response.data, null, 2) : error.message;
throw new Error(`${errorMsg}\nDetails: ${errorDetails}`);
}
throw new Error(`Unexpected error creating traces: ${error instanceof Error ? error.message : error}`);
}
}
async createSpans(spans: OpikSpan[]): Promise<OpikCreateSpansResponse> {
// Don't call API if there are no spans to create
if (spans.length === 0) {
return { spans: [] };
}
const limit = 1000; // Opik API prohibits more than 1000 spans at a time
const chunks = [...Array(Math.ceil(spans.length / limit))].map(_ => spans.splice(0, limit));
const response: OpikCreateSpansResponse = { spans: [] };
for (const chunkSpans of chunks) {
const request: OpikCreateSpansRequest = { spans: chunkSpans };
try {
this.logger.debug(`Sending ${chunkSpans.length} spans to Opik at ${this.config.base_url}`);
const chunkResponse = await this.client.post<OpikCreateSpansResponse>(
'/api/v1/private/spans/batch',
request
);
this.logger.debug(`Status Code: ${chunkResponse.status}`);
this.logger.debug(`API Response:`, chunkResponse.data);
this.logger.debug(`Successfully created ${chunkResponse.data?.spans?.length || 'unknown number of'} spans`);
response.spans?.push(...(chunkResponse.data.spans ?? []));
} catch (error) {
if (error instanceof AxiosError) {
// If workspace doesn't exist, try with "default"
if (error.response?.status === 403 &&
error.response?.data?.message?.includes('Workspace') &&
this.config.workspace !== 'default') {
this.logger.warning(`Workspace '${this.config.workspace}' not found, trying 'default'`);
// Create a new client with default workspace
const defaultClient = axios.create({
...this.client.defaults,
headers: {
...this.client.defaults.headers,
'Comet-Workspace': 'default'
}
});
try {
const chunkResponse = await defaultClient.post<OpikCreateSpansResponse>(
'/api/v1/private/spans/batch',
request
);
this.logger.debug(`Fallback Status Code: ${chunkResponse.status}`);
this.logger.debug(`Fallback API Response:`, chunkResponse.data);
this.logger.debug(`Successfully created ${chunkResponse.data?.spans?.length || 'unknown number of'} spans in default workspace`);
response.spans?.push(...(chunkResponse.data.spans ?? []));
} catch (fallbackError) {
this.logger.error(`Fallback to default workspace also failed`);
}
}
this.logger.debug(`Request details:`, {
url: error.config?.url,
method: error.config?.method,
baseURL: error.config?.baseURL,
headers: error.config?.headers
});
const status = error.response?.status || 'no response';
const statusText = error.response?.statusText || 'unknown error';
const errorMsg = `Failed to create spans: ${status} ${statusText}`;
const errorDetails = error.response?.data ? JSON.stringify(error.response.data, null, 2) : error.message;
throw new Error(`${errorMsg}\nDetails: ${errorDetails}`);
}
throw new Error(`Unexpected error creating spans: ${error instanceof Error ? error.message : error}`);
}
}
return response;
}
async testConnection(): Promise<boolean> {
try {
// Test with empty traces array to validate connection
await this.client.post('/api/v1/private/traces/batch', { traces: [] });
this.logger.debug(`Successfully connected to Opik at ${this.config.base_url}`);
return true;
} catch (error) {
if (error instanceof AxiosError) {
this.logger.error(`Failed to connect to Opik: ${error.response?.status} ${error.response?.statusText}`);
if (error.response?.data) {
this.logger.debug('Response details:', JSON.stringify(error.response.data, null, 2));
}
} else {
this.logger.error(`Unexpected connection error: ${error instanceof Error ? error.message : error}`);
}
return false;
}
}
async createSingleTrace(trace: OpikTrace): Promise<string> {
const response = await this.createTraces([trace]);
if (!response.traces || response.traces.length === 0) {
throw new Error('No trace ID returned from API');
}
return response.traces[0].id;
}
async updateTrace(traceId: string, trace: Partial<OpikTrace>): Promise<void> {
try {
this.logger.debug(`Updating trace ${traceId} in Opik`);
const response = await this.client.patch<void>(
`/api/v1/private/traces/${traceId}`,
trace
);
this.logger.debug(`Update Status Code: ${response.status}`);
this.logger.debug(`Successfully updated trace ${traceId}`);
} catch (error) {
if (error instanceof AxiosError) {
this.logger.debug(`Update request details:`, {
url: error.config?.url,
method: error.config?.method,
baseURL: error.config?.baseURL,
headers: error.config?.headers
});
const status = error.response?.status || 'no response';
const statusText = error.response?.statusText || 'unknown error';
const errorMsg = `Failed to update trace ${traceId}: ${status} ${statusText}`;
const errorDetails = error.response?.data ? JSON.stringify(error.response.data, null, 2) : error.message;
throw new Error(`${errorMsg}\nDetails: ${errorDetails}`);
}
throw new Error(`Unexpected error updating trace ${traceId}: ${error instanceof Error ? error.message : error}`);
}
}
async updateThreadTags(threadId: string, tags: string[]): Promise<void> {
try {
// First, get the thread_model_id by searching for the thread
const searchEndpoint = `/api/v1/private/traces/threads`;
const searchParams = new URLSearchParams({
project_name: 'Claude Code',
filters: JSON.stringify([{
id: 'thread_id_filter',
field: 'id',
type: 'string',
operator: 'contains',
key: '',
value: threadId
}]),
sorting: JSON.stringify([{
field: 'last_updated_at',
direction: 'DESC'
}]),
size: '1',
page: '1',
truncate: 'true'
});
const searchResponse = await this.client.get(`${searchEndpoint}?${searchParams}`);
if (!searchResponse.data?.content?.[0]?.thread_model_id) {
throw new Error(`Thread ${threadId} not found or no thread_model_id available`);
}
const threadModelId = searchResponse.data.content[0].thread_model_id;
// Now update the thread tags using the thread_model_id
const updateEndpoint = `/api/v1/private/traces/threads/${threadModelId}`;
const payload = { tags };
await this.client.patch<void>(updateEndpoint, payload);
} catch (error) {
if (error instanceof AxiosError) {
this.logger.error(`Thread tags update request details: ${JSON.stringify({
url: error.config?.url,
method: error.config?.method,
baseURL: error.config?.baseURL,
headers: error.config?.headers,
data: error.config?.data
})}`);
const status = error.response?.status || 'no response';
const statusText = error.response?.statusText || 'unknown error';
const errorMsg = `Failed to update thread ${threadId} tags: ${status} ${statusText}`;
const errorDetails = error.response?.data ? JSON.stringify(error.response.data, null, 2) : error.message;
throw new Error(`${errorMsg}\nDetails: ${errorDetails}`);
}
throw new Error(`Unexpected error updating thread ${threadId} tags: ${error instanceof Error ? error.message : error}`);
}
}
getConfig(): OpikConfig {
return { ...this.config };
}
}
export function createOpikClient(config: OpikConfig): OpikApiClient {
return new OpikApiClient(config);
}