-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.ts
More file actions
138 lines (119 loc) · 3.56 KB
/
api.ts
File metadata and controls
138 lines (119 loc) · 3.56 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
const debug = require('debug')('agentops:api');
// Request schema for /v3/auth/token endpoint
export interface TokenSchema {
api_key: string;
}
// Response schema for /v3/auth/token endpoint
export interface TokenResponse {
token: string;
project_id: string;
project_prem_status: string;
}
// Verify token response schema
export interface VerifyTokenResponse {
message: string;
payload: Record<string, any>;
expires_at: string;
}
export class BearerToken {
constructor(private token: string) {}
getToken(): string {
return this.token;
}
getAuthHeader(): string {
return `Bearer ${this.token}`;
}
}
export class API {
private bearerToken: BearerToken | null = null;
/**
* Creates a new API client instance.
*
* @param apiKey - The API key for authentication
* @param endpoint - The base endpoint URL for the API
*/
constructor(private apiKey: string, private endpoint: string) {}
/**
* Get the user agent string for API requests
*/
private get userAgent(): string {
return `agentops-ts-sdk/${process.env.npm_package_version || 'unknown'}`;
}
/**
* Set the bearer token for authenticated requests
*/
setBearerToken(token: BearerToken): void {
this.bearerToken = token;
}
/**
* Fetch data from the API using the specified path and method.
*
* @param path - The API endpoint path
* @param method - The HTTP method to use (GET or POST)
* @param body - The request body for POST requests
* @param headers - Additional headers to include in the request
* @returns The parsed JSON response
*/
private async fetch<T>(
path: string,
method: 'GET' | 'POST',
body?: any,
headers?: Record<string, string>
): Promise<T> {
const url = `${this.endpoint}${path}`;
const defaultHeaders: Record<string, string> = {
'User-Agent': this.userAgent,
'Content-Type': 'application/json',
};
// Add authorization header if bearer token is available
if (this.bearerToken) {
defaultHeaders['Authorization'] = this.bearerToken.getAuthHeader();
}
// Merge with additional headers
const finalHeaders = { ...defaultHeaders, ...headers };
const response = await fetch(url, {
method: method,
headers: finalHeaders,
body: body ? JSON.stringify(body) : undefined
});
if (!response.ok) {
let errorMessage = `Request failed: ${response.status} ${response.statusText}`;
try {
const errorData = await response.json();
if (errorData.error) {
errorMessage = errorData.error;
}
} catch {
// Ignore JSON parsing errors
}
throw new Error(errorMessage);
}
return await response.json() as T;
}
/**
* Authenticate with the AgentOps API using the provided API key.
*
* @returns A promise that resolves to a TokenResponse containing the authentication token
*/
async authenticate(): Promise<TokenResponse> {
return this.fetch<TokenResponse>('/v3/auth/token', 'POST', { api_key: this.apiKey });
}
/**
* Upload log content to the API.
*
* @param logContent - The log content to upload
* @param traceId - The trace ID to associate with the logs
* @returns A promise that resolves when the upload is complete
*/
async uploadLogFile(logContent: string, traceId: string): Promise<{ id: string }> {
if (!this.bearerToken) {
throw new Error('Authentication required. Bearer token not set.');
}
return this.fetch<{ id: string }>(
'/v4/logs/upload/',
'POST',
logContent,
{ 'Trace-Id': traceId }
);
}
}