Together AI Integration Guide

Technology: together-ai · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/together-ai

Insight:

Together AI is the open-model marketplace tier: about 20 serverless chat models (Qwen, GLM, DeepSeek V4, Kimi K3, MiniMax, Meta Muse, gpt-oss) plus image, video and audio models behind one OpenAI-compatible endpoint (https://api.together.ai/v1). The catalog churns fast. Llama 3.x, Gemma, Qwen2.5-VL and all serverless embedding and rerank models are gone, so pin model IDs from the live catalog and watch the deprecations page. Prompts are stored by default until an org admin turns on zero data retention. Training on your data is opt-in and off by default.

████████╗ ██████╗  ██████╗ ███████╗████████╗██╗  ██╗███████╗██████╗      █████╗ ██╗
╚══██╔══╝██╔═══██╗██╔════╝ ██╔════╝╚══██╔══╝██║  ██║██╔════╝██╔══██╗    ██╔══██╗██║
   ██║   ██║   ██║██║  ███╗█████╗     ██║   ███████║█████╗  ██████╔╝    ███████║██║
   ██║   ██║   ██║██║   ██║██╔══╝     ██║   ██╔══██║██╔══╝  ██╔══██╗    ██╔══██║██║
   ██║   ╚██████╔╝╚██████╔╝███████╗   ██║   ██║  ██║███████╗██║  ██║    ██║  ██║██║
   ╚═╝    ╚═════╝  ╚═════╝ ╚══════╝   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝    ╚═╝  ╚═╝╚═╝

Together AI Integration Guide

Focus: Open-weight inference through an OpenAI-compatible API. Covers serverless chat, vision, images, audio and video; the batch API; dedicated endpoints and provisioned throughput; fine-tuning and post-training; the code interpreter; and data-retention controls.

Overview

Together AI hosts open-source and open-weight models and bills per token, image, second or minute. You get no GPUs to manage. A single API key reaches:

The REST API follows OpenAI's shape, so you can keep the OpenAI SDK and change only the key and base URL. The first-party together-ai (npm) / together (PyPI) SDKs add the full surface: rerank, batches, files, fine-tuning, endpoints, code interpreter and video.

For codeAmani, Together is the open-weight lever. It sits beside Anthropic Claude, which sets the quality ceiling, and handles high-volume, cheap or fine-tuned work. The 2026-06-22 Swahili research report rated it "adopt" as the open-model and fine-tuning rail for Kenya-targeted text features.

flowchart LR
  A["Your app code<br/>(server-side only)"] --> B["OpenAI SDK · together-ai · @ai-sdk/togetherai<br/>baseURL api.together.ai/v1"]
  B --> C{"Model string"}
  C -->|"small / cheap"| D["Qwen/Qwen3.5-9B<br/>GLM-5.3-Flash · DeepSeek-V4.1-Flash"]
  C -->|"general"| E["meta-models/Muse-Glimmer-30B"]
  C -->|"frontier-open"| F["Kimi-K3 · GLM-5.3 · DeepSeek-V4-Pro"]
  C -->|"images"| G["FLUX.2 · GPT Image 2"]
  C -->|"endpoint string"| H["Dedicated endpoint<br/>api-inference.together.ai/v1"]

Official Documentation

Resource URL
Quickstart https://docs.together.ai/docs/quickstart
Serverless model catalog (IDs, context, prices) https://docs.together.ai/docs/serverless/models
Recommended models by use case https://docs.together.ai/docs/inference/recommended-models
OpenAI compatibility matrix https://docs.together.ai/docs/inference/openai-compatibility
Deprecations (removal dates) https://docs.together.ai/docs/deprecations
Changelog https://docs.together.ai/docs/changelog
Dedicated endpoints https://docs.together.ai/docs/dedicated-endpoints/overview
Zero data retention https://docs.together.ai/docs/zero-data-retention
Vercel AI SDK quickstart https://docs.together.ai/docs/using-together-with-vercels-ai-sdk
Pricing https://www.together.ai/pricing

URL moves (2026): docs/serverless-models → docs/serverless/models, docs/dedicated-endpoints → docs/dedicated-endpoints/overview, and docs/inference/pricing → docs/serverless/overview. The old paths still redirect.


Versions (verified 2026-10-20)

Package Version Notes
together-ai (npm) 0.58.0 Still 0.x, so pin exact. Client exposes chat, completions, embeddings, images, videos, audio, rerank, batches, files, fineTuning, codeInterpreter, endpoints, evals, models, projects, clusters, beta
together (PyPI) 2.42.0 Python ≥3.10. v2 is generated from the API spec: keyword-only args, httpx, renamed batch methods (migration guide). Post-training needs ≥2.41.0
@ai-sdk/togetherai 3.0.75 The 3.x line pairs with ai@7 (dist-tags: ai-v6 = 2.x, ai-v5 = 1.x). Peer: zod ^3.25.76 || ^4.1.8
ai 7.0.146 Vercel AI SDK 7
openai (npm) 7.39.0 Drop-in client

Setup

Option A: OpenAI SDK (drop-in)

import OpenAI from "openai";

const together = new OpenAI({
  apiKey: process.env.TOGETHER_API_KEY!,
  baseURL: "https://api.together.ai/v1",
});

const res = await together.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  messages: [{ role: "user", content: "Habari! Nisaidie kuandika tangazo fupi." }],
});

Through the OpenAI SDK the following are supported: chat, vision, tools, response_format, legacy completions, embeddings.create, images.generate, audio.speech / transcriptions / translations, and models.list.

These are not supported: Assistants/Threads, OpenAI-shaped batches.* and fine_tuning.*, and moderations. Video, image edits, rerank and logprobs are Together-native.

reasoning_effort works only on gpt-oss. service_tier, store, metadata and prediction are ignored. Read cached-token counts from both places: usage.prompt_tokens_details.cached_tokens (reasoning models) and a flat usage.cached_tokens (some non-reasoning models).

Option B: Native Together SDK (full surface)

npm install together-ai@0.58.0   # Node / TypeScript
pip install together             # Python (2.42.0)
import Together from "together-ai";

const client = new Together(); // reads TOGETHER_API_KEY, TOGETHER_BASE_URL, TOGETHER_PROJECT_ID

const res = await client.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  messages: [{ role: "user", content: "Say this is a test!" }],
  reasoning: { enabled: false }, // Together-native toggle for hybrid reasoning models
});
from together import Together

client = Together()  # reads TOGETHER_API_KEY
resp = client.chat.completions.create(
    model="Qwen/Qwen3.5-9B",
    messages=[{"role": "user", "content": "What is 2 + 2?"}],
    reasoning={"enabled": False},
)
print(resp.choices[0].message.content)

Option C: Vercel AI SDK 7

import { generateText, Output } from "ai";
import { createTogetherAI } from "@ai-sdk/togetherai";
import { z } from "zod";

// The provider's default baseURL is still the legacy https://api.together.xyz/v1
// (it works). Pin the current host explicitly.
const together = createTogetherAI({
  apiKey: process.env.TOGETHER_API_KEY ?? "",
  baseURL: "https://api.together.ai/v1",
});

const { output } = await generateText({
  model: together("zai-org/GLM-5.3-Flash"),
  output: Output.object({ schema: z.object({ category: z.string() }) }),
  prompt: "Classify: 'Mzigo wangu haujafika'",
  providerOptions: { togetherai: { reasoning: { enabled: false } } },
});

providerOptions.togetherai is passed straight into the request body. Use generateText + Output.object, not generateObject. Together's docs say generateObject fails with a schema-validation error on this provider. The provider also offers .image(), .embeddingModel() and .reranking(). The last two need a model that is actually deployed, because nothing is on serverless (see Embeddings below). Full typed examples are in examples/ai-sdk.ts.


Current model picks (serverless, 2026-10-20)

From the catalog and recommended models. Prices are per 1M tokens (input / cached input / output).

Use Model ID Price Notes
Small, fast, vision Qwen/Qwen3.5-9B $0.17 / – / $0.25 Together's "small and fast" and default vision pick. Apache-2.0. 262K ctx
General (Llama 3.3 replacement) meta-models/Muse-Glimmer-30B $0.35 / $0.04 / $1.50 Official replacement for Llama-3.3-70B-Instruct-Turbo. Apache-2.0
Mid-size, 1M context deepseek-ai/DeepSeek-V4.1-Flash $0.30 / $0.006 / $1.20 Very cheap cached input. MIT
Function calling zai-org/GLM-5.3-Flash $0.15 / $0.03 / $0.50 Together's function-calling pick. MIT
Cheap open reasoning openai/gpt-oss-120b $0.15 / – / $0.60 reasoning_effort low/medium/high
Frontier-open chat / reasoning moonshotai/Kimi-K3 $3.00 / $0.30 / $15.00 Together's top chat pick. Reasons by default
Coding agents zai-org/GLM-5.3 $1.40 / $0.26 / $4.40
Multimodal + long context MiniMaxAI/MiniMax-M3 $0.30 / $0.06 / $1.20 Quickstart default. 524K ctx
Text-to-image openai/gpt-image-2 (rec.) · black-forest-labs/FLUX.2-dev (cheap) ~$0.053 / ~$0.0154+ per image FLUX.1-schnell is gone
Speech-to-text nvidia/nemotron-3.5-asr-streaming-0.6b · openai/whisper-large-v3 $0.0015 / audio min Whisper gets the batch discount
Text-to-speech cartesia/sonic-3 · hexgrad/Kokoro-82M $65 · $4 per 1M chars

Models removed since the last review: migrate now

Old ID (was in this guide) Status Move to
meta-llama/Llama-3.3-70B-Instruct-Turbo Scheduled removal from serverless 2026-10-22 (already absent from the catalog) meta-models/Muse-Glimmer-30B (or a dedicated endpoint)
meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo Removed 2026-03-06 Qwen/Qwen3.5-9B
deepseek-ai/DeepSeek-V3.1 Removed 2026-05-14 deepseek-ai/DeepSeek-V4.1-Flash
Qwen/Qwen2.5-VL-72B-Instruct Removed 2026-01-05 Qwen/Qwen3.5-9B (vision)
intfloat/multilingual-e5-large-instruct Removed 2026-09-15, no dedicated option Off-platform (see Embeddings)
black-forest-labs/FLUX.1-schnell Removed 2026-08-19 black-forest-labs/FLUX.2-dev
black-forest-labs/FLUX.2-pro Still listed, now billed per image (~$0.03+) Unchanged

Lifecycle policy: an "upgrade" redirects automatically after 3 days' notice. A "new model" gets 2–3 weeks of deprecation notice and no redirect, and you must change the ID. Preview models can go with less than 24 hours' notice after 30 days. Users of a deprecated model get an email. Read deprecations before every release.


Core Patterns

Streaming (reasoning-aware)

Reasoning models stream their thinking in delta.reasoning and the answer in delta.content. Some use reasoning_content instead. Switch reasoning off with reasoning: { enabled: false } when you only want the answer.

const stream = await client.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  messages: [{ role: "user", content: prompt }],
  stream: true,
  reasoning: { enabled: false },
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
// Cancel with stream.controller.abort()

The Next.js route version, which also uses a model allowlist, is in examples/streaming.ts.

Structured outputs (JSON mode)

import { z } from "zod";
const Order = z.object({ item: z.string(), quantity: z.number().int() });

const res = await client.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  reasoning: { enabled: false },
  messages: [{ role: "user", content: "Nataka mikate miwili" }],
  response_format: {
    type: "json_schema",
    json_schema: { name: "order", schema: z.toJSONSchema(Order) },
  },
});
const order = Order.parse(JSON.parse(res.choices[0]?.message?.content ?? "{}"));

response_format accepts text, json_schema or json_object. The catalog's Structured outputs column lists which models support it.

Function calling

You pass OpenAI-shaped tools / tool_choice and get tool_calls back. Together documents the simple, multiple, parallel, multi-step, multi-turn and vision variants. Pick a model whose catalog row shows Function calling = Yes; zai-org/GLM-5.3-Flash is the recommended one. When a reasoning model makes multi-turn tool calls, send its reasoning / reasoning_content field back under the same key. The example is in examples/client.ts.

Vision

Add an image_url content part to the message. It can be a remote URL or a base64 data URI. The detail field is accepted but ignored. Vision models today are Qwen/Qwen3.5-9B (start here), MiniMaxAI/MiniMax-M3, nvidia/NVIDIA-Nemotron-3.5-Super-VL and moonshotai/Kimi-K3.

Image generation

const image = await client.images.generate({
  model: "black-forest-labs/FLUX.2-dev",
  prompt: "A vibrant Nairobi street market at golden hour, photorealistic",
  width: 1024,
  height: 768,
});
image.data[0]?.url; // or b64_json via response_format

Image models bill in one of two ways:

Image calls need a positive credit balance.

Batch API (offline, separate rate-limit pool)

Limit Value
Requests per batch 50,000
Input file 100 MB (10 MB per line)
Enqueued tokens 30B per model
Completion window 24h, fixed and best-effort (small batches finish in minutes)
File retention 7 days for input, output and error files, then gone
Discount "Up to 50%", but only for models on the discounted list. Today that list is only openai/whisper-large-v3. Every other model runs at standard rates

You are billed only for successful lines. Join results on custom_id, and always read the error file. CLI: tg batches submit file.jsonl --api chat.completions. The SDK version is in examples/batch-classify.ts.

Embeddings and rerank: no longer on serverless

As of 2026-10-20 the serverless catalog says "There are currently no embedding models offered via serverless" and "no rerank models." multilingual-e5-large-instruct was removed on 2026-09-15 and cannot be run as an on-demand dedicated endpoint.

Code interpreter and code sandbox

Product API Price Access
Code interpreter (TCI) client.codeInterpreter.execute({ code, language: "python", session_id? }) → POST /v1/tci/execute, plus codeInterpreter.sessions $0.03 per 60-minute session Self-serve. Python only
Code sandbox together-sandbox (npm/PyPI/CLI): Docker-image snapshots, sandboxes.create, execs.exec $0.0446 per vCPU-hr + $0.0149 per GiB-hr Allowlist: contact Together. Replaces the legacy @codesandbox/sdk flow

Use it to run model-generated code away from your own servers. Never eval model output locally.


Serverless vs. provisioned throughput vs. dedicated

flowchart TD
  A["Run an open model"] --> B{"Steady, high volume?"}
  B -->|"no: bursty / dev"| C["Serverless<br/>per token, best-effort, no region choice"]
  B -->|"yes, stock model, want SLA"| D["Provisioned throughput<br/>$0.05 per PTU-minute, 1-month min, sales-only"]
  B -->|"yes, fine-tuned / custom / region / HIPAA"| E["Dedicated endpoint<br/>per GPU-minute"]

Fine-tuning and post-training

Fine-tuning is a managed job that bills per token processed: (epochs × training tokens) + (evals × validation tokens). It supports LoRA (default; rank defaults to 64, up to 128) or full fine-tuning, with SFT or DPO.

LoRA base (examples) SFT / DPO per 1M tokens Min
Qwen/Qwen3.5-9B, Qwen/Qwen3.5-4B, meta-llama/Meta-Llama-3.1-8B-Instruct-Reference $0.34 / $0.84 $4
Qwen/Qwen3.8-27B, google/gemma-4-31B-it, Qwen/Qwen3.6-35B-A3B $1.05 / $2.62 $4
meta-llama/Llama-3.3-70B-Instruct-Reference $2.03 / $5.08 $4
openai/gpt-oss-120b $2.50 / $6.25 $6

Get a quote with tg fine-tuning create (the CLI asks you to confirm the price), client.fineTuning.estimatePrice(...), or the console. Before you train, check that the base model can be deployed (tg beta models configs <BASE_MODEL>). Some fine-tunable models cannot be hosted on a dedicated endpoint.

Post-training (launched 2026-10-13) works differently: your own Python loop calls forward_backward / optim_step / sample_batch against GPUs you provision. It supports SFT, DPO and GRPO, and is billed per GPU-minute. B200 lists at $11/GPU-hr, with a promo price of $9 until 2026-12-14. You need a $100 minimum credit balance to start. Use it only if you need RL or custom loss functions; the job-based fine-tuning above is simpler.


Data retention, training and privacy (US customers)

Sources: zero data retention and privacy and security. The privacy policy is the legal source of truth.

Setting (Org Settings → Privacy, admins only) Default Effect
Store prompts and model responses On Together stores prompts and outputs and may use them for product improvement. They are not shared with third parties and can be deleted. Turning this off = zero data retention (ZDR).
Allow organization's data for training Off Opt-in only. Together does not train on your data without explicit consent
Allow passthrough models On Passthrough models forward your prompts to a third-party provider, under that provider's data policy. Turning ZDR on switches passthrough off automatically

What this means in practice:


Swahili and Kenya-targeted text

The research report (research-and-development/reports/2026-06-22-swahili-ai-models.md) chose Together as the open-model rail. Its candidates were Gemma 2 27B, Llama 3.3 70B and Llama 4 Scout, and all of them have since left Together serverless. Gemma 3n, the report's "high-volume text" pick, is gone too, and so is the multilingual-e5 embedder.

Current serverless models and what their model cards claim, checked on the Hub 2026-10-20. None of the cards names Swahili explicitly.

Model Card's language claim License Fit for Swahili work
Qwen/Qwen3.5-9B "201 languages and dialects" Apache-2.0 Default candidate. Cheap, vision, also LoRA-fine-tunable ($0.34/1M)
meta-models/Muse-Glimmer-30B "data from more than 100 languages" Apache-2.0 Quality step-up, and the Llama 3.3 replacement
moonshotai/Kimi-K3, zai-org/GLM-5.3, deepseek-ai/DeepSeek-V4.1-Flash, MiniMaxAI/MiniMax-M3, openai/gpt-oss-120b No multilingual coverage stated (GLM cards tag only en, zh) Mixed Evaluate before use, do not assume
google/gemma-4-31B-it "140+ languages" (pre-training) Apache-2.0 Dedicated endpoint or fine-tune only. Left serverless 2026-09-15

Rules:

  1. Gate on the in-house Swahili + Sheng eval before any production route. Use AfriMMLU, MasakhaNEWS, FLORES-200 and the codeAmani set. Dialect fragility is the #1 risk in the report.
  2. Text first: WhatsApp + M-Pesa bots (P1). Keep Claude as the fallback for low-confidence turns.
  3. Dialect control: LoRA-fine-tune Qwen/Qwen3.5-9B or Qwen/Qwen3.8-27B on curated Sheng/Tanzanian data, then host it on a dedicated endpoint. Remember the endpoint's per-minute cost; use idle shutdown.
  4. Embeddings for Swahili RAG now come from Hugging Face or Pinecone, not Together.
  5. Swahili speech-to-text: openai/whisper-large-v3 is on serverless at $0.0015/min. Together has no Swahili TTS claim, so keep TTS on ElevenLabs or facebook/mms-tts-swh behind the MOS gate.

AI routing: where Together fits

Task Provider / model
Complex reasoning, agents, quality-critical text Anthropic Claude (current model ID in the anthropic/ guide)
High-volume classification, extraction, FAQ, RAG synthesis Together Qwen/Qwen3.5-9B → meta-models/Muse-Glimmer-30B
Cheap tool-calling agents Together zai-org/GLM-5.3-Flash
Open long-context (1M) Together deepseek-ai/DeepSeek-V4.1-Flash
Vision / receipts / OCR Together Qwen/Qwen3.5-9B (or MiniMax-M3)
Image generation Together black-forest-labs/FLUX.2-dev (cheap) / openai/gpt-image-2 (quality)
Fast structured JSON (OpenAI) OpenAI GPT-4o per company routing policy
Embeddings Hugging Face / Pinecone (multilingual-e5-large), not Together

Together is OpenAI-shaped, so the resilient-fallback pattern applies unchanged. Retry 429 and 503 with jittered exponential backoff, then fall back to Claude. Also handle a 404 / "model unavailable" error by falling back, because deprecations remove IDs on a schedule.


Environment Variables

The only secret:

TOGETHER_API_KEY=your-together-api-key

Non-secret settings, read by the native SDK:

Variable Default Purpose
TOGETHER_BASE_URL https://api.together.ai/v1 Point at a proxy, or at https://api-inference.together.ai/v1 for dedicated endpoints
TOGETHER_PROJECT_ID key's project Project scope for beta endpoint/management calls and the CLI
TOGETHER_LOG warn SDK log level

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Check TOGETHER_API_KEY. Keys are project-scoped and may have expired
404 / model not found / unavailable The ID was probably deprecated. Check deprecations. IDs are case-sensitive org/model
Empty content but tokens were used A reasoning model spent max_tokens on thinking. Raise max_tokens or pass reasoning: { enabled: false }
generateObject schema error (AI SDK) Use generateText with Output.object
cached_tokens always 0 Read both usage.prompt_tokens_details.cached_tokens and usage.cached_tokens
429 / 503 Exponential backoff. For steady load, buy provisioned throughput or use a dedicated endpoint
Embeddings call fails No serverless embedding models exist. Use HF / Pinecone
Image call refused Add credit (a positive balance is required). If ZDR is on, passthrough image models are disabled
Dedicated endpoint returns 404 Use the endpoint string <project_slug>/<endpoint> and the api-inference.together.ai/v1 base URL

Official docs: