パッケージの詳細

together-ai

togethercomputer82.4kApache-2.00.17.0

The official TypeScript library for the Together API

readme

Together Node API Library

NPM version npm bundle size

This library provides convenient access to the Together REST API from server-side TypeScript or JavaScript.

The REST API documentation can be found on docs.together.ai. The full API of this library can be found in api.md.

It is generated with Stainless.

Installation

npm install together-ai

Usage

The full API of this library can be found in api.md.

import Together from 'together-ai';

const client = new Together({
  apiKey: process.env['TOGETHER_API_KEY'], // This is the default and can be omitted
});

const chatCompletion = await client.chat.completions.create({
  messages: [{ role: 'user', content: 'Say this is a test!' }],
  model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
});

console.log(chatCompletion.choices);

Streaming responses

We provide support for streaming responses using Server Sent Events (SSE).

import Together from 'together-ai';

const client = new Together();

const stream = await client.chat.completions.create({
  messages: [{ role: 'user', content: 'Say this is a test' }],
  model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
  stream: true,
});
for await (const chatCompletionChunk of stream) {
  console.log(chatCompletionChunk.choices);
}

If you need to cancel a stream, you can break from the loop or call stream.controller.abort().

Request & Response types

This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:

import Together from 'together-ai';

const client = new Together({
  apiKey: process.env['TOGETHER_API_KEY'], // This is the default and can be omitted
});

const params: Together.Chat.CompletionCreateParams = {
  messages: [{ role: 'user', content: 'Say this is a test' }],
  model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
};
const chatCompletion: Together.Chat.ChatCompletion = await client.chat.completions.create(params);

Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.

File uploads

Request parameters that correspond to file uploads can be passed in many different forms:

  • File (or an object with the same structure)
  • a fetch Response (or an object with the same structure)
  • an fs.ReadStream
  • the return value of our toFile helper
import fs from 'fs';
import fetch from 'node-fetch';
import Together, { toFile } from 'together-ai';

const client = new Together();

// If you have access to Node `fs` we recommend using `fs.createReadStream()`:
await client.files.upload({
  file: fs.createReadStream('/path/to/file'),
  file_name: 'dataset.csv',
  purpose: 'fine-tune',
});

// Or if you have the web `File` API you can pass a `File` instance:
await client.files.upload({
  file: new File(['my bytes'], 'file'),
  file_name: 'dataset.csv',
  purpose: 'fine-tune',
});

// You can also pass a `fetch` `Response`:
await client.files.upload({
  file: await fetch('https://somesite/file'),
  file_name: 'dataset.csv',
  purpose: 'fine-tune',
});

// Finally, if none of the above are convenient, you can use our `toFile` helper:
await client.files.upload({
  file: await toFile(Buffer.from('my bytes'), 'file'),
  file_name: 'dataset.csv',
  purpose: 'fine-tune',
});
await client.files.upload({
  file: await toFile(new Uint8Array([0, 1, 2]), 'file'),
  file_name: 'dataset.csv',
  purpose: 'fine-tune',
});

Handling errors

When the library is unable to connect to the API, or if the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of APIError will be thrown:

const chatCompletion = await client.chat.completions
  .create({
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
  })
  .catch(async (err) => {
    if (err instanceof Together.APIError) {
      console.log(err.status); // 400
      console.log(err.name); // BadRequestError
      console.log(err.headers); // {server: 'nginx', ...}
    } else {
      throw err;
    }
  });

Error codes are as follows:

Status Code Error Type
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
>=500 InternalServerError
N/A APIConnectionError

Retries

Certain errors will be automatically retried 5 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors will all be retried by default.

You can use the maxRetries option to configure or disable this:

// Configure the default for all requests:
const client = new Together({
  maxRetries: 0, // default is 2
});

// Or, configure per-request:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'mistralai/Mixtral-8x7B-Instruct-v0.1' }, {
  maxRetries: 5,
});

Timeouts

Requests time out after 1 minute by default. You can configure this with a timeout option:

// Configure the default for all requests:
const client = new Together({
  timeout: 20 * 1000, // 20 seconds (default is 1 minute)
});

// Override per-request:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'mistralai/Mixtral-8x7B-Instruct-v0.1' }, {
  timeout: 5 * 1000,
});

On timeout, an APIConnectionTimeoutError is thrown.

Note that requests which time out will be retried twice by default.

Advanced Usage

Accessing raw Response data (e.g., headers)

The "raw" Response returned by fetch() can be accessed through the .asResponse() method on the APIPromise type that all methods return.

You can also use the .withResponse() method to get the raw Response along with the parsed data.

const client = new Together();

const response = await client.chat.completions
  .create({
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
  })
  .asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object

const { data: chatCompletion, response: raw } = await client.chat.completions
  .create({
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
  })
  .withResponse();
console.log(raw.headers.get('X-My-Header'));
console.log(chatCompletion.choices);

Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.get, client.post, and other HTTP verbs. Options on the client, such as retries, will be respected when making these requests.

await client.post('/some/path', {
  body: { some_prop: 'foo' },
  query: { some_query_arg: 'bar' },
});

Undocumented request params

To make requests using undocumented parameters, you may use // @ts-expect-error on the undocumented parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you send will be sent as-is.

client.foo.create({
  foo: 'my_param',
  bar: 12,
  // @ts-expect-error baz is not yet public
  baz: 'undocumented option',
});

For requests with the GET verb, any extra params will be in the query, all other requests will send the extra param in the body.

If you want to explicitly send an extra argument, you can do so with the query, body, and headers request options.

Undocumented response properties

To access undocumented response properties, you may access the response object with // @ts-expect-error on the response object, or cast the response object to the requisite type. Like the request params, we do not validate or strip extra properties from the response from the API.

Customizing the fetch client

By default, this library uses node-fetch in Node, and expects a global fetch function in other environments.

If you would prefer to use a global, web-standards-compliant fetch function even in a Node environment, (for example, if you are running Node with --experimental-fetch or using NextJS which polyfills with undici), add the following import before your first import from "Together":

// Tell TypeScript and the package to use the global web fetch instead of node-fetch.
// Note, despite the name, this does not add any polyfills, but expects them to be provided if needed.
import 'together-ai/shims/web';
import Together from 'together-ai';

To do the inverse, add import "together-ai/shims/node" (which does import polyfills). This can also be useful if you are getting the wrong TypeScript types for Response (more details).

Logging and middleware

You may also provide a custom fetch function when instantiating the client, which can be used to inspect or alter the Request or Response before/after each request:

import { fetch } from 'undici'; // as one example
import Together from 'together-ai';

const client = new Together({
  fetch: async (url: RequestInfo, init?: RequestInit): Promise<Response> => {
    console.log('About to make a request', url, init);
    const response = await fetch(url, init);
    console.log('Got response', response);
    return response;
  },
});

Note that if given a DEBUG=true environment variable, this library will log all requests and responses automatically. This is intended for debugging purposes only and may change in the future without notice.

Configuring an HTTP(S) Agent (e.g., for proxies)

By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests.

If you would like to disable or customize this behavior, for example to use the API behind a proxy, you can pass an httpAgent which is used for all requests (be they http or https), for example:

import http from 'http';
import { HttpsProxyAgent } from 'https-proxy-agent';

// Configure the default for all requests:
const client = new Together({
  httpAgent: new HttpsProxyAgent(process.env.PROXY_URL),
});

// Override per-request:
await client.chat.completions.create(
  {
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
  },
  {
    httpAgent: new http.Agent({ keepAlive: false }),
  },
);

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Requirements

TypeScript >= 4.5 is supported.

The following runtimes are supported:

  • Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)
  • Node.js 18 LTS or later (non-EOL) versions.
  • Deno v1.28.0 or higher.
  • Bun 1.0 or later.
  • Cloudflare Workers.
  • Vercel Edge Runtime.
  • Jest 28 or greater with the "node" environment ("jsdom" is not supported at this time).
  • Nitro v2.6 or greater.

Note that React Native is not supported at this time.

If you are interested in other runtime environments, please open or upvote an issue on GitHub.

Contributing

See the contributing documentation.

更新履歴

Changelog

0.17.0 (2025-07-03)

Full Changelog: v0.16.0...v0.17.0

Features

  • api: add batch api to config (6bf62dd)
  • api: Add file_type and file_purpose (f91fb18)
  • api: add files/upload apu support and switch upload_file method over to use it. (5e60c99)
  • api: address diagnostic issues in audio api, correct openapi issue in images api, disambiguate a response in finetune api, enable automated testing on finetune and images (9131477)
  • api: api update (0f63bf1)
  • api: api update (cc8b7a8)
  • api: api update (1df5bbe)
  • api: api update (0b81ef9)
  • api: api update (fd4611d)
  • api: api update (ea28f8f)
  • api: api update (9d7d2f1)
  • api: api update (f52b93d)
  • api: api update (ebf6451)
  • api: api update (e50cdb2)
  • api: api update (158a5c8)
  • api: Formatting fixes, some lint fixes (6b6fc13)
  • api: get test_code_interpreter passing (b67a035)
  • api: update spec / config to remove remaining codegen warnings (1665d1f)
  • api: Update spec and config to get all tests except code-interpolation an fine_tune unit tests working. (1cb0018)
  • client: add support for endpoint-specific base URLs (41abee6)

Bug Fixes

  • ci: release-doctor — report correct token name (38fdf05)
  • client: don't send Content-Type for bodyless methods (4104dc3)
  • publish script — handle NPM errors correctly (78d1a5c)
  • tests: format (82fad3c)
  • tests: remove unused tests (bb90a25)

Chores

  • api: re-enable audio unit tests (5ac5b53)
  • ci: bump node version for release workflows (681d96e)
  • ci: enable for pull requests (b3c7e61)
  • ci: only run for pushes and fork pull requests (448b1fa)
  • docs: grammar improvements (c9d78f6)
  • docs: use top-level-await in example snippets (815f983)
  • improve publish-npm script --latest tag logic (1025321)
  • internal: make base APIResource abstract (d031002)
  • mention unit type in timeout docs (488c92c)

Documentation

Refactors

  • types: replace Record with mapped types (07b8800)

0.16.0 (2025-04-28)

Full Changelog: v0.15.2...v0.16.0

Features

0.15.2 (2025-04-25)

Full Changelog: v0.15.1...v0.15.2

Features

Chores

  • ci: only use depot for staging repos (41fd7ce)
  • ci: run on more branches and use depot runners (c20d3fa)

0.15.1 (2025-04-22)

Full Changelog: v0.15.0...v0.15.1

Chores

  • ci: add timeout thresholds for CI jobs (b642163)
  • client: minor internal fixes (f3be3a7)

0.15.0 (2025-04-10)

Full Changelog: v0.14.0...v0.15.0

Features

Chores

  • internal: reduce CI branch coverage (27d4cbc)
  • internal: upload builds and expand CI branch coverage (#171) (3970fad)

0.14.0 (2025-04-08)

Full Changelog: v0.13.0...v0.14.0

Features

Bug Fixes

Chores

  • client: expose headers on some streaming errors (#159) (be1dd4a)
  • exports: cleaner resource index imports (#155) (086093a)
  • exports: stop using path fallbacks (#156) (e0a4623)
  • internal: add aliases for Record and Array (#165) (2c53021)
  • internal: fix devcontainers setup (#144) (e9bd176)
  • internal: remove extra empty newlines (#152) (a161ee7)
  • tests: improve enum examples (#169) (616acc8)

Documentation

  • update URLs from stainlessapi.com to stainless.com (#145) (511a9de)

0.13.0 (2025-01-27)

Full Changelog: v0.12.0...v0.13.0

Features

0.12.0 (2025-01-23)

Full Changelog: v0.11.2...v0.12.0

Features

0.11.2 (2025-01-23)

Full Changelog: v0.11.1...v0.11.2

Bug Fixes

  • send correct Accept header for certain endpoints (#122) (29223b0)

Chores

0.11.1 (2025-01-06)

Full Changelog: v0.11.0...v0.11.1

Chores

  • internal: fix lint errors (194e247)

0.11.0 (2025-01-02)

Full Changelog: v0.10.0...v0.11.0

Features

  • added messages format check (d2fa4db)
  • api: add models for chat completion structured message types (#107) (d32c311)
  • api: api update (#99) (dea8e5c)
  • internal: make git install file structure match npm (#101) (28e49f0)

Bug Fixes

Chores

Documentation

0.10.0 (2024-11-27)

Full Changelog: v0.9.0...v0.10.0

Features

Bug Fixes

Chores

  • internal: version bump (#83) (2e9673e)
  • rebuild project due to codegen change (#87) (800fd5a)
  • rebuild project due to codegen change (#88) (7db117f)
  • rebuild project due to codegen change (#90) (7d5a9b4)
  • rebuild project due to codegen change (#91) (1703fbc)
  • remove redundant word in comment (#94) (bedbb68)

Documentation

  • remove suggestion to use npm call out (#93) (52bdca6)

0.9.0 (2024-11-05)

Full Changelog: v0.8.0...v0.9.0

Features

  • adding upload API as a helper function. Need to figure out how to make it part of Together.files package (59efebe)
  • fixed linting error (045f8dd)
  • removed (d588157)
  • updated yarn.lock (6487474)
  • yarn lock change (b8ce4ae)

0.8.0 (2024-10-30)

Full Changelog: v0.7.0...v0.8.0

Features

Documentation

  • api: Add back in required readme field (#78) (74b457f)

0.7.0 (2024-10-23)

Full Changelog: v0.6.0...v0.7.0

Features

0.6.0 (2024-10-22)

Full Changelog: v0.6.0-alpha.8...v0.6.0

Features

  • api: api update (#67) (21e06d1)
  • api: OpenAPI spec update via Stainless API (#55) (ebe1c62)
  • api: OpenAPI spec update via Stainless API (#62) (b6af173)

Bug Fixes

  • client: correct File construction from node-fetch Responses (#54) (e1d5c6b)
  • errors: pass message through to APIConnectionError (#60) (0d0ede4)
  • uploads: avoid making redundant memory copies (#57) (e88f744)

Chores

  • better object fallback behaviour for casting errors (#61) (bad19ff)
  • ci: install deps via ./script/bootstrap (#52) (a22842a)
  • internal: codegen related update (#56) (8fd1782)
  • internal: codegen related update (#58) (e5b82e7)
  • internal: codegen related update (#59) (962541e)
  • internal: codegen related update (#63) (6093fb9)
  • internal: move LineDecoder to a separate file (#64) (9a5999d)
  • internal: pass props through internal parser (#65) (162bc3c)

0.6.0-alpha.8 (2024-08-29)

Full Changelog: v0.6.0-alpha.7...v0.6.0-alpha.8

Features

  • api: OpenAPI spec update via Stainless API (#48) (e382b4a)

Chores

0.6.0-alpha.7 (2024-08-28)

Full Changelog: v0.6.0-alpha.6...v0.6.0-alpha.7

Features

  • api: OpenAPI spec update via Stainless API (#44) (5fbcdd8)

Bug Fixes

  • chat completion streaming when enabling logprobs (cad72ef)

Chores

0.6.0-alpha.6 (2024-08-26)

Full Changelog: v0.6.0-alpha.5...v0.6.0-alpha.6

Chores

  • internal: codegen related update (#41) (3776c8d)

0.6.0-alpha.5 (2024-08-20)

Full Changelog: v0.6.0-alpha.4...v0.6.0-alpha.5

Features

  • api: manual updates (#31) (52c8005)
  • api: OpenAPI spec update via Stainless API (#28) (9544a3f)
  • api: OpenAPI spec update via Stainless API (#36) (0154ccf)
  • api: OpenAPI spec update via Stainless API (#39) (a141abb)

Chores

0.6.0-alpha.4 (2024-07-16)

Full Changelog: v0.6.0-alpha.3...v0.6.0-alpha.4

Features

  • api: manual updates (#22) (ede606f)
  • api: OpenAPI spec update via Stainless API (#18) (73499c2)
  • api: OpenAPI spec update via Stainless API (#19) (9158220)
  • api: OpenAPI spec update via Stainless API (#20) (debd949)
  • api: OpenAPI spec update via Stainless API (#23) (1b03e3f)
  • api: OpenAPI spec update via Stainless API (#24) (e28fb4b)
  • api: OpenAPI spec update via Stainless API (#25) (24a4e34)
  • api: OpenAPI spec update via Stainless API (#26) (a041bff)

Bug Fixes

  • client: fix auth via Bearer token (#21) (c001b61)

Chores

0.6.0-alpha.3 (2024-05-29)

Full Changelog: v0.6.0-alpha.2...v0.6.0-alpha.3

Features

Chores

0.6.0-alpha.2 (2024-05-27)

Full Changelog: v0.6.0-alpha.1...v0.6.0-alpha.2

Features

  • api: OpenAPI spec update via Stainless API (#10) (8e9cec9)

0.6.0-alpha.1 (2024-05-24)

Full Changelog: v0.1.0-alpha.1...v0.6.0-alpha.1

Features

0.1.0-alpha.1 (2024-05-20)

Full Changelog: v0.0.1-alpha.0...v0.1.0-alpha.1

Features

  • api: Config update for pstern-sl/dev (50330bc)
  • api: manual updates (d3d60df)
  • api: OpenAPI spec update via Stainless API (c7b048d)
  • api: OpenAPI spec update via Stainless API (f2eba5e)
  • api: OpenAPI spec update via Stainless API (9d72c93)
  • api: OpenAPI spec update via Stainless API (d5f7089)
  • api: OpenAPI spec update via Stainless API (2f777f5)
  • api: OpenAPI spec update via Stainless API (6b6d656)
  • api: OpenAPI spec update via Stainless API (2099de1)
  • api: OpenAPI spec update via Stainless API (#3) (6ab0237)
  • api: OpenAPI spec update via Stainless API (#5) (2cea8b5)
  • api: update via SDK Studio (78442fc)
  • api: update via SDK Studio (8bb8235)
  • api: update via SDK Studio (4edc4ed)
  • api: update via SDK Studio (6792cd8)
  • api: update via SDK Studio (0e5a965)
  • api: update via SDK Studio (b208042)
  • api: update via SDK Studio (e705a6a)
  • api: update via SDK Studio (8801a8f)
  • api: update via SDK Studio (3c8036e)
  • api: update via SDK Studio (5f63392)
  • api: update via SDK Studio (afbb5d9)
  • api: update via SDK Studio (c89406c)
  • api: update via SDK Studio (1a01c5f)
  • api: update via SDK Studio (97762a6)
  • api: update via SDK Studio (644232d)
  • api: update via SDK Studio (4af7da5)
  • api: update via SDK Studio (7ffe18f)
  • api: update via SDK Studio (8eac113)
  • api: update via SDK Studio (8b71dad)
  • api: update via SDK Studio (b873e4b)
  • api: update via SDK Studio (333b4bd)
  • api: update via SDK Studio (19125a0)
  • api: updates (3781ee8)
  • update via SDK Studio (de036f5)
  • update via SDK Studio (913553c)
  • update via SDK Studio (1716130)
  • update via SDK Studio (fccf615)
  • update via SDK Studio (5cb5be4)
  • update via SDK Studio (504bc56)
  • update via SDK Studio (bca35e9)
  • update via SDK Studio (d26b5ce)

Chores