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

feat(client): support results endpoint #666

Merged
merged 1 commit into from
Jan 21, 2025
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 .stats.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
configured_endpoints: 21
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic-fd67aea6883f1ee9e46f31a42d3940f0acb1749e787055bd9b9f278b20fa53ec.yml
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic-75f0573c3d6d79650bcbd8b1b4fcf93ce146d567afeb1061cd4afccf8d1d6799.yml
4 changes: 2 additions & 2 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Methods:
- <code title="get /v1/messages/batches">client.messages.batches.<a href="./src/resources/messages/batches.ts">list</a>({ ...params }) -> MessageBatchesPage</code>
- <code title="delete /v1/messages/batches/{message_batch_id}">client.messages.batches.<a href="./src/resources/messages/batches.ts">delete</a>(messageBatchId) -> DeletedMessageBatch</code>
- <code title="post /v1/messages/batches/{message_batch_id}/cancel">client.messages.batches.<a href="./src/resources/messages/batches.ts">cancel</a>(messageBatchId) -> MessageBatch</code>
- <code title="get /v1/messages/batches/{message_batch_id}/results">client.messages.batches.<a href="./src/resources/messages/batches.ts">results</a>(messageBatchId) -> Response</code>
- <code title="get /v1/messages/batches/{message_batch_id}/results">client.messages.batches.<a href="./src/resources/messages/batches.ts">results</a>(messageBatchId) -> JSONLDecoder&lt;MessageBatchIndividualResponse&gt;</code>

# Models

Expand Down Expand Up @@ -191,4 +191,4 @@ Methods:
- <code title="get /v1/messages/batches?beta=true">client.beta.messages.batches.<a href="./src/resources/beta/messages/batches.ts">list</a>({ ...params }) -> BetaMessageBatchesPage</code>
- <code title="delete /v1/messages/batches/{message_batch_id}?beta=true">client.beta.messages.batches.<a href="./src/resources/beta/messages/batches.ts">delete</a>(messageBatchId, { ...params }) -> BetaDeletedMessageBatch</code>
- <code title="post /v1/messages/batches/{message_batch_id}/cancel?beta=true">client.beta.messages.batches.<a href="./src/resources/beta/messages/batches.ts">cancel</a>(messageBatchId, { ...params }) -> BetaMessageBatch</code>
- <code title="get /v1/messages/batches/{message_batch_id}/results?beta=true">client.beta.messages.batches.<a href="./src/resources/beta/messages/batches.ts">results</a>(messageBatchId, { ...params }) -> Response</code>
- <code title="get /v1/messages/batches/{message_batch_id}/results?beta=true">client.beta.messages.batches.<a href="./src/resources/beta/messages/batches.ts">results</a>(messageBatchId, { ...params }) -> JSONLDecoder&lt;BetaMessageBatchIndividualResponse&gt;</code>
41 changes: 41 additions & 0 deletions src/internal/decoders/jsonl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { AnthropicError } from '../../error';
import { ReadableStreamToAsyncIterable } from '../stream-utils';
import { type Response } from '../../_shims/index';
import { LineDecoder, type Bytes } from './line';

export class JSONLDecoder<T> {
controller: AbortController;

constructor(
private iterator: AsyncIterableIterator<Bytes>,
controller: AbortController,
) {
this.controller = controller;
}

private async *decoder(): AsyncIterator<T, any, undefined> {
const lineDecoder = new LineDecoder();
for await (const chunk of this.iterator) {
for (const line of lineDecoder.decode(chunk)) {
yield JSON.parse(line);
}
}

for (const line of lineDecoder.flush()) {
yield JSON.parse(line);
}
}

[Symbol.asyncIterator](): AsyncIterator<T> {
return this.decoder();
}

static fromResponse<T>(response: Response, controller: AbortController): JSONLDecoder<T> {
if (!response.body) {
controller.abort();
throw new AnthropicError(`Attempted to iterate over a response with no body`);
}

return new JSONLDecoder(ReadableStreamToAsyncIterable<Bytes>(response.body), controller);
}
}
31 changes: 18 additions & 13 deletions src/resources/beta/messages/batches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as BetaAPI from '../beta';
import * as MessagesAPI from '../../messages/messages';
import * as MessagesMessagesAPI from './messages';
import { Page, type PageParams } from '../../../pagination';
import { type Response } from '../../../_shims/index';
import { JSONLDecoder } from '../../../internal/decoders/jsonl';

export class Batches extends APIResource {
/**
Expand Down Expand Up @@ -160,26 +160,31 @@ export class Batches extends APIResource {
messageBatchId: string,
params?: BatchResultsParams,
options?: Core.RequestOptions,
): Core.APIPromise<Response>;
results(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<Response>;
): Core.APIPromise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
results(
messageBatchId: string,
options?: Core.RequestOptions,
): Core.APIPromise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
results(
messageBatchId: string,
params: BatchResultsParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.APIPromise<Response> {
): Core.APIPromise<JSONLDecoder<BetaMessageBatchIndividualResponse>> {
if (isRequestOptions(params)) {
return this.results(messageBatchId, {}, params);
}
const { betas } = params;
return this._client.get(`/v1/messages/batches/${messageBatchId}/results?beta=true`, {
...options,
headers: {
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
Accept: 'application/binary',
...options?.headers,
},
__binaryResponse: true,
});
return this._client
.get(`/v1/messages/batches/${messageBatchId}/results?beta=true`, {
...options,
headers: {
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
Accept: 'application/x-jsonl',
...options?.headers,
},
__binaryResponse: true,
})
._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
}
}

Expand Down
19 changes: 12 additions & 7 deletions src/resources/messages/batches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as Core from '../../core';
import * as Shared from '../shared';
import * as MessagesAPI from './messages';
import { Page, type PageParams } from '../../pagination';
import { type Response } from '../../_shims/index';
import { JSONLDecoder } from '../../internal/decoders/jsonl';

export class Batches extends APIResource {
/**
Expand Down Expand Up @@ -79,12 +79,17 @@ export class Batches extends APIResource {
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*/
results(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<Response> {
return this._client.get(`/v1/messages/batches/${messageBatchId}/results`, {
...options,
headers: { Accept: 'application/binary', ...options?.headers },
__binaryResponse: true,
});
results(
messageBatchId: string,
options?: Core.RequestOptions,
): Core.APIPromise<JSONLDecoder<MessageBatchIndividualResponse>> {
return this._client
.get(`/v1/messages/batches/${messageBatchId}/results`, {
...options,
headers: { Accept: 'application/x-jsonl', ...options?.headers },
__binaryResponse: true,
})
._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
}
}

Expand Down
18 changes: 16 additions & 2 deletions tests/api-resources/beta/messages/batches.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,28 @@ describe('resource batches', () => {
).rejects.toThrow(Anthropic.NotFoundError);
});

test('results: request options instead of params are passed correctly', async () => {
// Prism doesn't support JSONL responses yet
test.skip('results', async () => {
const responsePromise = client.beta.messages.batches.results('message_batch_id');
const rawResponse = await responsePromise.asResponse();
expect(rawResponse).toBeInstanceOf(Response);
const response = await responsePromise;
expect(response).not.toBeInstanceOf(Response);
const dataAndResponse = await responsePromise.withResponse();
expect(dataAndResponse.data).toBe(response);
expect(dataAndResponse.response).toBe(rawResponse);
});

// Prism doesn't support JSONL responses yet
test.skip('results: request options instead of params are passed correctly', async () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.beta.messages.batches.results('message_batch_id', { path: '/_stainless_unknown_path' }),
).rejects.toThrow(Anthropic.NotFoundError);
});

test('results: request options and params are passed correctly', async () => {
// Prism doesn't support JSONL responses yet
test.skip('results: request options and params are passed correctly', async () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.beta.messages.batches.results(
Expand Down
15 changes: 14 additions & 1 deletion tests/api-resources/messages/batches.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,20 @@ describe('resource batches', () => {
).rejects.toThrow(Anthropic.NotFoundError);
});

test('results: request options instead of params are passed correctly', async () => {
// Prism doesn't support JSONL responses yet
test.skip('results', async () => {
const responsePromise = client.messages.batches.results('message_batch_id');
const rawResponse = await responsePromise.asResponse();
expect(rawResponse).toBeInstanceOf(Response);
const response = await responsePromise;
expect(response).not.toBeInstanceOf(Response);
const dataAndResponse = await responsePromise.withResponse();
expect(dataAndResponse.data).toBe(response);
expect(dataAndResponse.response).toBe(rawResponse);
});

// Prism doesn't support JSONL responses yet
test.skip('results: request options instead of params are passed correctly', async () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.messages.batches.results('message_batch_id', { path: '/_stainless_unknown_path' }),
Expand Down