Skip to content

Commit b5e1e4a

Browse files
chore(internal): move client class to separate file (#408)
1 parent 0c1eb5d commit b5e1e4a

File tree

2 files changed

+247
-239
lines changed

2 files changed

+247
-239
lines changed

src/client.ts

Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2+
3+
import * as Core from './core';
4+
import * as Errors from './error';
5+
import { type Agent } from './_shims/index';
6+
import * as Uploads from './uploads';
7+
import * as API from '@anthropic-ai/sdk/resources/index';
8+
9+
export interface ClientOptions {
10+
/**
11+
* Defaults to process.env['ANTHROPIC_API_KEY'].
12+
*/
13+
apiKey?: string | null | undefined;
14+
15+
/**
16+
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
17+
*/
18+
authToken?: string | null | undefined;
19+
20+
/**
21+
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
22+
*
23+
* Defaults to process.env['ANTHROPIC_BASE_URL'].
24+
*/
25+
baseURL?: string | null | undefined;
26+
27+
/**
28+
* The maximum amount of time (in milliseconds) that the client should wait for a response
29+
* from the server before timing out a single request.
30+
*
31+
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
32+
* much longer than this timeout before the promise succeeds or fails.
33+
*/
34+
timeout?: number;
35+
36+
/**
37+
* An HTTP agent used to manage HTTP(S) connections.
38+
*
39+
* If not provided, an agent will be constructed by default in the Node.js environment,
40+
* otherwise no agent is used.
41+
*/
42+
httpAgent?: Agent;
43+
44+
/**
45+
* Specify a custom `fetch` function implementation.
46+
*
47+
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
48+
* defined globally.
49+
*/
50+
fetch?: Core.Fetch | undefined;
51+
52+
/**
53+
* The maximum number of times that the client will retry a request in case of a
54+
* temporary failure, like a network error or a 5XX error from the server.
55+
*
56+
* @default 2
57+
*/
58+
maxRetries?: number;
59+
60+
/**
61+
* Default headers to include with every request to the API.
62+
*
63+
* These can be removed in individual requests by explicitly setting the
64+
* header to `undefined` or `null` in request options.
65+
*/
66+
defaultHeaders?: Core.Headers;
67+
68+
/**
69+
* Default query parameters to include with every request to the API.
70+
*
71+
* These can be removed in individual requests by explicitly setting the
72+
* param to `undefined` in request options.
73+
*/
74+
defaultQuery?: Core.DefaultQuery;
75+
}
76+
77+
/** API Client for interfacing with the Anthropic API. */
78+
export class Anthropic extends Core.APIClient {
79+
apiKey: string | null;
80+
authToken: string | null;
81+
82+
private _options: ClientOptions;
83+
84+
/**
85+
* API Client for interfacing with the Anthropic API.
86+
*
87+
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
88+
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
89+
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
90+
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
91+
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
92+
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
93+
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
94+
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
95+
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
96+
*/
97+
constructor({
98+
baseURL = Core.readEnv('ANTHROPIC_BASE_URL'),
99+
apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null,
100+
authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,
101+
...opts
102+
}: ClientOptions = {}) {
103+
const options: ClientOptions = {
104+
apiKey,
105+
authToken,
106+
...opts,
107+
baseURL: baseURL || `https://api.anthropic.com`,
108+
};
109+
110+
super({
111+
baseURL: options.baseURL!,
112+
timeout: options.timeout ?? 600000 /* 10 minutes */,
113+
httpAgent: options.httpAgent,
114+
maxRetries: options.maxRetries,
115+
fetch: options.fetch,
116+
});
117+
this._options = options;
118+
119+
this.apiKey = apiKey;
120+
this.authToken = authToken;
121+
}
122+
123+
completions: API.Completions = new API.Completions(this);
124+
messages: API.Messages = new API.Messages(this);
125+
beta: API.Beta = new API.Beta(this);
126+
127+
protected override defaultQuery(): Core.DefaultQuery | undefined {
128+
return this._options.defaultQuery;
129+
}
130+
131+
protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
132+
return {
133+
...super.defaultHeaders(opts),
134+
'anthropic-version': '2023-06-01',
135+
...this._options.defaultHeaders,
136+
};
137+
}
138+
139+
protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {
140+
if (this.apiKey && headers['x-api-key']) {
141+
return;
142+
}
143+
if (customHeaders['x-api-key'] === null) {
144+
return;
145+
}
146+
147+
if (this.authToken && headers['authorization']) {
148+
return;
149+
}
150+
if (customHeaders['authorization'] === null) {
151+
return;
152+
}
153+
154+
throw new Error(
155+
'Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted',
156+
);
157+
}
158+
159+
protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
160+
const apiKeyAuth = this.apiKeyAuth(opts);
161+
const bearerAuth = this.bearerAuth(opts);
162+
163+
if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
164+
return apiKeyAuth;
165+
}
166+
167+
if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
168+
return bearerAuth;
169+
}
170+
return {};
171+
}
172+
173+
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
174+
if (this.apiKey == null) {
175+
return {};
176+
}
177+
return { 'X-Api-Key': this.apiKey };
178+
}
179+
180+
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers {
181+
if (this.authToken == null) {
182+
return {};
183+
}
184+
return { Authorization: `Bearer ${this.authToken}` };
185+
}
186+
187+
static Anthropic = this;
188+
static HUMAN_PROMPT = '\n\nHuman:';
189+
static AI_PROMPT = '\n\nAssistant:';
190+
191+
static AnthropicError = Errors.AnthropicError;
192+
static APIError = Errors.APIError;
193+
static APIConnectionError = Errors.APIConnectionError;
194+
static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
195+
static APIUserAbortError = Errors.APIUserAbortError;
196+
static NotFoundError = Errors.NotFoundError;
197+
static ConflictError = Errors.ConflictError;
198+
static RateLimitError = Errors.RateLimitError;
199+
static BadRequestError = Errors.BadRequestError;
200+
static AuthenticationError = Errors.AuthenticationError;
201+
static InternalServerError = Errors.InternalServerError;
202+
static PermissionDeniedError = Errors.PermissionDeniedError;
203+
static UnprocessableEntityError = Errors.UnprocessableEntityError;
204+
205+
static toFile = Uploads.toFile;
206+
static fileFromPath = Uploads.fileFromPath;
207+
}
208+
209+
export namespace Anthropic {
210+
export import RequestOptions = Core.RequestOptions;
211+
212+
export import Completions = API.Completions;
213+
export import Completion = API.Completion;
214+
export import CompletionCreateParams = API.CompletionCreateParams;
215+
export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming;
216+
export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming;
217+
218+
export import Messages = API.Messages;
219+
export import ContentBlock = API.ContentBlock;
220+
export import ContentBlockDeltaEvent = API.ContentBlockDeltaEvent;
221+
export import ContentBlockStartEvent = API.ContentBlockStartEvent;
222+
export import ContentBlockStopEvent = API.ContentBlockStopEvent;
223+
export import ImageBlockParam = API.ImageBlockParam;
224+
export import Message = API.Message;
225+
export import MessageDeltaEvent = API.MessageDeltaEvent;
226+
export import MessageDeltaUsage = API.MessageDeltaUsage;
227+
export import MessageParam = API.MessageParam;
228+
export import MessageStartEvent = API.MessageStartEvent;
229+
export import MessageStopEvent = API.MessageStopEvent;
230+
export import MessageStreamEvent = API.MessageStreamEvent;
231+
export import TextBlock = API.TextBlock;
232+
export import TextBlockParam = API.TextBlockParam;
233+
export import TextDelta = API.TextDelta;
234+
export import Usage = API.Usage;
235+
export import MessageCreateParams = API.MessageCreateParams;
236+
export import MessageCreateParamsNonStreaming = API.MessageCreateParamsNonStreaming;
237+
export import MessageCreateParamsStreaming = API.MessageCreateParamsStreaming;
238+
export import MessageStreamParams = API.MessageStreamParams;
239+
240+
export import Beta = API.Beta;
241+
}

0 commit comments

Comments
 (0)