Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: unreleased changes #45

Merged
merged 3 commits into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.5.2"
".": "0.5.3"
}
22 changes: 19 additions & 3 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export {

const MAX_RETRIES = 2;

type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;

export abstract class APIClient {
baseURL: string;
Expand All @@ -37,18 +37,20 @@ export abstract class APIClient {
maxRetries,
timeout = 60 * 1000, // 60s
httpAgent,
fetch: overridenFetch,
}: {
baseURL: string;
maxRetries?: number | undefined;
timeout: number | undefined;
httpAgent: Agent | undefined;
fetch: Fetch | undefined;
}) {
this.baseURL = baseURL;
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries ?? MAX_RETRIES);
this.timeout = validatePositiveInteger('timeout', timeout);
this.httpAgent = httpAgent;

this.fetch = fetch;
this.fetch = overridenFetch ?? fetch;
}

protected authHeaders(): Headers {
Expand Down Expand Up @@ -120,6 +122,20 @@ export abstract class APIClient {
return this.requestAPIList(Page, { method: 'get', path, ...opts });
}

private calculateContentLength(body: unknown): string | null {
if (typeof body === 'string') {
if (typeof Buffer !== 'undefined') {
return Buffer.byteLength(body, 'utf8').toString();
}

const encoder = new TextEncoder();
const encoded = encoder.encode(body);
return encoded.length.toString();
}

return null;
}

buildRequest<Req extends {}>(
options: FinalRequestOptions<Req>,
): { req: RequestInit; url: string; timeout: number } {
Expand All @@ -129,7 +145,7 @@ export abstract class APIClient {
isMultipartBody(options.body) ? options.body.body
: options.body ? JSON.stringify(options.body, null, 2)
: null;
const contentLength = typeof body === 'string' ? body.length.toString() : null;
const contentLength = this.calculateContentLength(body);

const url = this.buildURL(path!, query);
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
Expand Down
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ type Config = {
*/
httpAgent?: Agent;

/**
* Specify a custom `fetch` function implementation.
*
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
* defined globally.
*/
fetch?: Core.Fetch | undefined;

/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
Expand Down Expand Up @@ -81,6 +89,7 @@ export class Anthropic extends Core.APIClient {
timeout: options.timeout,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
fetch: options.fetch,
});
this.apiKey = options.apiKey || null;
this._options = options;
Expand Down
16 changes: 12 additions & 4 deletions src/streaming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,19 +259,27 @@ function partition(str: string, delimiter: string): [string, string, string] {
* Most browsers don't yet have async iterable support for ReadableStream,
* and Node has a very different way of reading bytes from its "ReadableStream".
*
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1624185965
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
*/
function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {
if (stream[Symbol.asyncIterator]) return stream;

const reader = stream.getReader();
return {
next() {
return reader.read();
async next() {
try {
const result = await reader.read();
if (result?.done) reader.releaseLock(); // release lock when stream becomes closed
return result;
} catch (e) {
reader.releaseLock(); // release lock when stream becomes errored
throw e;
}
},
async return() {
reader.cancel();
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
return { done: true, value: undefined };
},
[Symbol.asyncIterator]() {
Expand Down
34 changes: 34 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { Headers } from '@anthropic-ai/sdk/core';
import Anthropic from '@anthropic-ai/sdk';
import { Response } from '@anthropic-ai/sdk/_shims/fetch';

describe('instantiate client', () => {
const env = process.env;
Expand Down Expand Up @@ -77,6 +78,23 @@ describe('instantiate client', () => {
});
});

test('custom fetch', async () => {
const client = new Anthropic({
baseURL: 'http://localhost:5000/',
apiKey: 'my api key',
fetch: (url) => {
return Promise.resolve(
new Response(JSON.stringify({ url, custom: true }), {
headers: { 'Content-Type': 'application/json' },
}),
);
},
});

const response = await client.get('/foo');
expect(response).toEqual({ url: 'http://localhost:5000/foo', custom: true });
});

describe('baseUrl', () => {
test('trailing slash', () => {
const client = new Anthropic({ baseURL: 'http://localhost:5000/custom/path/', apiKey: 'my api key' });
Expand Down Expand Up @@ -126,3 +144,19 @@ describe('instantiate client', () => {
expect(client.apiKey).toBeNull();
});
});

describe('request building', () => {
const client = new Anthropic({ apiKey: 'my api key' });

describe('Content-Length', () => {
test('handles multi-byte characters', () => {
const { req } = client.buildRequest({ path: '/foo', method: 'post', body: { value: '—' } });
expect((req.headers as Record<string, string>)['Content-Length']).toEqual('20');
});

test('handles standard characters', () => {
const { req } = client.buildRequest({ path: '/foo', method: 'post', body: { value: 'hello' } });
expect((req.headers as Record<string, string>)['Content-Length']).toEqual('22');
});
});
});