Together AI Integration Guide
What is Together AI?
OpenAI-compatible base URL + native SDK + AI SDK 7 provider over a fast-churning open-model catalog.
Point the OpenAI SDK at `https://api.together.ai/v1` for chat, vision, tools, JSON schema, images and audio. Use `together-ai@0.58.0` / `together` 2.42 for batches, files, fine-tuning, rerank, endpoints, video and `codeInterpreter.execute`. In AI SDK 7 use `@ai-sdk/togetherai@3`, and use `generateText` + `Output.object` because `generateObject` fails. Hybrid reasoners take `reasoning: { enabled: false }`. Serverless embeddings and rerank are gone, and Llama 3.x, Gemma and Qwen2.5-VL have left serverless, so keep model IDs in one config module and watch the deprecations page. For codeAmani: turn on ZDR in Org Settings → Privacy (training opt-in is already off by default). Route bulk Swahili/English text to `Qwen/Qwen3.5-9B` behind an in-house Swahili eval, and keep Claude for quality-critical turns.
Five Together AI primitives
One OpenAI-shaped endpoint fronts the open-model catalog. Pick how you pay for capacity, then lock down data retention.
████████╗ ██████╗ ██████╗ ███████╗████████╗██╗ ██╗███████╗██████╗ █████╗ ██╗
╚══██╔══╝██╔═══██╗██╔════╝ ██╔════╝╚══██╔══╝██║ ██║██╔════╝██╔══██╗ ██╔══██╗██║
██║ ██║ ██║██║ ███╗█████╗ ██║ ███████║█████╗ ██████╔╝ ███████║██║
██║ ██║ ██║██║ ██║██╔══╝ ██║ ██╔══██║██╔══╝ ██╔══██╗ ██╔══██║██║
██║ ╚██████╔╝╚██████╔╝███████╗ ██║ ██║ ██║███████╗██║ ██║ ██║ ██║██║
╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝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:
- Chat / reasoning / vision: Qwen3.5–3.8, GLM-5.x, DeepSeek V4.x, Kimi K3, MiniMax M3, Meta Muse, gpt-oss and NVIDIA Nemotron
- Images: FLUX.2, FLUX.1 Kontext, GPT Image, Nano Banana, Seedream, Qwen Image and Ideogram. Many of these are passthrough models; see the privacy section below
- Video (Seedance, Veo, Wan, FLUX 3…), text-to-speech (Cartesia Sonic, Kokoro, Orpheus) and speech-to-text (Whisper large-v3, Parakeet, Nemotron ASR)
- Batch API, dedicated endpoints, provisioned throughput, fine-tuning, post-training, code interpreter / code sandbox, and GPU clusters
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.
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, anddocs/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_formatImage models bill in one of two ways:
- Per megapixel: models Together serves directly, such as FLUX.2 [max] at $0.07/MP and FLUX.1 Kontext [pro] at $0.04/MP. Going above the default step count raises the cost proportionally. Going below it does not lower the cost.
- Per image (estimate): passthrough providers such as GPT Image, Nano Banana, Seedream and FLUX.2 pro/dev/flex. You pay whatever the upstream provider charges.
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.
- Rerank: the API (
client.rerank.create,POST /v1/rerank) still exists but needs a dedicated endpoint running a rerank model. The docs namemixedbread-ai/mxbai-rerank-large-v2, but it is not in the dedicated catalog, so you may need to upload it as a custom model. Verify this before you plan on it. - Swahili RAG embeddings: move off Together. Use
intfloat/multilingual-e5-largethrough the Hugging Face router (hf-inference,deepinfra) or Pinecone's hostedmultilingual-e5-large. See thehugging-face/andpinecone/guides.client.embeddings.createand AI SDK.embeddingModel()still compile but have no serverless model to call.
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
- Serverless: per-token pricing on a shared fleet. Dynamic per-account rate limits were retired on 2026-10-02. You may still get
429(slow down) or503(wait and retry) at peak, so use exponential backoff on both. Serverless has no region selection. Cached input is automatic, prefix-based and best-effort. - Provisioned throughput: reserved capacity for GLM-5.3, GLM-5.3-Flash, GLM-5.2, DeepSeek-V4.1-Flash or Kimi K3. You buy it from sales at $0.05 per PTU-minute with a 1-month minimum. The SLA is 99% successful requests. Traffic above your PTUs overflows to serverless at serverless rates.
- Dedicated endpoints (DMI): billed per GPU-minute, and only while replicas are ready. H100 80GB costs $5.49/hr and B200 $8.99/hr; H200, B300 and GB300 are quoted by sales. One H100 running all day is about $132/day or $3,950/month. You can set autoscaling bounds and an idle shutdown (
--inactive-timeout), plus traffic splits, A/B tests, rollouts and HIPAA placement (--placement.hipaa).- Deploy with
tg beta endpoints deploy <model> --endpoint <name>. Call it by passing the endpoint string<project_slug>/<endpoint_name>asmodel. - The docs send dedicated traffic to
https://api-inference.together.ai/v1.
- Deploy with
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.
- Every job has a $4 minimum; larger models have higher minimums.
- Failed jobs are fully refunded. A cancelled job charges only the steps it completed.
- After training, you can host the model on a dedicated endpoint, which bills per minute, or download it.
| 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:
- Turn ZDR on for every codeAmani production org. The default stores prompts, and the org setting overrides any personal-account toggle for traffic sent with org API keys. ZDR is not retroactive. To delete data from before you enabled it, use the settings page or email
privacy@together.ai. - What is kept even with ZDR: request metadata (token counts, model IDs, timestamps), account and billing data, and files you upload. Fine-tuning and batch files stay until you delete them; batch input, output and error files expire after 7 days.
- Turning ZDR on removes the passthrough image models. That covers GPT Image, Nano Banana, Seedream and the per-image FLUX.2 variants. If you need ZDR and images together, use per-megapixel models served by Together itself (FLUX.2 [max], FLUX.1 Kontext, SD XL…). Test this first: the catalog does not label which models are passthrough.
- Hosting location: third-party open models run on Together's own infrastructure, and the model authors never see your traffic. DeepSeek models, for example, run in Together's North America data centers. Serverless has no region pinning. For residency (EU), VPC, private networking or HIPAA, use dedicated endpoints with placement policies or an enterprise contract.
- Keys are project-scoped and can be given an expiry date. Anyone holding a key can spend your balance, and auto-recharge will refill it.
- HIPAA / PHI: never send PHI to serverless. Use dedicated endpoints with HIPAA placement, under a signed agreement with Together. This is not verified as self-serve; ask sales.
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:
- 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.
- Text first: WhatsApp + M-Pesa bots (P1). Keep Claude as the fallback for low-confidence turns.
- Dialect control: LoRA-fine-tune
Qwen/Qwen3.5-9BorQwen/Qwen3.8-27Bon curated Sheng/Tanzanian data, then host it on a dedicated endpoint. Remember the endpoint's per-minute cost; use idle shutdown. - Embeddings for Swahili RAG now come from Hugging Face or Pinecone, not Together.
- Swahili speech-to-text:
openai/whisper-large-v3is on serverless at $0.0015/min. Together has no Swahili TTS claim, so keep TTS on ElevenLabs orfacebook/mms-tts-swhbehind 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-keyNon-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
- Secrets server-side only.
TOGETHER_API_KEYlives in Vercel env vars or the Hazina vault and is used only fromapp/api/**, server actions or workers. Never ship it to the browser. Use separate keys per environment, and set an expiry on dev/CI keys. - Turn on ZDR in Org Settings → Privacy for any org that handles customer text, and leave training opt-in off. Record the setting in the project's compliance notes (
COMPLIANCE_GUIDE.md; KDPA for Kenya-targeted projects). - Pin model IDs in one config module, never inline in routes, and alert on 404s. Five of the nine model IDs the previous version of this guide used are gone or going from serverless.
- Payments are unaffected. Together is pay-as-you-go by card on Together's side. Customer billing for codeAmani apps stays on Stripe (default), with M-Pesa only for Kenya-targeted projects.
- Open weights = data-sovereignty on-ramp. Apache/MIT models such as Qwen3.5, Muse Glimmer, GLM-5.3-Flash and DeepSeek can later move to self-hosted or HF ZeroGPU with only a
baseURLchange. - Kenya-targeted, 2G/3G: use small models with reasoning disabled (
Qwen/Qwen3.5-9B,reasoning: { enabled: false }), always stream, and capmax_tokens. For images, choose cheap per-image models and small sizes (FLUX.2-devat 512×512). - Cost discipline: on classification batches set
max_tokens: 4andtemperature: 0. Cached input on DeepSeek-V4.1-Flash costs $0.006/1M, so put the fixed system prompt first to benefit from prefix caching.
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 |