# Manage your account Source: https://docs.together.ai/docs/account-management Sign up for Together AI, get your API key, and manage your account settings. ## Create an account Head to [together.ai](https://www.together.ai/) and select **Get Started**. You can sign in with Google or GitHub. Together uses OAuth (Open Authorization) instead of a traditional username and password. This keeps your account secure and means one less password to remember. **Important:** You must always sign in with the same provider you used at signup. If you try a different provider, you'll see "This email is already linked to another sign-in method." > [!NOTE] > > LinkedIn authentication was previously available but has been discontinued. If you signed up with LinkedIn, you can now sign in with Google or GitHub using the same email address. ## Create an API key Once your account is set up, create a project API key to start making requests. > [card] [API keys and authentication](/docs/api-keys-authentication) > > Create, scope, and manage your API keys. ## Change your email address Because Together uses OAuth, email addresses can't be changed directly. To transfer your account to a new email: 1. **Create a new account** with your preferred email address. 2. **Contact support** from your current email and provide the new email address. 3. **Old account deactivation:** Your original account will be blocked to prevent confusion. 4. **Update your integrations:** Update any API integrations to use your new account's API key. Once the transfer is complete, you'll have access to all your previous features and credits under the new email. ## Delete your account You can delete your account through the self-service process. This complies with GDPR and other data protection regulations. 1. Log in to your Together AI account. 2. Navigate to your profile settings at [api.together.ai/settings/profile](https://api.together.ai/settings/profile). 3. Scroll down to the **Privacy and Security** section. 4. Select the **delete your account** link. 5. Follow the prompts to confirm. > [!WARNING] > > Account deletion removes all your personal data and unsubscribes you from all mailing lists. This cannot be undone. Due to OAuth authentication, you cannot create a new account using the same email address after deletion -- you would need a different email to sign up again. If you run into any issues, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). ## Next steps Your account belongs to an *organization*: a shared workspace for managing member access, project collaboration, and billing in one place. Learn more by reading these pages: > [card] [Organizations](/docs/organizations) > > Learn how membership and project collaboration work on Together. > [card] [Roles and permissions](/docs/roles-permissions) > > Control what each member can do in your organization. > [card] [Projects](/docs/projects) > > Organize work so teammates can share API keys, models, and usage. # Agent integrations Source: https://docs.together.ai/docs/agent-integrations Use OSS agent frameworks with Together AI. You can use Together AI with many of the most popular AI agent frameworks. Choose your preferred framework to learn how to enhance your agents with the best open source models. ## [LangGraph](/docs/langgraph) LangGraph is a library for building stateful, multi-actor applications with LLMs. It provides a flexible framework for creating complex, multi-step reasoning applications through acyclic and cyclic graphs. ## [CrewAI](/docs/crewai) CrewAI is an open source framework for orchestrating AI agent systems. It enables multiple AI agents to collaborate effectively by assuming roles and working toward shared goals. ## [PydanticAI](/docs/pydanticai) PydanticAI provides structured data extraction and validation for LLMs using Pydantic schemas. It ensures your AI outputs adhere to specified formats, making integration with downstream systems reliable. ## [AutoGen(AG2)](/docs/autogen) AutoGen(AG2) is an OSS agent framework for multi-agent conversations and workflow automation. It enables the creation of customizable agents that can interact with each other and with human users to solve complex tasks. ## [DSPy](/docs/dspy) DSPy is a programming framework for algorithmic AI systems. It offers a compiler-like approach to prompt engineering, allowing you to create modular, reusable, and optimizable language model programs. ## [Composio](/docs/composio) Composio provides a platform for building and deploying AI applications with reusable components. It simplifies the process of creating complex AI systems by connecting specialized modules. # Coding agent setup Source: https://docs.together.ai/docs/agent-skills Make your AI coding agent Together-AI-aware with a ready-made skill for code generation and an MCP server for live docs lookup. Together AI publishes two complementary tools for coding agents: * [Skill](#skill): A single `together-ai` skill that teaches your agent how to write correct Together AI code (right model IDs, SDK patterns, best practices) across every product area. * [Docs MCP server](#docs-mcp-server): Gives your agent live access to this documentation site so it can look up current information without leaving your editor. Install both for the best experience: the skill for code generation and MCP for documentation lookup. > [!TIP] > > To run the coding agent itself on Together AI models, use [Together Link](/docs/togetherlink). It routes coding agents through Together AI with one command and no provider configuration. The `together-ai` skill also covers Together Link setup. ## Skill The `together-ai` skill covers the whole platform, from chat completions and image generation to fine-tuning, dedicated model inference, and GPU clusters. When your agent detects a Together AI task, it loads the skill automatically. You can also invoke it by name, for example `/together-ai` in Claude Code or `$together-ai` in Codex. Installing one skill for the whole platform doesn't fill your agent's context. The skill's short `SKILL.md` routes each task to a guide for that product area, and the agent opens the deeper model lists, API references, and runnable scripts only when that guide points to them. ### Install the skill ```bash Any agent theme={null} npx skills add togethercomputer/skills ``` ```bash Claude Code theme={null} # From the plugin marketplace /plugin marketplace add togethercomputer/skills /plugin install togetherai-skills@togetherai-skills # Or copy manually (project-level) cp -r skills/together-ai your-project/.claude/skills/ # Or copy manually (global, available in all projects) cp -r skills/together-ai ~/.claude/skills/ ``` ```bash Cursor theme={null} cp -r skills/together-ai your-project/.cursor/skills/ ``` ```bash Codex theme={null} cp -r skills/together-ai your-project/.agents/skills/ ``` ```bash Gemini CLI theme={null} gemini extensions install https://github.com/togethercomputer/skills.git --consent ``` To verify a manual install, check that the skill's `SKILL.md` is in place (for example, `ls your-project/.claude/skills/together-ai/SKILL.md`). > [!NOTE] > > The skill replaces the earlier per-product skills (`together-chat-completions`, `together-images`, `together-gpu-clusters`, and so on). If you installed any of them, delete their directories after you install `together-ai`, so your agent doesn't load outdated guidance alongside the new skill. ### What the skill covers Each product area has its own domain guide inside the skill. | Domain guide | What it covers | | - | - | | **[Chat completions](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/chat-completions.md)** | Serverless chat inference, streaming, multi-turn conversations, tool calling, structured JSON outputs, and reasoning and vision models. | | **[Images](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/images.md)** | Text-to-image generation, image editing with Kontext, FLUX model selection, and reference-image guidance. | | **[Video](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/video.md)** | Text-to-video and image-to-video generation, keyframe control, and async job polling. | | **[Audio](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/audio.md)** | Text-to-speech (REST, streaming, realtime WebSocket) and speech-to-text (transcription, translation, diarization, timestamps, realtime). | | **[Batch inference](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/batch-inference.md)** | Async batch jobs with JSONL input, polling, result downloads, and up to 50% cost savings. | | **[Evaluations](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/evaluations.md)** | LLM-as-a-judge jobs that classify, score, or compare model outputs. | | **[Fine-tuning](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/fine-tuning.md)** | Low-rank adapter (LoRA), full, DPO preference, VLM, function-calling, and reasoning fine-tuning, plus bring-your-own-model uploads. | | **[Sandboxes](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/sandboxes.md)** | Remote stateful Python execution for agent-written code, data analysis, and charts. | | **[Dedicated model inference](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/dedicated-model-inference.md)** | Endpoints, deployments, and configs on dedicated GPUs, with autoscaling, traffic splitting, A/B tests, shadow experiments, metrics, custom model or LoRA uploads, and migration from the v1 endpoints API. | | **[Dedicated container inference](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/dedicated-containers.md)** | Custom Dockerized inference workers using the Jig CLI, Sprocket SDK, and queue API. | | **[GPU clusters](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/gpu-clusters.md)** | On-demand and reserved GPU clusters with Kubernetes or Slurm, shared storage, and credentials. | | **[Kueue](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/kueue.md)** | Quota-gated job queueing on a Together AI Kubernetes cluster. | | **[Volcano](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/volcano.md)** | All-or-nothing gang scheduling on a Together AI Kubernetes cluster. | | **[Together Link](https://github.com/togethercomputer/skills/blob/main/skills/together-ai/domains/togetherlink.md)** | Running Claude Code, Codex, OpenCode, Pi Code, Claude Desktop, or ChatGPT Desktop on Together AI models. | ### Single-area tasks Describe what you want, and the skill routes the agent to the matching domain guide. If you prompt your agent with: ```text theme={null} Build a multi-turn chatbot using Together AI with Kimi-K3 that can call a weather API and return structured JSON. ``` The agent opens the chat completions guide and generates correct SDK code with the right model ID, streaming setup, tool definitions, and the complete tool-call loop. ### Multi-area tasks For tasks that span several products, the agent reads each domain guide when it reaches that step. If you prompt your agent with: ```text theme={null} Fine-tune a model on my support tickets with Together AI, deploy it to a dedicated endpoint, then evaluate its answers with an LLM judge. ``` The agent works through three guides: 1. **Fine-tuning:** Validates and uploads the dataset, launches a LoRA job, and polls it to completion. 2. **Dedicated model inference:** Deploys the fine-tuned model and waits until the endpoint is ready. 3. **Evaluations:** Scores the endpoint's answers with an LLM judge and downloads the per-row results. See the [skills repository](https://github.com/togethercomputer/skills) for more workflow examples. ### SDK compatibility All generated code targets the Together Python SDK 2.x and the Together TypeScript SDK (`together-ai`) 0.x. Python SDK 3.0 and TypeScript SDK 1.0 moved or removed methods the skill still uses, such as `client.beta.endpoints` and `client.beta.clusters`, so pin the earlier versions in projects that run its code: ```bash theme={null} uv add "together>=2.0.0,<3" npm install "together-ai@<1" ``` If you're upgrading from v1, see the [Python v2 SDK migration guide](/docs/pythonv2-migration-guide). ## Docs MCP server [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) lets AI coding agents call external tools and pull in external data. The Together AI docs MCP server gives your agent direct access to this documentation site without leaving your editor. ### Install The fastest install is the universal `npx add-mcp` shortcut, which detects your active client and configures the server in one step. The other tabs cover client-specific install commands and manual configuration. > [tab] Universal > > ```bash theme={null} > npx add-mcp https://docs.together.ai/mcp > ``` > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http "TogetherAIDocs" https://docs.together.ai/mcp > ``` > [tab] Cursor > > [![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=together-docs\&config=eyJ1cmwiOiJodHRwczovL2RvY3MudG9nZXRoZXIuYWkvbWNwIn0%3D) > > For manual configuration, add this to your Cursor MCP settings: > > ```json theme={null} > { > "mcpServers": { > "together-docs": { > "url": "https://docs.together.ai/mcp" > } > } > } > ``` > [tab] VS Code > > [Install in VS Code](https://vscode.dev/redirect/mcp/install?name=Together%20AI%20Docs\&config=%7B%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fdocs.together.ai%2Fmcp%22%7D) > > For manual configuration, add this to your VS Code `settings.json`: > > ```json theme={null} > { > "mcp": { > "servers": { > "together-docs": { > "type": "http", > "url": "https://docs.together.ai/mcp" > } > } > } > } > ``` > [tab] Codex > > See the [Codex repository](https://github.com/openai/codex) for details. To connect to the remote server, add this to your Codex configuration: > > ```toml theme={null} > [mcp_servers.together_docs] > type = "http" > url = "https://docs.together.ai/mcp" > ``` > [tab] OpenCode > > Add this to your OpenCode configuration file: > > ```json theme={null} > { > "mcp": { > "together_docs": { > "type": "remote", > "url": "https://docs.together.ai/mcp", > "enabled": true > } > } > } > ``` ### Prompt examples Once installed, your agent can answer prompts like: * "Write a script to process data with batch inference." * "Build a simple chat app with Together AI's chat completions API." * "Find the best open-source model for frontier coding." * "How do I fine-tune a model on my own data?" The MCP server provides tools to search and retrieve documentation content, so your agent gets accurate answers without leaving your coding environment. ## Related resources > [card] [Skills repository on GitHub](https://github.com/togethercomputer/skills) > > Source, domain guides, references, and runnable scripts for the `together-ai` skill. > [card] [Together AI cookbook](https://github.com/togethercomputer/together-cookbook) > > End-to-end examples and tutorials. > [card] [Python v2 SDK migration guide](/docs/pythonv2-migration-guide) > > Breaking changes between the v1 and v2 SDKs. > [card] [Agent Skills specification](https://agentskills.io/specification) > > The open standard the skill follows. # Agno Source: https://docs.together.ai/docs/agno Use Agno with Together AI to build multimodal agents. Agno is an open-source library for creating multimodal agents. It supports interactions with text, images, audio, and video while remaining model-agnostic, allowing you to use any model in the Together AI library with this integration. ## Install libraries ```bash theme={null} uv add agno duckduckgo-search ``` ## Authentication Set your `TOGETHER_API_KEY` environment variable. ```shell Shell theme={null} export TOGETHER_API_KEY=*** ``` ## Example Below is an agent with access to web search. ```python Python theme={null} from agno.agent import Agent from agno.models.together import Together from agno.tools.duckduckgo import DuckDuckGoTools agent = Agent( model=Together(id="Qwen/Qwen3.5-9B"), tools=[DuckDuckGoTools()], markdown=True, ) agent.print_response("What's happening in New York?", stream=True) ``` ## Next steps > [!NOTE] > > ### Agno - Together AI Cookbook > > Explore the in-depth [Agno Cookbook](https://github.com/togethercomputer/together-cookbook/blob/main/agents/Agno/Agents_Agno.ipynb). # Evaluations Source: https://docs.together.ai/docs/ai-evaluations Use LLMs to classify, score, and compare model outputs on Together AI. > [!TIP] > > Using a coding agent? Install the [together-ai](https://github.com/togethercomputer/skills/tree/main/skills/together-ai) skill to let your agent write correct evaluation code automatically. [Learn more](/docs/agent-skills). The Together AI evaluations API allows you to use LLMs as a judge to assess the outputs of other models. You describe how the judge should assess each input, and the service runs the judgments across your dataset and returns aggregated results. You can evaluate Together AI [serverless models](/docs/evaluations-supported-models#serverless-models), models on your own [dedicated model inference](/docs/dedicated-endpoints/overview) endpoints, or external provider models such as OpenAI, Anthropic, and Google. Evaluations run from the [CLI or the SDKs](/docs/run-an-evaluation), or from the [web console](https://api.together.ai/evaluations). ## Evaluation types Every evaluation uses one of three types. Choose the type that matches the question you are trying to answer. ### Classify `classify` evaluations assign each input to one of the labels you define, such as `Toxic` and `Non-toxic`. You mark one or more labels as passing to get a pass percentage across the dataset. Use `classify` when you need a categorical judgment, for example when moderating content, enforcing policy compliance, detecting intent, or filtering and curating a dataset. ### Score `score` evaluations rate each input on a numeric scale that you define, such as 1 to 10. You set a pass threshold to get the percentage of inputs that meet a quality bar, along with the mean and standard deviation of scores. Use `score` when quality is a matter of degree rather than a category, for example when rating helpfulness, factuality, or writing quality. ### Compare `compare` evaluations judge two candidate responses for the same input and pick the better one, reporting how often each side wins and how often the judge finds a tie. By default, the judge runs twice with the candidate positions swapped to cancel out position bias. Use `compare` when you're running an A/B test between two models, two prompts, or two configurations of the same model. ## Datasets and templates Every evaluation runs over a dataset you upload as JSONL or CSV, where each row holds the same fields. Rows can carry a prompt to generate from, pre-generated responses to judge, or an `image_data_urls` column for vision inputs. Jinja2 templates connect your dataset to the models. The `input_template` injects dataset columns into the prompt sent to the model being evaluated, and the `system_template` gives the judge or the generating model its instructions. Every dataset column must be used by the job (referenced in a template, holding pre-generated responses, or carrying images). Jobs with unused columns fail validation. For the column rules, template syntax, and every parameter, see the [evaluations reference](/docs/evaluations-reference). ## Model sources Both the judge and the models being evaluated can come from three sources: * **Serverless:** A Together AI serverless model from the evaluations allowlist. * **Dedicated:** A [dedicated model inference](/docs/dedicated-endpoints/overview) endpoint you have deployed, referenced by its endpoint ID (`ep_abc123`). The endpoint needs a running deployment. * **External:** A model from an external provider, addressed with a shortcut or a custom OpenAI-compatible base URL. For the full list of supported serverless models and external shortcuts, see [Supported models](/docs/evaluations-supported-models). ## Pricing Evaluations bill only the serverless inference used by the job, at standard [serverless rates](https://www.together.ai/pricing). External models are billed by their provider through the API key you supply. Jobs run their requests concurrently. Completion time depends on dataset size, model size, and current capacity. Small jobs (under 1,000 samples) typically complete in under an hour. ## Next steps > [card] [Run an evaluation](/docs/run-an-evaluation) > > Prepare a dataset, launch a job, and download results with the API. > [card] [Parameters and results](/docs/evaluations-reference) > > Parameters, result formats, and template syntax. > [card] [Supported models](/docs/evaluations-supported-models) > > Serverless models and external provider shortcuts. # Build an AI search engine Source: https://docs.together.ai/docs/ai-search-engine Build an open source AI search engine inspired by Perplexity with Next.js and Together AI. [TurboSeek](https://www.turboseek.io/) is an app that answers questions using [Together AI’s](https://www.together.ai/) open-source LLMs. It pulls multiple sources from the web using Exa's API, then summarizes them to present a single answer to the user. ![](https://mintcdn.com/togetherai-52386018/nzLwcAOIrJYyQhDB/images/guides/4.png?fit=max\&auto=format\&n=nzLwcAOIrJYyQhDB\&q=85\&s=8e4b3476c21b5b285796f863c8ad8753) In this post, you’ll learn how to build the core parts of TurboSeek. The app is [open-source](https://github.com/Nutlope/turboseek/) and built with Next.js and Tailwind, but Together’s API can be used with any language or framework. ## Step 1: Build the input prompt TurboSeek’s core interaction is a text field where the user can enter a question: ![](https://mintcdn.com/togetherai-52386018/nzLwcAOIrJYyQhDB/images/guides/5.png?fit=max\&auto=format\&n=nzLwcAOIrJYyQhDB\&q=85\&s=5d3b06c25e24a4ed4f07a2c8ce3075f3) In our page, we’ll render an `` and control it using some new React state: ```jsx JSX theme={null} // app/page.tsx function Page() { let [question, setQuestion] = useState(''); return (
setQuestion(e.target.value)} placeholder="Ask anything" />
); } ``` When the user submits our form, we need to do two things: 1. Use the Exa API to fetch sources from the web. 2. Pass the text from the sources to an LLM to summarize and generate an answer. Let’s start by fetching the sources. We’ll wire up a submit handler to our form that makes a POST request to a new endpoint, `/getSources`: ```jsx JSX theme={null} // app/page.tsx function Page() { let [question, setQuestion] = useState(""); async function handleSubmit(e) { e.preventDefault(); let response = await fetch("/api/getSources", { method: "POST", body: JSON.stringify({ question }), }); let sources = await response.json(); // This fetch() will 404 for now } return (
setQuestion(e.target.value)} placeholder="Ask anything" />
); } ``` If we submit the form, we see our React app makes a request to `/getSources`: ![](https://mintcdn.com/togetherai-52386018/nzLwcAOIrJYyQhDB/images/guides/6.png?fit=max\&auto=format\&n=nzLwcAOIrJYyQhDB\&q=85\&s=5cf145f32811a6031de82c9f0e211e18) Our frontend is ready! Let’s add an API route to get the sources. ## Step 2: Get web sources with Exa To create our API route, we’ll make a new `app/api/getSources/route.js` file: ```jsx JSX theme={null} // app/api/getSources/route.js export async function POST(req) { let json = await req.json(); // `json.question` has the user's question } ``` We’re ready to send our question to Exa API to return back nine sources from the web. The [Exa API SDK](https://exa.ai/) lets you make a fetch request to get back search results including content, so we’ll use it to build up our list of sources: ```jsx JSX theme={null} // app/api/getSources/route.js import Exa from "exa-js"; import { NextResponse } from "next/server"; const exaClient = new Exa(process.env.EXA_API_KEY); export async function POST(req) { const json = await req.json(); const response = await exaClient.searchAndContents(json.question, { numResults: 9, type: "auto", }); return NextResponse.json( response.results.map((result) => ({ title: result.title || undefined, url: result.url, content: result.text })), ); } ``` In order to make a request to Exa API, you’ll need to get an [API key from Exa](https://exa.ai/). Once you have it, set it in `.env.local`: ```bash .env.local theme={null} EXA_API_KEY=xxxxxxxxxxxx ``` and our API handler should work. Let’s try it out from our React app! We’ll log the sources in our event handler: ```jsx JSX theme={null} // app/page.tsx function Page() { let [question, setQuestion] = useState(""); async function handleSubmit(e) { e.preventDefault(); let response = await fetch("/api/getSources", { method: "POST", body: JSON.stringify({ question }), }); let sources = await response.json(); // log the response from our new endpoint console.log(sources); } return (
setQuestion(e.target.value)} placeholder="Ask anything" />
); } ``` and if we try submitting a question, we’ll see an array of pages logged in the console! ![](https://mintcdn.com/togetherai-52386018/nzLwcAOIrJYyQhDB/images/guides/7.png?fit=max\&auto=format\&n=nzLwcAOIrJYyQhDB\&q=85\&s=9f509e066e9b0850ae3b9e8c50e9c8b2) Let’s create some new React state to store the responses and display them in our UI: ```jsx JSX theme={null} function Page() { let [question, setQuestion] = useState(""); let [sources, setSources] = useState([]); async function handleSubmit(e) { e.preventDefault(); let response = await fetch("/api/getSources", { method: "POST", body: JSON.stringify({ question }), }); let sources = await response.json(); // Update the sources with our API response setSources(sources); } return ( <>
setQuestion(e.target.value)} placeholder="Ask anything" />
{/* Display the sources */} {sources.length > 0 && (

Sources

)} ); } ``` If we try it out, our app is working great so far! We’re taking the user’s question, fetching nine relevant web sources from Exa, and displaying them in our UI. Next, let’s work on summarizing the sources. ## Step 3: Fetch the content from each source Now that our React app has the sources, we can send them to a second endpoint where we’ll use Together to summarize them into our final answer. Let’s add that second request to a new endpoint we’ll call `/api/getAnswer`, passing along the question and sources in the request body: ```jsx JSX theme={null} // app/page.tsx function Page() { // ... async function handleSubmit(e) { e.preventDefault(); const response = await fetch("/api/getSources", { method: "POST", body: JSON.stringify({ question }), }); const sources = await response.json(); setSources(sources); // Send the question and sources to a new endpoint const answerResponse = await fetch("/api/getAnswer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question, sources }), }); // The second fetch() will 404 for now } // ... } ``` If we submit a new question, we’ll see our React app make a second request to `/api/getAnswer`. Let’s create the second route! Make a new `app/api/getAnswer/route.js` file: ```jsx JSX theme={null} // app/api/getAnswer/route.js export async function POST(req) { let json = await req.json(); // `json.question` and `json.sources` has our data } ``` ## Step 4: Summarize the sources Now that we have the text content from each source, we can pass it along with a prompt to Together to get a final answer. Let’s install Together’s node SDK: ```bash theme={null} npm i together-ai ``` and use it to query Llama 3.1 8B Turbo: ```jsx JSX theme={null} import { Together } from "togetherai"; const together = new Together(); export async function POST(req) { const json = await req.json(); // Since exa already gave us the content of the pages we can simply use it const results = json.sources // Ask Together to answer the question using the results but limiting content // of each page to the first 10k characters to prevent overflowing context const systemPrompt = ` Given a user question and some context, please write a clean, concise and accurate answer to the question based on the context. You will be given a set of related contexts to the question. Please use the context when crafting your answer. Here are the set of contexts: ${results.map((result) => `${result.content.slice(0, 10_000)}\n\n`)} `; const runner = await together.chat.completions.stream({ model: "Qwen/Qwen3.5-9B", reasoning: { enabled: false }, messages: [ { role: "system", content: systemPrompt }, { role: "user", content: json.question }, ], }); return new Response(runner.toReadableStream()); } ``` Now we’re ready to read it in our React app! ## Step 5: Display the answer in the UI Back in our page, let’s create some new React state called `answer` to store the text from our LLM: ```jsx JSX theme={null} // app/page.tsx function Page() { const [answer, setAnswer] = useState(""); async function handleSubmit(e) { e.preventDefault(); const response = await fetch("/api/getSources", { method: "POST", body: JSON.stringify({ question }), }); const sources = await response.json(); setSources(sources); // Send the question and sources to a new endpoint const answerStream = await fetch("/api/getAnswer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question, sources }), }); } // ... } ``` We can use the `ChatCompletionStream` helper from Together’s SDK to read the stream and update our `answer` state with each new chunk: ```jsx JSX theme={null} // app/page.tsx import { ChatCompletionStream } from "together-ai/lib/ChatCompletionStream"; function Page() { const [answer, setAnswer] = useState(""); async function handleSubmit(e) { e.preventDefault(); const response = await fetch("/api/getSources", { method: "POST", body: JSON.stringify({ question }), }); const sources = await response.json(); setSources(sources); // Send the question and sources to a new endpoint const answerResponse = await fetch("/api/getAnswer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question, sources }), }); const runner = ChatCompletionStream.fromReadableStream(answerResponse.body); runner.on("content", (delta) => setAnswer((prev) => prev + delta)); } // ... } ``` Our new React state is ready! Let’s update our UI to display it: ```jsx JSX theme={null} function Page() { let [question, setQuestion] = useState(""); let [sources, setSources] = useState([]); async function handleSubmit(e) { // } return ( <>
setQuestion(e.target.value)} placeholder="Ask anything" />
{/* Display the sources */} {sources.length > 0 && (

Sources

)} {/* Display the answer */} {answer &&

{answer}

} ); } ``` If we try submitting a question, we’ll see the sources come in, and once our `getAnswer` endpoint responds with the first chunk, we’ll see the answer text start streaming into our UI! The core features of our app are working great. ## Digging deeper We’ve built out the main flow of our app using just two endpoints: one that blocks on an API request to Exa AI, and one that returns a stream using Together’s Node SDK. React and Next.js were a great fit for this app, giving us all the tools and flexibility we needed to make a complete full-stack web app with secure server-side logic and reactive client-side updates. [TurboSeek](https://www.turboseek.io/) is fully open-source and has even more features like suggesting similar questions, so if you want to keep working on the code from this tutorial, be sure to check it out on GitHub: [https://github.com/Nutlope/turboseek/](https://github.com/Nutlope/turboseek/) And if you’re ready to add streaming LLM features like the chat completions we saw above to your own apps, [sign up for Together AI today](https://www.together.ai/), get \$5 for free to start out, and make your first query in minutes! *** # Build an interactive AI tutor Source: https://docs.together.ai/docs/ai-tutor Create LlamaTutor from scratch, an open source AI tutor with 90k users. [LlamaTutor](https://llamatutor.together.ai/) is an app that creates an interactive tutoring session for a given topic using [Together AI’s](https://www.together.ai/) open-source LLMs. ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/25.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=dd9838164e399ad4ba65028af3ce2793) It pulls multiple sources from the web with the [Exa](https://exa.ai/) search API, then uses the text from the sources to kick off an interactive tutoring session with the user. ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/26.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=83d3d4d158ada52cab0ab2471f09faa2) In this post, you’ll learn how to build the core parts of LlamaTutor. The app is open-source and built with Next.js and Tailwind, but Together’s API works great with any language or framework. ## Building the input prompt and education dropdown LlamaTutor’s core interaction is a text field where the user can enter a topic, and a dropdown that lets the user choose which education level the material should be taught at: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/27.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=e733787a865a226113fd4ee32bbc2564) In the main page component, we’ll render an `` and ` setTopic(e.target.value)} placeholder="Teach me about..." /> ); } ``` When the user submits our form, our submit handler ultimately needs to do three things: 1. Use the Exa API to fetch six different websites related to the topic. 2. Parse the text from each website. 3. Pass all the parsed text, as well as the education level, to Together AI to kick off the tutoring session. Let’s start by fetching the websites with Exa. We’ll wire up a submit handler to our form that makes a POST request to a new `/getSources` endpoint: ```jsx JSX theme={null} // app/page.tsx function Page() { const [topic, setTopic] = useState(''); const [grade, setGrade] = useState(''); async function handleSubmit(e) { e.preventDefault(); let response = await fetch('/api/getSources', { method: 'POST', body: JSON.stringify({ topic }), }); let sources = await response.json(); // This fetch() will 404 for now } return (
setTopic(e.target.value)} placeholder="Teach me about..." />
); } ``` If we submit the form, we see our React app makes a request to `/getSources`: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/28.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=92e5573388f6bd84d025eb6c79eaf062) Let’s go implement this API route. ## Getting web sources with Exa To create our API route, we’ll make a new `app/api/getSources/route.js` file: ```jsx JSX theme={null} // app/api/getSources/route.js export async function POST(req) { let json = await req.json(); // `json.topic` has the user's text } ``` The [Exa API](https://exa.ai/) lets you make a fetch request to get back search results, so we’ll use it to build up our list of sources: ```jsx JSX theme={null} // app/api/getSources/route.js import { NextResponse } from 'next/server'; export async function POST(req) { const json = await req.json(); const response = await fetch('https://api.exa.ai/search', { method: 'POST', headers: { 'x-api-key': process.env['EXA_API_KEY'], 'Content-Type': 'application/json', }, body: JSON.stringify({ query: json.topic, numResults: 6, type: 'auto', }), }); const { results } = await response.json(); return NextResponse.json( results.map((result) => ({ name: result.title, url: result.url, })) ); } ``` In order to make a request to Exa's API, you'll need to [get an API key from Exa](https://dashboard.exa.ai/api-keys). Once you have it, set it in `.env.local`: ```jsx JSX theme={null} // .env.local EXA_API_KEY=xxxxxxxxxxxx ``` and our API handler should work. Let’s try it out from our React app! We’ll log the sources in our submit handler: ```jsx JSX theme={null} // app/page.tsx function Page() { const [topic, setTopic] = useState(''); const [grade, setGrade] = useState(''); async function handleSubmit(e) { e.preventDefault(); const response = await fetch('/api/getSources', { method: 'POST', body: JSON.stringify({ topic }), }); const sources = await response.json(); // log the response from our new endpoint console.log(sources); } return (
setTopic(e.target.value)} placeholder="Teach me about..." />
); } ``` and if we try submitting a topic, we’ll see an array of pages logged in the console! ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/29.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=9f0c9b3b0f6228e07bea418c5353b3b5) Let’s create some new React state to store the responses and display them in our UI: ```jsx JSX theme={null} // app/page.tsx function Page() { const [topic, setTopic] = useState(''); const [grade, setGrade] = useState(''); const [sources, setSources] = useState([]); async function handleSubmit(e) { e.preventDefault(); const response = await fetch('/api/getSources', { method: 'POST', body: JSON.stringify({ topic }), }); const sources = await response.json(); // Update the sources with our API response setSources(sources); } return ( <>
{/* ... */}
{/* Display the sources */} {sources.length > 0 && (

Sources

)} ); } ``` If we try it out, our app is working great so far! ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/30.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=ce32b4be67a3087fd6e054e52b65d231) We’re taking the user’s topic, fetching six relevant web sources from Exa, and displaying them in our UI. Next, let’s get the text content from each website so that our AI model has some context for its first response. ## Fetching the content from each source Let’s make a request to a second endpoint called `/api/getParsedSources`, passing along the sources in the request body: ```jsx JSX theme={null} // app/page.tsx function Page() { // ... async function handleSubmit(e) { e.preventDefault(); const response = await fetch('/api/getSources', { method: 'POST', body: JSON.stringify({ question }), }); const sources = await response.json(); setSources(sources); // Send the sources to a new endpoint const parsedSourcesRes = await fetch('/api/getParsedSources', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sources }), }); // The second fetch() will 404 for now } // ... } ``` We’ll create a file at `app/api/getParsedSources/route.js` for our new route: ```jsx JSX theme={null} // app/api/getParsedSources/route.js export async function POST(req) { let json = await req.json(); // `json.sources` has the websites from Exa } ``` Now we’re ready to actually get the text from each one of our sources. Let’s write a new `getTextFromURL` function and outline our general approach: ```jsx JSX theme={null} async function getTextFromURL(url) { // 1. Use fetch() to get the HTML content // 2. Use the `jsdom` library to parse the HTML into a JavaScript object // 3. Use `@mozilla/readability` to clean the document and // return only the main text of the page } ``` Let’s implement this new function. We’ll start by installing the `jsdom` and `@mozilla/readability` libraries: ```bash theme={null} npm i jsdom @mozilla/readability ``` Next, let’s implement the steps: ```jsx JSX theme={null} async function getTextFromURL(url) { // 1. Use fetch() to get the HTML content const response = await fetch(url); const html = await response.text(); // 2. Use the `jsdom` library to parse the HTML into a JavaScript object const virtualConsole = new jsdom.VirtualConsole(); const dom = new JSDOM(html, { virtualConsole }); // 3. Use `@mozilla/readability` to clean the document and // return only the main text of the page const { textContent } = new Readability(doc).parse(); } ``` Looks good - let’s try it out! We’ll run the first source through `getTextFromURL`: ```jsx JSX theme={null} // app/api/getParsedSources/route.js export async function POST(req) { let json = await req.json(); let textContent = await getTextFromURL(json.sources[0].url); console.log(textContent); } ``` If we submit our form, we’ll see the text show up in our server terminal from the first page! ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/31.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=aafd49af898764f983d6129e351e7f15) Let’s update the code to get the text from all the sources. Since each source is independent, we can use `Promise.all` to kick off our functions in parallel: ```jsx JSX theme={null} // app/api/getAnswer/route.js export async function POST(req) { let json = await req.json(); let results = await Promise.all( json.sources.map((source) => getTextFromURL(source.url)) ); console.log(results); } ``` If we try again, we’ll now see an array of each web page’s text logged to the console: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/32.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=5e5eb89322d2bde318831fc0891c9ea4) We’re ready to use the parsed sources in our React frontend! ## Using the sources for the chatbot’s initial messages Back in our React app, we now have the text from each source in our submit handler: ```jsx JSX theme={null} // app/page.tsx function Page() { // ... async function handleSubmit(e) { e.preventDefault(); const response = await fetch('/api/getSources', { method: 'POST', body: JSON.stringify({ question }), }); const sources = await response.json(); setSources(sources); const parsedSourcesRes = await fetch('/api/getParsedSources', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sources }), }); // The text from each source const parsedSources = await parsedSourcesRes.json(); } // ... } ``` We’re ready to kick off our chatbot. We’ll use the selected grade level and the parsed sources to write a system prompt, and pass in the selected topic as the user’s first message: ```jsx JSX theme={null} // app/page.tsx function Page() { const [messages, setMessages] = useState([]); // ... async function handleSubmit(e) { // ... // The text from each source const parsedSources = await parsedSourcesRes.json(); // Start our chatbot const systemPrompt = ` You're an interactive personal tutor who is an expert at explaining topics. Given a topic and the information to teach, please educate the user about it at a ${grade} level. Here's the information to teach: ${parsedSources.map( (result, index) => `## Webpage #${index}:\\n ${result.fullContent} \\n\\n` )} `; const initialMessages = [ { role: 'system', content: systemPrompt }, { role: 'user', content: topic }, ]; setMessages(initialMessages); // This will 404 for now const chatRes = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: initialMessages }), }); } // ... } ``` We also created some new React state to store all the messages so that we can display and update the chat history as the user sends new messages. We’re ready to implement our final API endpoint at `/chat`! ## Implementing the chatbot endpoint with Together AI’s SDK Let’s install Together AI’s node SDK: ```bash theme={null} npm i together-ai ``` and use it to query Qwen3.5 9B: ```jsx JSX theme={null} // api/chat/route.js import Together from 'together-ai'; const together = new Together(); export async function POST(req) { const json = await req.json(); const res = await together.chat.completions.create({ model: 'Qwen/Qwen3.5-9B', reasoning: { enabled: false }, messages: json.messages, stream: true, }); return new Response(res.toReadableStream()); } ``` Since we’re passing the array of messages directly from our React app, and the format is the same as what Together’s `chat.completions.create` method expects, our API handler is mostly acting as a simple passthrough. We’re also using the `stream: true` option so our frontend will be able to show partial updates as soon as the LLM starts its response. We’re ready to display our chatbot’s first message in our React app! ## Displaying the chatbot’s response in the UI Back in our page, we’ll use the `ChatCompletionStream` helper from Together’s SDK to update our `messages` state as our API endpoint streams in text: ```jsx JSX theme={null} // app/page.tsx function Page() { const [messages, setMessages] = useState([]); // ... async function handleSubmit(e) { // ... const chatRes = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: initialMessages }), }); ChatCompletionStream.fromReadableStream(chatRes.body).on( 'content', (delta) => { setMessages((prev) => { const lastMessage = prev[prev.length - 1]; if (lastMessage.role === 'assistant') { return [ ...prev.slice(0, -1), { ...lastMessage, content: lastMessage.content + delta }, ]; } else { return [...prev, { role: 'assistant', content: delta }]; } }); } ); } // ... } ``` Note that because we’re storing the entire history of messages as an array, we check the last message’s `role` to determine whether to append the streamed text to it, or push a new object with the assistant’s initial text. Now that our `messages` React state is ready, let’s update our UI to display it: ```jsx JSX theme={null} // app/page.tsx function Page() { const [topic, setTopic] = useState(''); const [grade, setGrade] = useState(''); const [sources, setSources] = useState([]); const [messages, setMessages] = useState([]); async function handleSubmit(e) { // ... } return ( <>
{/* ... */}
{/* Display the sources */} {sources.length > 0 && (

Sources

)} {/* Display the messages */} {messages.map((message, i) => (

{message.content}

))} ); } ``` If we try it out, we’ll see the sources come in, and once our `chat` endpoint responds with the first chunk, we’ll see the answer text start streaming into our UI! ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/33.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=6524178a639503751c16dc713afb81a4) ## Letting the user ask follow-up questions To let the user ask our tutor follow-up questions, let’s make a new form that only shows up once we have some messages in our React state: ```jsx JSX theme={null} // app/page.tsx function Page() { // ... const [newMessageText, setNewMessageText] = useState(''); return ( <> {/* Form for initial messages */} {messages.length === 0 && (
{/* ... */}
)} {sources.length > 0 && <>{/* ... */}} {messages.map((message, i) => (

{message.content}

))} {/* Form for follow-up messages */} {messages.length > 0 && (
setNewMessageText(e.target.value)} type="text" />
)} ); } ``` We’ll make a new submit handler called `handleMessage` that will look a lot like the end of our first `handleSubmit` function: ```jsx JSX theme={null} // app/page.tsx function Page() { const [messages, setMessages] = useState([]); // ... async function handleMessage(e) { e.preventDefault(); const newMessages = [ ...messages, { role: 'user', content: newMessageText, }, ]; const chatRes = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: newMessages }), }); setMessages(newMessages); ChatCompletionStream.fromReadableStream(chatRes.body).on( 'content', (delta) => { setMessages((prev) => { const lastMessage = prev[prev.length - 1]; if (lastMessage.role === 'assistant') { return [ ...prev.slice(0, -1), { ...lastMessage, content: lastMessage.content + delta }, ]; } else { return [...prev, { role: 'assistant', content: delta }]; } }); } ); } // ... } ``` Because we have all the messages in React state, we can create a new object for the user’s latest message, send it over to our existing `chat` endpoint, and reuse the same logic to update our app’s state as the latest response streams in. The core features of our app are working great! ## Digging deeper React and Together AI are a perfect match for building powerful chatbots like LlamaTutor. The app is fully open-source, so if you want to keep working on the code from this tutorial, be sure to check it out on GitHub: [https://github.com/Nutlope/llamatutor](https://github.com/Nutlope/llamatutor) And if you’re ready to start building your own chatbots, [sign up for Together AI today](https://www.together.ai/) and make your first query in minutes! *** # Authentication Source: https://docs.together.ai/docs/api-keys-authentication Create, manage, and authenticate with project-scoped API keys. Together AI uses API keys to authenticate requests. Keys are scoped to [projects](/docs/projects), meaning a key only has access to the resources within its project. ## Create an API key Create independent API keys for separate use cases, systems, or workloads. For example, one for production, one for development, one for CI/CD, and one for inference. **1. Open the project** Navigate to the project you want to create a key for. **2. Open API key settings** Go to the project's [API keys settings](https://api.together.ai/settings/projects/~current/api-keys). **3. Create the key** Select **Create API Key** and enter a name. To make the key expire automatically, select **Set an expiration date** and choose a preset or custom date. Then select **Create**. **4. Copy the key** Copy the key immediately. It won't be shown again. > [!WARNING] > > New API keys are displayed only once at creation. Save them in a secure location, such as a secrets manager, immediately. If you lose a key, you'll need to create a new one. ## Revoke API keys A revoked key stops working within about five minutes and can't be restored. Before you revoke a key, check the **Last used** column in the project's [API keys settings](https://api.together.ai/settings/projects/~current/api-keys). It shows how long ago the key was last used, or **Never**. Hover the info icon for the exact date. * **One key:** Open the three-dot menu on the key's row and select **Revoke key**. * **Several keys:** Select each key's checkbox, or the header checkbox to select every listed key. Then select **Revoke *N* keys**. You can revoke up to 100 keys at once, and you can't select legacy or expired keys. To confirm, enter `I understand` and select **Revoke**. If the key was used in the past 24 hours, the dialog warns you first. Revoked keys show a **Revoked** status and are hidden by the default **Status: Active** filter. ## Best practices * **Name your keys descriptively** (for example, `prod-inference`, `ci-pipeline`, `dev-local`) so you can identify and rotate them. * **Set expiration dates** for keys used in temporary or testing contexts. Select **Set an expiration date** when creating a key, or **Set expiration** in the three-dot menu next to an existing key. To keep a key that's scheduled to expire, select **Cancel expiration** from the same menu. * **Rotate keys regularly** and [revoke](#revoke-api-keys) any that are no longer in use. * **Never commit keys to source control:** Use environment variables or a secrets manager. * **Treat keys as secrets:** Anyone holding a key has full access to its project's resources and can spend your credit balance, which auto-recharge tops back up. If you suspect a key has leaked, revoke it immediately and create a new one. ## Set as an environment variable The Together Python and TypeScript SDKs read your key from the `TOGETHER_API_KEY` environment variable. Set it in your shell: ```bash macOS / Linux theme={null} export TOGETHER_API_KEY="your_api_key" ``` ```powershell Windows (PowerShell) theme={null} $env:TOGETHER_API_KEY="your_api_key" ``` If your project loads environment variables from a `.env` file, add it there: ```dotenv .env theme={null} TOGETHER_API_KEY=your_api_key ``` > [!TIP] > > To authenticate the Together CLI, [log in with `tg login`](/reference/cli/auth) instead of setting an API key. ## Authenticate a request Include your API key in the `Authorization` header of every API request: ```bash theme={null} curl https://api.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "meta-models/Muse-Glimmer-30B", "messages": [{"role": "user", "content": "Hello"}] }' ``` ## Project key scoping API keys are scoped to projects: * A key created in project A can only access resources in project A. * Keys persist even if the collaborator who created them is removed from the project. * Both project admins and member-role collaborators can create and revoke keys. This means you can safely share a project API key with a CI/CD pipeline or external collaborator without giving them access to resources in other projects. > [!NOTE] > > Keys created before multi-project support was enabled are scoped to your organization's default project. ## Playground The [Together AI playground](https://api.together.ai/playground/) recognizes all API keys associated with your account. When you use the playground, it shows available models across all your keys and projects. ## Cost analytics and usage Use API key IDs to segment usage and cost by key and workload. The `api_key_id` field is supported for inference requests, so you can track which keys are driving spend in your [project's cost analytics](https://api.together.ai/settings/projects/~current/cost-analytics). ## Limitations **No per-key usage limits:** You can't cap spend or rate-limit individual API keys. Usage limits apply at the organization level. ## Vercel integration When you connect a Vercel project from [Integrations settings](https://api.together.ai/settings/integrations), each linked Vercel project gets its own dedicated API key. Together creates the key in your organization's default project and sets it as the `TOGETHER_API_KEY` environment variable in the Vercel project. Manage or revoke these keys from the default project's [API keys settings](https://api.together.ai/settings/projects/~current/api-keys), like any other key. Disconnecting a Vercel project removes the environment variable from Vercel but doesn't revoke the key. > [!NOTE] > > This is the Together AI console Vercel integration, not the npm [AI SDK provider](/docs/using-together-with-vercels-ai-sdk). ## Legacy API keys Your organization may have a legacy API key scoped to its default project. It appears in that project's [API keys settings](https://api.together.ai/settings/projects/~current/api-keys) with a **Deprecated** badge. Legacy keys are deprecated, and you should **avoid using them in production.** These keys can't be scoped to a specific project or workload. Use [project-scoped API keys](#create-an-api-key) instead. Legacy keys can't be regenerated, renamed, or given an expiration date. To replace a legacy key, create a project-scoped key, move your applications to it, then open the three-dot menu on the legacy key's row and select **Revoke key**. ## Related resources > [card] [Projects](/docs/projects) > > Understand how API keys are scoped to projects. > [card] [Roles and permissions](/docs/roles-permissions) > > See who can create and manage API keys. # AutoGen(AG2) Source: https://docs.together.ai/docs/autogen Use AutoGen (AG2) to build and orchestrate AI agents with Together AI models. AG2 (formerly AutoGen) is an open-source framework for building and orchestrating AI agents. It focuses on enabling multiple agents to cooperate in solving complex tasks. The framework supports various language models from Together AI, tool integrations, and both autonomous and human-in-the-loop workflows. ## Install libraries ```shell Shell theme={null} uv add autogen ``` Set your Together API key: ```shell Shell theme={null} export TOGETHER_API_KEY=*** ``` ## Example Set up and configure AutoGen to use LLMs from Together AI. ```python Python theme={null} import os config_list = [ { # Let's choose the Llama 3.3 70B model "model": "meta-models/Muse-Glimmer-30B", # Provide your Together.AI API key here or put it into the TOGETHER_API_KEY environment variable. "api_key": os.environ.get("TOGETHER_API_KEY"), # Specify the API Type as 'together' so it uses the Together.AI client class "api_type": "together", "stream": False, } ] ``` Importantly, we have tweaked the system message so that the model doesn't return the termination keyword, which we've changed to FINISH, with the code block. ```python Python theme={null} from pathlib import Path from autogen import AssistantAgent, UserProxyAgent from autogen.coding import LocalCommandLineCodeExecutor # Setting up the code executor workdir = Path("coding") workdir.mkdir(exist_ok=True) code_executor = LocalCommandLineCodeExecutor(work_dir=workdir) # Setting up the agents # The UserProxyAgent will execute the code that the AssistantAgent provides user_proxy_agent = UserProxyAgent( name="User", code_execution_config={"executor": code_executor}, is_termination_msg=lambda msg: "FINISH" in msg.get("content"), ) system_message = """You are a helpful AI assistant who writes code and the user executes it. Solve tasks using your coding and language skills. In the following cases, suggest python code (in a python coding block) for the user to execute. Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill. When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user. If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try. When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible. IMPORTANT: Wait for the user to execute your code and then you can reply with the word "FINISH". DO NOT OUTPUT "FINISH" after your code block.""" # The AssistantAgent, using Together.AI's Code Llama model, will take the coding request and return code assistant_agent = AssistantAgent( name="Together Assistant", system_message=system_message, llm_config={"config_list": config_list}, ) # Start the chat, with the UserProxyAgent asking the AssistantAgent the message chat_result = user_proxy_agent.initiate_chat( assistant_agent, message="Provide code to count the number of prime numbers from 1 to 10000.", ) ``` ## Output ````text theme={null} User (to Together Assistant): Provide code to count the number of prime numbers from 1 to 10000. -------------------------------------------------------------------------------- Together Assistant (to User): ```python def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True count = 0 for num in range(1, 10001): if is_prime(num): count += 1 print(count) ``` This code defines a helper function `is_prime(n)` to check if a number `n` is prime. It then iterates through numbers from 1 to 10000, checks if each number is prime using the helper function, and increments a counter if it is. Finally, it prints the total count of prime numbers found. -------------------------------------------------------------------------------- ```` # Cost analytics Source: https://docs.together.ai/docs/billing-cost-analytics Track daily Together AI spend and billable units by product, line item, project, or API key. The cost analytics dashboard charts your daily spend or billable units, such as tokens, so you can see which products, projects, and API keys drive your usage over time. ![Project cost analytics page showing daily cost grouped by product](https://mintcdn.com/togetherai-52386018/7SPYs5brFN4wuyRD/images/billing-cost-analytics.png?fit=max\&auto=format\&n=7SPYs5brFN4wuyRD\&q=85\&s=b19600a82e3acc545f7d483b91d83534) ## Open cost analytics * **Organization:** Open [organization cost analytics](https://api.together.ai/settings/organization/~current/cost-analytics) to see spend across every project. Only organization admins can view this page. * **Project:** Open your [project's cost analytics page](https://api.together.ai/settings/projects/~current/cost-analytics) to scope the view to a single project. Project cost analytics is in early access, and not all products attribute usage to a project yet, so project totals can be incomplete. External collaborators can't view it. To see usage for the current billing period, open your [billing settings](https://api.together.ai/settings/organization/~current/billing) and select **See current monthly invoice usage** on the **Monthly spend** card. ## Choose a measure and grouping Use **Measure** to choose what the chart shows: * **Cost (\$):** Daily spend in US dollars. This is the default. * **Units:** Daily billable units, such as tokens. Totals and tooltips show unit counts instead of dollar amounts. Use **Group by** to break the chart down: * **Product:** Each product, such as serverless inference or storage. * **Line items:** Each billable line item. * **Project (beta):** Each project in your organization. Available on organization cost analytics only. * **API key (beta):** Each API key. With **Units**, grouping by product, project, or API key adds up the unit counts of every line item in the group. Group by **Line items** to see each item's count on its own. ## Filter and set the time range * **Filter:** Include or exclude specific series from the current grouping. The filter shows **All usage** until you apply one. Filtering isn't available when you group by line items. * **Time range:** Choose **Yesterday**, **Last 7 Days**, or **Last 30 Days** (the default), or pick start and end dates on the calendar. A range can cover up to 31 days. All dates are in UTC. The total in the top right covers all usage in the selected period, even when a filter hides some of it from the chart. When you group by project or API key, the chart leaves out usage that isn't attributed to one, but the total still includes it. ## Review line items The **Breakdown** table below the chart lists every billable line item for each day in the selected time range, with its quantity, unit price, and amount. It always shows all line items for the time range, regardless of the chart's **Measure**, **Group by**, and **Filter** settings. * **Search:** Find line items by name or by the attributes listed under each name. * **Sort:** Sort rows by quantity, unit price, or amount. * **Download CSV:** Export every line item in the time range, including rows hidden by your search. The file has `Date`, `Line Item`, `Dimensions`, `Quantity`, `Unit Price (USD)`, and `Amount (USD)` columns. ## Next steps > [card] [Spend controls](/docs/billing-spend-controls) > > Cap spend, set up auto-recharge, and trace a spend increase to its source. > [card] [Billing usage API](/reference/billing-usage) > > Pull cost-annotated usage line items into your own reporting. # Credits Source: https://docs.together.ai/docs/billing-credits Understand credits and billing basics on Together AI. ## What are credits used for? Together credits are the unit used to measure and charge for usage of Together AI services on your account. Once purchased, credits can be used immediately for: * API requests. * Dedicated model inference. * Fine-tuning jobs. * Evaluation jobs. * All other Together AI services. You need enough balance to cover the cost of creating a dedicated endpoint, fine-tuning job, or evaluation job. ## Free trial and access requirements Together AI does not currently offer free trials. Access to the Together platform requires a minimum \$15 credit purchase. Together AI is **fully prepaid**. You need a positive credit balance to use the platform. Add credits from your [billing settings](https://api.together.ai/settings/organization/~current/billing) before making API calls. If your balance reaches zero, API access is suspended until you add credits. Customers with an active Scale or Enterprise contract continue to be billed under their existing contract terms. See [Spend controls](/docs/billing-spend-controls) for balance cut-offs, cost attribution, and monitoring options. ## Buy credits 1. Go to your [billing settings](https://api.together.ai/settings/organization/~current/billing). 2. In the **Credit balance** card, select **Add credits**. 3. Enter an amount and confirm. The minimum is \$15 for your organization's first purchase and \$5 after that. The purchase uses your [default payment method](/docs/billing-payment-methods). Credits from card purchases usually appear in your balance within a few moments. Avoid re-submitting the purchase while it's pending. Automated Clearing House (ACH) purchases deposit credits only after the payment clears, usually 1–3 business days. ## Auto-recharge credits Together supports automatic credit purchases when your balance falls below a set threshold. When auto-recharge runs, your **default** payment method is charged in a **single transaction** to bring your balance up to your target. **Auto-recharge and ACH:** Auto-recharge is available only when your default payment method is a credit or debit card. If your default is a US bank account (ACH), auto-recharge is not available, even if you also have a card saved. If a card is your default, auto-recharge works normally even when ACH is also on file. Setting ACH as default turns auto-recharge off automatically. To enable auto-recharge: 1. Go to your [billing settings](https://api.together.ai/settings/organization/~current/billing). 2. In the **Auto-recharge** panel, select **Set thresholds** (or **Edit limits** if auto-recharge is already configured). 3. Enable automatic credit purchases and set: * **When balance goes below:** The balance at which auto-recharge is triggered. * **Bring credit balance up to:** The target balance after auto-recharge runs. You are charged the amount needed to reach this target. 4. Save your settings. Note: If you set a threshold above your current balance, auto-recharge triggers immediately with one purchase to bring your balance up to your target. Manual credit purchases also use your [default payment method](/docs/billing-payment-methods). ## Credit expiration No, prepaid balance credits in your Together AI account do not currently have an expiration date. You can use your credits at any time after purchase. If any changes to this policy are made in the future, Together AI will notify customers in advance through official communications. Everyone's circumstances are different, and no customer should ever be put in a tricky situation by an unexpected bill. To help avoid such a situation, Together AI offers usage-based billing and credit packs, which are charged at the time of purchase. **Important:** Credits purchased after an invoice is generated cannot be used to clear previous invoices or past-due balances. Past-due balances must be paid separately using a valid payment method, regardless of your available credit balance. If you're experiencing access issues with a positive balance, check whether your credits are free credits or purchased credits. Platform access requires the minimum \$15 credit purchase described above. # Payment methods & invoices Source: https://docs.together.ai/docs/billing-payment-methods Managing payment cards, ACH transfers, viewing invoices, and updating billing details. ## Supported payment methods Together AI supports two payment methods to fund your account: * **Credit and debit cards:** Accepted from all major networks (Visa, Mastercard, American Express). * **ACH bank transfers:** Pay directly from a U.S. bank account. *** ## Credit and debit cards Together AI accepts all major credit and debit cards on networks including Visa, Mastercard, and American Express. Prepaid cards are not supported. > [!NOTE] > > In some territories, banks require authorization for every transaction. Together AI sends an authorization link to your account's registered email. Approve these promptly to avoid credit purchase failures. ### Managing payment methods You can save **multiple payment methods** on an organization, for example a US bank account (ACH) and one or more credit cards. Choose which method is **default**. Credit purchases and auto-recharge (if enabled) use the default. 1. Go to your [billing settings](https://api.together.ai/settings/organization/~current/billing). 2. In the **Payment method** panel, select **Manage payment methods**. 3. Add a card or bank account, set a **default** method, or remove methods you no longer need. **Requirements:** * You must always keep **at least one valid credit or debit card** on file (even if ACH is your default payment method). * You cannot remove the default method until you set another method as default. * You cannot set an expired card as default. ### Invoice address Your **invoice address** is separate from the address collected when you add a payment method. It is used for invoices and tax. 1. Go to your [billing settings](https://api.together.ai/settings/organization/~current/billing). 2. In the **Invoice address** panel, select **Edit** (or **Add** if no address is on file). 3. Update the address and save. You can change your invoice address without updating your payment methods. The Tax ID field appears after you enter address information. **Note:** If you need to add your organization name, add a different email address to receive invoices, or add a non-standard Tax ID format, contact [Support](https://portal.usepylon.com/together-ai/forms/support-request) for assistance. These changes cannot be made through the billing settings interface. *** ## ACH bank transfers ACH (Automated Clearing House) payments let you purchase Together AI credits directly from your U.S. bank account. Use ACH for large purchases or when you hit credit card limits. You can purchase up to \$50,000 per transaction, or \$100,000 if your organization has a Scale or Enterprise contract. ### Adding a bank account Together AI supports most U.S. financial institutions with instant verification. Link a bank account from billing settings: 1. Go to your [Billing settings](https://api.together.ai/settings/organization/~current/billing). 2. In the **Payment method** panel, select **Manage payment methods** (or **Add payment method** if no method is on file). 3. Select **Add payment method**, then choose **US Bank Account**. 4. Enter your email and full name. 5. Search for or select your bank and follow the on-screen steps to authorize your account. 6. Enter your billing address. 7. Select **Save Payment Method**. > [!NOTE] > > Only U.S. financial institutions that support instant verification are available right now. Manual entry of routing and account numbers is not supported. ### Purchasing credits Once your bank account is linked, start a purchase from your [Billing settings](https://api.together.ai/settings/organization/~current/billing) the same way you would with a card: 1. Select **Add Credits** in the Credits Balance block. 2. Enter an amount and confirm. Credits are **not** deposited until the ACH payment clears. Settlement usually takes **1–3 business days**, but can take longer depending on your bank. Until then, the purchase shows as pending and your balance does not increase. If the payment fails, no credits are deposited. Contact [Support](https://portal.usepylon.com/together-ai/forms/support-request) if you need help with a failed transaction. ### Things to know * **Default method controls charges:** Credit purchases use whichever payment method is marked default. You can keep both cards and a bank account on file and switch the default as needed. * **Auto-recharge requires a card:** Auto-recharge only works when your default payment method is a credit or debit card. If you set a US bank account as default, auto-recharge is turned off automatically. * **Keep at least one valid card on file:** Your organization must always have at least one valid credit or debit card saved, even when ACH is set as default. * **Failed payments:** If an ACH payment fails, no credits are deposited. Contact [Support](https://portal.usepylon.com/together-ai/forms/support-request) if you have questions about a failed transaction. ### Troubleshooting **My bank isn't showing up in the list.** Only U.S. banks that support instant verification are currently available. If your institution isn't listed, try searching by name or contact [Support](https://portal.usepylon.com/together-ai/forms/support-request). **I got an error during bank selection.** This can happen if your bank is temporarily unable to verify the account link. Contact [Support](https://portal.usepylon.com/together-ai/forms/support-request) for help investigating. **I got an error after selecting Save.** Try refreshing the page and attempting again. If the issue persists, reach out to [Support](https://portal.usepylon.com/together-ai/forms/support-request) with any error details. *** ## Viewing previous invoices All of your previous invoices (and current usage) can be viewed and downloaded in your [billing settings](https://api.together.ai/settings/organization/~current/billing). Scroll down to billing history. Note that you may receive \$0 invoices even when using free or pre-purchased credits. These provide a record of your usage, including tokens used and models accessed. You can download the invoice PDF for details. ## Adding business details to invoices You can add your business name or other details to your invoices. Unfortunately this can't be done through your billing settings at the moment, so reach out to Support and they'll get it sorted for you! # Spend controls Source: https://docs.together.ai/docs/billing-spend-controls Manage Together AI spend with balance cut-offs, auto-recharge, cost attribution, and programmatic monitoring. Together AI provides balance cut-offs to stop API access, auto-recharge to keep prepaid workloads funded, and cost analytics to investigate spend. Your [organization](/docs/organizations) is the billing boundary: usage across its projects and members is billed to the organization. ## Methods for controlling spend | Control | What it does | Availability | | - | - | - | | Hard cut-off at \$0 | Stops API access when the prepaid balance reaches zero. | Prepaid accounts. | | In-arrears cut-off | Pauses access when usage passes an agreed negative balance. | Qualifying contracted enterprise accounts. | | Auto-recharge | Purchases credits before the balance runs out. | Prepaid accounts with a credit or debit card as the default payment method. | | Serverless access | Turns serverless inference off or on. | Contracted accounts, through your solutions architect. | Organization and project budgets and spend alerts are [coming soon](#coming-soon-budgets-and-alerts). To monitor usage and costs, use [cost analytics](/docs/billing-cost-analytics). ### Hard cut-off at \$0 If you don't have a sales contract with Together AI, your account runs on [prepaid credits](/docs/billing-credits). API access stops when your organization's balance reaches zero and resumes after you add credits. Customers with a sales contract continue to operate under their contract terms. > [!WARNING] > > Metering has a short delay, so some usage can arrive after the balance reaches zero. You remain responsible for that usage. The cut-off does not guarantee an exact spending cap. ### In-arrears cut-off Qualifying enterprise customers billed monthly can set a cut-off at an agreed negative balance. Once usage passes that threshold, access pauses for the rest of the billing period. [Contact sales](https://www.together.ai/contact-sales) to find out whether your account qualifies. ### Turn serverless inference access off or on If you have a contract, ask your solutions architect to turn serverless access off when you need to stop serverless spend, and to turn it back on later. ## Keep prepaid workloads funded Prepaid services consume your organization's credit balance. You can [buy credits manually](/docs/billing-credits#buy-credits) for predictable, temporary, or experimental workloads, or enable [auto-recharge](/docs/billing-credits#auto-recharge-credits) for production workloads that need to keep running. Auto-recharge purchases credits when your balance falls below a threshold you set. Choose the threshold based on your consumption rate: higher-throughput workloads need a larger buffer between a recharge and balance exhaustion. Auto-recharge keeps purchasing credits as you consume them, so it does not cap spend. Auto-recharge requires a credit or debit card as your [default payment method](/docs/billing-payment-methods). Setting an Automated Clearing House (ACH) bank account as the default turns auto-recharge off, even if you have a card saved. ## Attribute spend to projects and API keys [Projects](/docs/projects) separate resources and API keys by team, environment, application, or workload. Choose project boundaries that match how you assign cost ownership. For example, separate production, staging, and experimentation workloads into their own projects. Cost analytics can group organization usage by project, and each project has its own cost analytics view. > [!NOTE] > > Projects share the organization's credit balance. A separate project does not get its own prepaid balance or spending cap, and turning off auto-recharge affects funding for the entire organization, including production projects. Within a project, create separate, descriptively named [API keys](/docs/api-keys-authentication) for distinct services or workloads, such as `prod-chat-api` and `prod-agent-worker`. Cost analytics attributes inference usage to individual API keys. API keys do not currently support independent spending limits. ## Investigate spend with cost analytics Use [cost analytics](/docs/billing-cost-analytics) to view costs or billable units, such as tokens, over a selected date range. You can group usage by product, line item, project, or API key. Project and API key grouping are in beta. To investigate an increase in spend, start with organization-level cost analytics and group by project. Open the responsible project's cost analytics, then group by API key or line item to identify the workload or product driving the change. Filter individual series to narrow the investigation. Filtering is unavailable when grouping by line item. ## Monitor spend programmatically The [billing usage API](/reference/billing-usage) returns organization billing usage as cost-annotated line items through `GET /v1/billing/usage`. Use it to build internal dashboards, scheduled reports, anomaly detection, custom alerts, or chargeback systems. > [!NOTE] > > The billing usage API is in beta and requires access to be enabled for your organization. [Contact support](https://portal.usepylon.com/together-ai/forms/support-request) to request access. The response shape can change during beta. Each line item includes the product, quantity, unit price, and cost. Inference line items can include `project_id` and `api_key_id`, so you can join usage to an internal service catalog to map it to the owning team. The API returns usage for the key's entire organization, and any project's key can read it. Review the [access scope](/reference/billing-usage) before integrating it into internal systems. Send `organization_id` in your requests: it is optional during beta but will be required at general availability. During beta, current-month usage can be up to 1 hour behind, and prior-month usage up to 24 hours behind. All timestamps are in Coordinated Universal Time (UTC). ## Coming soon: budgets and alerts > [!NOTE] > > Organization and project budgets and spend alerts are planned features. They are not currently available to configure. **Spend alerts** will notify you when organization or project usage reaches thresholds you set, without interrupting your workloads. Until alerts are available, use the [billing usage API](/reference/billing-usage) for custom monitoring. **Budgets** will stop spending at an organization or project limit. They suit workloads that can tolerate interruption, such as training jobs, development environments, and agent loops that should stop if spend runs away. Until budgets are available, the balance cut-offs above are the only hard stops. ## Recommended setups ### Production workloads Use a dedicated production project, descriptive API keys, auto-recharge, and cost analytics. Set the recharge threshold high enough for your consumption rate, and integrate the billing usage API with your internal monitoring if you need custom reports or alerts. ### Development and experimentation Use separate non-production projects and cost analytics to track consumption. If the entire organization can tolerate interruption, keep auto-recharge off and add credits manually. The zero-balance cut-off affects all projects in the organization. ### Larger organizations Align projects with teams, applications, or environments, and use descriptive API keys per workload. Combine organization and project cost analytics with the billing usage API to feed existing financial operations (FinOps) reporting and ownership data. # Billing troubleshooting Source: https://docs.together.ai/docs/billing-troubleshooting Resolve payment issues, understand charges, and manage billing problems. ## Troubleshooting payment declines There are many reasons that payments can be declined. If your payment isn't going through, check the following: * Is there enough money in your account to cover the payment? * Is the payment card in date? * If the card was recently replaced, have you activated it? * Have you entered the correct CVV number? * **Have you filled in all of the address information when adding the card?** Ensure the billing address exactly matches what's registered with your card provider, including the zip/post code. Even if your payment provider shows the transaction as approved, address mismatches can still cause the payment to be declined. * **Are you using a supported card type?** Together AI only accepts credit or debit cards linked to a bank account. Prepaid cards are not supported and will be declined. Virtual cards are also often blocked by issuing banks for certain types of transactions. * **Does your card support recurring payments?** Together AI requires payment cards that support recurring payments. Some prepaid cards or cards from certain banks may not support this feature, which can cause payment declines even with valid card information. * **Are you seeing a \$0 authorization hold from your bank?** This is a normal verification process to confirm your card is active before charging the actual amount. You need to approve this authorization hold in your banking app or with your bank for the real payment to go through. * **Are you waiting long enough for processing?** Credit purchases can take up to 15 minutes to complete. Avoid re-entering your card details during this processing period, as this may cause multiple credit purchases. * Is your card frozen/blocked by your bank? * Does your card have any spending limits that you might have reached? * Is your bank sending you an additional security prompt that you need to complete? If you see the error message "We only accept credit or debit cards," this indicates you're trying to use an unsupported payment method. Make sure you're using a regular credit or debit card linked to a bank account, not a prepaid card, virtual card, or alternative payment method. ### ACH bank transfer declines If you pay by Automated Clearing House (ACH) transfer from a linked US bank account, also check: * Does the linked account have enough available balance to cover the purchase? * Is the bank account authorized for ACH debits? * Did instant bank verification succeed when you linked the account? * Did your bank block or return the debit after the purchase was submitted? If an ACH payment fails, no credits are deposited. Contact [Support](https://portal.usepylon.com/together-ai/forms/support-request) if you need help with a failed ACH payment. ## Understanding pending payments There are a number of stages to every payment made on the Together AI platform. First, Together AI's payment processor contacts your bank or card issuer to approve the payment. Once the payment has gone through, an invoice is generated, which you can access from [your billing settings](https://api.together.ai/settings/organization/~current/billing). The payment systems then need to update your account balance to reflect the purchase. Once all of this has happened, your balance updates. ### Card payments For credit and debit card purchases, this usually completes within 60 seconds of you confirming the payment, often instantly. Sometimes there can be a delay in the process, either on Together AI's side or due to your bank taking longer than expected to confirm the payment. ### ACH bank transfers For ACH purchases, credits are deposited **only after the payment clears**. This usually takes **1–3 business days**, but can take longer depending on your bank. While the payment is pending, your credit balance does not increase. You will see a pending banner on your [billing settings](https://api.together.ai/settings/organization/~current/billing) page. If the [ACH payment](/docs/billing-payment-methods#ach-bank-transfers) ultimately fails, no credits are deposited. ### What to do while a payment is pending If this happens, you will see a pending banner on your [billing settings](https://api.together.ai/settings/organization/~current/billing) page to let you know that the transaction has been received but is still in progress. If this is the case, don't make any further payments. Each further payment will be treated as an individual transaction, so you could end up buying more credit packs than you intended. ## Unexpected auto-recharge charges If you were charged right after [configuring auto-recharge](/docs/billing-credits#auto-recharge-credits), check your threshold. Setting the threshold above your current balance triggers an immediate purchase to bring your balance up to your target. Auto-recharge always charges in a single transaction, so if you see repeated charges, check whether multiple manual purchases were submitted while a payment was still pending. ## Understanding unexpected charges If you're seeing charges on your account without making API calls, you may be incurring costs from deployed resources that continue to run even when not actively used. ### Common causes of unexpected charges 1. **Fine-tuned model hosting:** Deployed fine-tuned models incur per-minute hosting fees regardless of API usage. These charges continue until you stop the endpoint. 2. **Dedicated model inference:** This is charged based on hardware allocation, even without active requests. Charges accrue as long as the endpoint remains active. 3. **Serverless model usage:** Charged based on actual token usage and model size - you only pay for what you use. ### Managing your deployments To avoid unexpected charges: 1. Visit your [models dashboard](https://api.together.ai/models). 2. Check for deployed fine-tuned models or active dedicated endpoints. 3. Stop any unused endpoints. Monitor usage and pricing at [together.ai/pricing](https://www.together.ai/pricing). Deployment charges are separate from usage charges and credit purchases. # Changelog Source: https://docs.together.ai/docs/changelog **November 5, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `moonshotai/Kimi-K3.1-Pro`: 1,048,576 context length, NVFP4 quantization, text and image input, function calling, and structured outputs. Pricing: \$2.00 input / \$10.00 output / \$0.20 cached input (per 1M tokens). **November 4, 2026** ## Post-training: Kimi K3.1 Pro `moonshotai/Kimi-K3.1-Pro` is available for [post-training](/docs/post-training/overview): LoRA training on `B200-SXM`, a 163,840-token training context, a 167,936-token generator context, rank up to 32, and up to three adapter sessions per resource. You can't deploy its adapters on dedicated model inference yet. See [Supported models](/docs/post-training/supported-models). **November 3, 2026** ## Messages API and Responses API Together AI now supports the Anthropic [Messages API](/docs/inference/messages-api) at `POST /v1/messages` and the OpenAI [Responses API](/docs/inference/responses-api) at `POST /v1/responses`. To run an app built on either API on Together, change its API key, base URL, and model. Both APIs support `zai-org/GLM-5.3` and `zai-org/GLM-5.2` on serverless inference, and `zai-org/GLM-5.3-Flash` and `zai-org/GLM-5.2` on dedicated model inference. ## Together Python SDK and CLI 3.1.0 Together Python SDK 3.1.0 and Together CLI 3.1.0 are now available. > [!WARNING] > > `tg beta jig deploy` no longer stores your API key as a `TOGETHER_API_KEY` secret on new deployments. Existing deployments keep the secret they already have. > > Sprocket 0.1.8 and later authenticate with the deployment's service token instead. Before you deploy with CLI 3.1.0, raise the `sprocket` pin in your image to 0.1.8 or later. If your own code reads `TOGETHER_API_KEY`, [set it as a secret](/reference/cli/jig#jig-secrets-set). **What's new:** * **Deploy after `tg login`:** `tg beta jig deploy` now works with a `tg login` session, so you don't need an API key to [deploy a container](/docs/containers-quickstart). * **Expiring secrets:** `client.beta.jig.secrets.create` and `update` take `ttl_seconds`, which sets how long a secret lives before it's deleted, from one to 14 days. Secrets return their deletion time as `expires_at`. To set an expiry from the CLI, pass `--ttl` to [`tg beta jig secrets set`](/reference/cli/jig#jig-secrets-set). * **`--debug` replaces `TOGETHER_DEBUG`:** `tg beta jig` no longer reads the `TOGETHER_DEBUG` environment variable. For debug output, pass `--debug`. * **Idle timeout in the SDK:** `ModelResourcesClient.create` takes `inactive_timeout`, the number of seconds a resource stays `READY` without activity before it stops. To keep a resource from [stopping for inactivity](/docs/post-training/model-resources#idle-timeout) while you aren't running operations, call `extend_expiry`. * **`ready_timeout` replaces `timeout`:** `ModelResourcesClient.create` now takes `ready_timeout`, which caps how long it [waits for the resource](/docs/post-training/model-resources#create-a-resource) to become `READY`. `timeout` still works but shows a `FutureWarning`. * **GB200 GPU clusters:** `client.clusters.create` and [`tg clusters create`](/reference/cli/clusters#create-a-cluster) accept `GB200_SXM` as a GPU type. * **Applied credit in the SDK:** Line items from `client.organization.usage.costs.list()` now include a typed `applied_credit` object. ## Post-training: FP4 preparation for MiniMax M3.1 Flash You can now deploy a MiniMax M3.1 Flash adapter on dedicated model inference by first [preparing it for FP4 inference](/docs/post-training/prepare-for-fp4-inference). The base model already ships in its serving format, so the job only merges the adapter, which takes about 1 hour. ## Post-training: MiniMax M3 retired `MiniMaxAI/MiniMax-M3` is no longer available for new [post-training](/docs/post-training/overview) model resources. Use `MiniMaxAI/MiniMax-M3.1-Flash` instead. Existing MiniMax M3 model resources keep running, and their checkpoints stay available for download. See [Supported models](/docs/post-training/supported-models). **November 2, 2026** ## Post-training: GLM-5.3 Flash `zai-org/GLM-5.3-Flash` is available for [post-training](/docs/post-training/overview): LoRA training on `B200-SXM`, a 159,744-token training context, a 163,840-token generator context, rank up to 32, and up to five adapter sessions per resource. The [cookbook](/docs/post-training/cookbook) renders its prompts with the GLM codec. To deploy a GLM-5.3 Flash adapter on dedicated model inference, first [prepare it for FP4 inference](/docs/post-training/prepare-for-fp4-inference). **October 23, 2026** ## New post-training models The following models are now available for [post-training](/docs/post-training/supported-models): * `MiniMaxAI/MiniMax-M3.1-Flash`: 262,144 context length, low-rank adapter (LoRA) training on `B200-SXM` GPUs. **October 22, 2026** ## Together SDK and CLI 3.0 Together Python SDK 3.0, TypeScript SDK 1.0, and Together CLI 3.0 are now available. > [!WARNING] > > 3.0 is a major release with breaking changes. The `beta` paths for dedicated model inference and GPU clusters no longer work, the SDK base URL drops `/v1`, and `whoami` returns a new response shape. Read [SDK v3 migration](/docs/sdk-v3-migration-guide) before you upgrade. **What's new:** * **Dedicated model inference and GPU clusters out of `beta`:** Manage [dedicated model inference](/docs/dedicated-endpoints/overview) and [GPU clusters](/docs/gpu-clusters-overview) with `client.endpoints`, `client.models`, and `client.clusters`, or with `tg endpoints`, `tg models`, and `tg clusters` in the CLI. * **Faster chat completions:** The SDKs send chat completions directly to the inference host, `https://api-inference.together.ai`, by default. * **Identity for any credential:** [`client.whoami()`](/reference/whoami) returns a typed identity for project API keys, organization API keys, and user sessions, including credentials that aren't scoped to a project. * **Billing usage in the SDK:** `client.organization.usage.costs.list()` returns your organization's cost line items by day or hour from the [billing usage API](/reference/billing-usage), which is in beta and enabled per organization. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `MiniMaxAI/MiniMax-M3.1-Flash`: 1,048,576 context length, NVFP4 quantization, function calling, and structured outputs. Pricing: \$0.15 input / \$0.60 output / \$0.015 cached input (per 1M tokens). ## Applied credit types in billing usage Billing usage line items now include an `applied_credit` object. Its `type` identifies the kind of credit that covers the usage: `CREDIT` (free credit), `PREPAID` (credit purchased in advance), or `POSTPAID` (credit under a paid commitment). Line items for usage that no credit covers omit the object. Usage covered by different credits now appears as separate line items. See [Get billing usage](/reference/billing-usage). ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `meta-llama/Llama-3.3-70B-Instruct-Turbo`. Use `meta-models/Muse-Glimmer-30B` instead. * `deepseek-ai/DeepSeek-V4-Flash-0731`. Use `deepseek-ai/DeepSeek-V4.1-Flash-1017` instead. Both models remain available through on-demand [dedicated endpoints](/docs/dedicated-endpoints). For Llama 3.3 70B, deploy `meta-llama/Llama-3.3-70B-Instruct`. See [Deprecations](/docs/deprecations) for migration options. **October 19, 2026** ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `moonshotai/Kimi-K3`. ## Longer post-training context for Kimi K3 `moonshotai/Kimi-K3` on [post-training](/docs/post-training/overview) now supports a 163,840-token training context (up from 65,536) and a 167,936-token generator context (up from 69,632). See [Supported models](/docs/post-training/supported-models). **October 18, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `deepseek-ai/DeepSeek-V4.1-Flash-1017`: 1,000,000 context length, FP8 quantization, function calling, and structured outputs. Pricing: \$0.30 input / \$1.20 output / \$0.006 cached input (per 1M tokens). ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `deepseek-ai/DeepSeek-V4.1-Flash-1017`. **October 17, 2026** ## Post-training: Muse Spark Open `meta-models/Muse-Spark-Open-816B-A42B` is available for [post-training](/docs/post-training/overview): LoRA training on `B200-SXM`, a 159,744-token training context, a 163,840-token generator context, rank up to 32, and one adapter session per resource. See [Supported models](/docs/post-training/supported-models). **October 16, 2026** ## Geo-specific inference You can now keep serverless inference processing in the United States. Set your client's base URL to `https://us-api.together.ai/v1`, using your existing API key and model IDs. There are no GPUs to provision. US models: `moonshotai/Kimi-K3`, `zai-org/GLM-5.3`, `zai-org/GLM-5.2`, `deepseek-ai/DeepSeek-V4.1-Flash`, `deepseek-ai/DeepSeek-V4.1-Flash-1017`, `deepseek-ai/DeepSeek-V4-Pro-0813`, and `MiniMaxAI/MiniMax-M3`. US-only inference costs 1.25× standard serverless rates (a 25% premium) for input, cached input, and output tokens. See [Geo-specific inference](/docs/serverless/geo-specific-inference) for details. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `reflection/Beam-1.0-501B-A23B`: 1,048,576 context length, NVFP4 quantization, function calling, and structured outputs. Pricing: \$0.40 input / \$1.20 output / \$0.04 cached input (per 1M tokens). ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `reflection/Beam-1.0-501B-A23B`. ## New field names for FP4 preparation FP4 preparation requests now identify the adapter with `model_object_id` and `model_revision_id`. The job still accepts only LoRA adapters, not full-weight models. The `adapter_object_id` and `adapter_revision_id` names are deprecated but still accepted. A request can use either pair, but not both. A job's `params` list the adapter under both pairs of names, with the same values. See [Prepare for FP4 inference](/docs/post-training/prepare-for-fp4-inference#find-the-adapter-id) for details. ## Batch jobs are single-model Each batch job now runs against one model. Every line in the input file must name the same model in `body.model`, and a file that mixes models fails during `VALIDATING` instead of running. To run the same prompts through several models, submit one input file and one batch job per model. See [Batch processing overview](/docs/inference/batch/overview) for details. **October 15, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `meta-models/Muse-Spark-Open-816B-A42B`: 1,048,576 context length, NVFP4 quantization, function calling, and structured outputs. Pricing: \$1.25 input / \$4.25 output / \$0.15 cached input (per 1M tokens). * `nvidia/NVIDIA-Nemotron-3.5-Super-VL`: 262,144 context length, NVFP4 quantization, image input, function calling, and structured outputs. Pricing: \$0.15 input / \$0.50 output / \$0.02 cached input (per 1M tokens). ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `nvidia/NVIDIA-Nemotron-3.5-Super-VL`. **October 14, 2026** ## Pricing update The following models have updated pricing. All usage is now billed at the new rates (per 1M tokens): * `moonshotai/Kimi-K3`: \$2.70 → \$3.00 (input), \$13.50 → \$15.00 (output). See [Serverless models](/docs/serverless/models) for the full pricing catalog. **October 13, 2026** ## Post-training Post-training lets you write your own training loop and run it against Together AI GPUs. Your code builds each batch and chooses the loss function and learning rate, while the GPUs you provision run the forward and backward passes, optimizer steps, and sampling. It bills per GPU-minute. Write a loop with the Python SDK (`together.post_training`, version 2.41.0 or later), or start from a recipe in the [post-training cookbook](/docs/post-training/cookbook). **What's included:** * **Three training methods:** [Supervised fine-tuning (SFT)](/docs/post-training/sft), [direct preference optimization (DPO)](/docs/post-training/dpo), and [reinforcement learning with group relative policy optimization (GRPO)](/docs/post-training/grpo). Each method trains a low-rank adapter (LoRA) or the full model weights. * **[Custom loss functions](/docs/post-training/custom-loss-functions):** Train with any objective you compute in PyTorch from the model's log-probabilities. * **[Multi-turn environments](/docs/post-training/multi-turn-environments):** Train tool-use agents with GRPO over whole episodes. * **[Several adapters on one base model](/docs/post-training/multi-lora):** Attach several LoRA sessions to one model resource, so a hyperparameter sweep costs one base model's GPU time. * **[Multi-LoRA deployment](/docs/post-training/multi-lora-deployment):** Attach trained adapters to one dedicated deployment of their base model, then name an adapter in each request to compare them. * **[Prepare for FP4 inference](/docs/post-training/prepare-for-fp4-inference):** Merge a LoRA adapter into GLM-5.3 or Kimi-K3 and quantize the result to FP4 for dedicated model inference. * **[Tinker compatibility](/docs/post-training/migrate-from-tinker):** Run a Tinker training script on post-training by changing its import line and, if needed, its base model. * **[CLI commands](/reference/cli/training):** Together CLI 2.41.0 adds `tg training` to list model resources, sessions, and checkpoints and to run FP4 preparation jobs. `tg beta endpoints deploy` adds `--attach-adapter` and `--merge` for deploying a trained adapter. See [Post-training](/docs/post-training/overview) for details. ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `nvidia/parakeet-tdt-0.6b-v3` (speech-to-text). * `openai/whisper-large-v3` (speech-to-text). ## Unified `together-ai` agent skill A single `together-ai` skill now replaces the per-product Together AI [agent skills](/docs/agent-skills). It covers every product area, plus Together Link setup. The skill loads the guide for a product area only when a task needs it, so installing it doesn't fill your agent's context. If you installed any of the earlier skills (`together-chat-completions`, `together-images`, and so on), delete them after you install `together-ai`, so your agent doesn't load outdated guidance alongside the new skill. ## Lower maximum batch size for Qwen 27B full fine-tuning The maximum batch size for full fine-tuning of `Qwen/Qwen3.8-27B`, `Qwen/Qwen3.6-27B`, and `Qwen/Qwen3.5-27B` is now 4, down from 16 for SFT and 8 for DPO. See [Supported models](/docs/fine-tuning/supported-models#full-fine-tuning) for each model's limits. **October 12, 2026** ## Browser login for the Together CLI Together CLI 2.41.0 adds `tg login`, which logs you in through your browser instead of with an API key. If you don't have a Together AI account yet, you can create one during login. The release also adds: * `tg switch`, which changes the project the CLI works in. * `tg projects ls`, which lists the projects your current credentials can access. * `tg logout`, which removes your stored credentials. For CI/CD and scripts, the CLI still accepts an API key. See [Login](/reference/cli/auth). **October 2, 2026** ## New provisioned throughput models The following models are now available on [provisioned throughput](/docs/inference/provisioned-throughput): * `zai-org/GLM-5.3`. * `zai-org/GLM-5.3-Flash`. * `deepseek-ai/DeepSeek-V4.1-Flash`. ## Dynamic rate limits for serverless retired Serverless no longer applies dynamic rate limits that scale with your recent traffic. Most users will no longer encounter rate limits, though requests can still be limited during periods of high demand. If you get a `429 Too Many Requests` response, reduce your request rate and spread out bursts. If you get a `503 Service Unavailable` response, wait briefly before retrying. Retry both with exponential backoff. See [Rate limits](/docs/serverless/rate-limits). **October 1, 2026** ## Together Link beta Together Link runs six coding agents on models hosted by Together AI: Claude Code, Codex, OpenCode, and Pi Code in the terminal, plus Claude Desktop (including Cowork) and ChatGPT Desktop. Install it with one command, launch your agent through it, and your normal agent configuration stays untouched. It's now in beta on macOS and Linux. ```bash theme={null} # Install Together Link curl -fsSL https://link.together.ai/install | bash # Open the interactive launcher togetherlink # Or launch an agent directly, pinned to one model togetherlink --main moonshotai/Kimi-K3 claude ``` **What's included:** * **Six agents:** Launch Claude Code (`tclaude`), Codex (`tcodex`), OpenCode (`topencode`), or Pi Code (`tpi`) in your terminal, or switch Claude Desktop and ChatGPT Desktop to a reversible Together Link profile. OpenCode requires OpenCode 2, and Pi Code requires version 0.80.8 or newer. * **Auto router:** Sessions default to the `auto` model, which picks a Together AI model for each request. In Claude Code and Claude Desktop sessions with an Anthropic API key, it sends the most difficult requests to Claude Opus. * **Models:** `moonshotai/Kimi-K3`, `zai-org/GLM-5.3`, `zai-org/GLM-5.3-Flash`, and `deepseek-ai/DeepSeek-V4.1-Flash`, all with 1M context, billed at standard serverless rates. Pin one with `--main`, or switch with your agent's `/model` command. * **Cost tracking:** A session receipt on exit, an estimated spend in Claude Code's status line, and `togetherlink usage` for spend across sessions. * **Image generation:** Claude Code, Claude Desktop, and ChatGPT Desktop sessions include a skill that generates and edits images with Together AI image models. * **Headless mode:** Each agent's own non-interactive flags pass through, so scripts can drive `tclaude -p`, `tcodex exec`, `topencode run`, and `tpi -p`. See [Together Link](/docs/togetherlink) for details. ## Code sandbox SDK and CLI The new `together-sandbox` SDK runs commands and code in isolated runtime environments built from Docker-image snapshots. It ships as a Python SDK, a TypeScript SDK, and a standalone CLI, and is available to organizations on an allowlist ([contact us](https://www.together.ai/contact) to request access). **What's changed from the [legacy SDK](/docs/together-code-sandbox-legacy) (`@codesandbox/sdk`):** * **Together-native authentication:** Clients authenticate with your Together API key (`TOGETHER_API_KEY`) instead of a CodeSandbox API token. * **Python support:** The legacy SDK was TypeScript-only. The new SDK is published on both PyPI and npm, and the CLI installs as a self-contained binary. * **Docker-defined environments:** Sandboxes boot from snapshots built from a Docker image or Dockerfile by Together's remote image builder, replacing templates built with the CodeSandbox CLI. No local Docker is required. * **Snapshot-based persistence:** Sandboxes are ephemeral by default and termination is permanent. To maintain state, snapshot the filesystem on termination and start a new sandbox from it. This replaces the legacy hibernate and resume model. See [Code sandbox](/docs/together-code-sandbox) for the new workflow. ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `hexgrad/Kokoro-82M` (text-to-speech). * `Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice` (text-to-speech). **September 29, 2026** ## Higher LoRA rank limit for fine-tuning You can now train low-rank adapters (LoRA) with a rank of up to 128 for the majority of models, up from 64. The default rank for these models stays at 64, so set `lora_r` to use a higher one. The [model limits](/reference/get-fine-tunes-models-limits) response has a new `lora_training.default_rank` field next to `lora_training.max_rank`. Run [`tg fine-tuning model-limits `](/reference/cli/finetune#model-limits) to see both values for a model. Version 2.36.0 of the Together CLI and Python SDK uses the default rank when you don't set `lora_r`. Earlier versions, including the 1.x SDK, use the model's maximum rank instead, which is now 128 on these models. Upgrade to 2.36.0 or set `lora_r` yourself, especially if you [continue training](/docs/fine-tuning/lora-vs-full#continue-training-from-a-checkpoint) from a rank-64 adapter, where the rank has to match. In the console, the rank field now starts at the model's default rank (64 on most models) instead of 8. See [Supported models](/docs/fine-tuning/supported-models) for each model's default and maximum rank. ## Longer fine-tuning context for Qwen 27B models `Qwen/Qwen3.8-27B`, `Qwen/Qwen3.6-27B`, and `Qwen/Qwen3.5-27B` now support a 131,072-token context for SFT (up from 32,768) and 65,536 for DPO (up from 16,384), for both LoRA and full fine-tuning. Batch size limits have also changed: LoRA jobs on these models run at a batch size of 2, down from 16, and the maximum DPO batch size for full fine-tuning drops from 16 to 8. See [Supported models](/docs/fine-tuning/supported-models) for each model's limits. ## Batch API files are now retained for 7 days The input file you upload for a batch job, along with the output and error files the job produces, are now retained for 7 days. After that the files are no longer accessible, so download your results before the window closes. Reusing an uploaded input file across batch jobs also works only within that window. See [Batch inference](/docs/inference/batch/overview#data-retention). **September 24, 2026** ## Deploy a fine-tuned model by its registry name Since Together CLI version `2.24.0`, `tg beta endpoints deploy` accepts a completed fine-tuning job's `model_object_name`, the qualified `/` registry name, in place of its `model_object_id`. The CLI resolves the name to the same model, so you can deploy straight from the name shown in the [fine-tuning jobs dashboard](https://api.together.ai/jobs). The SDK and API take `model_object_id`. See [Deploy a fine-tuned model](/docs/fine-tuning/deployment). **September 23, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `together/Tev1-4B-experimental`: 32,768 context length. Pricing: \$0.042 input / free output (per 1M tokens). **September 22, 2026** ## Pricing update The following models have lower pricing, effective September 22, 2026. All usage from that date forward is billed at the new rates (per 1M tokens): * `Qwen/Qwen3.7-Max`: \$2.50 → \$1.50 (input), \$7.50 → \$4.50 (output). * `Qwen/Qwen3.8-Flash`: \$0.15 → \$0.09 (input), \$0.47 → \$0.282 (output). See [Serverless models](/docs/serverless/models) for the full pricing catalog. **September 16, 2026** ## Automatic idle shutdown for dedicated deployments Deployments can now stop themselves when they go unused. Set an inactivity timeout with `--inactive-timeout` (the `inactiveTimeout` field in the management API), and if the deployment serves no inference requests for that many minutes, it scales to zero replicas, releasing its hardware and stopping billing. See [Automatic idle shutdown](/docs/dedicated-endpoints/scaling#automatic-idle-shutdown). **September 15, 2026** ## Rollouts for dedicated model inference [Rollouts](/docs/dedicated-endpoints/rollouts) shift live traffic from one deployment to another under the same endpoint, without changing the endpoint URL. Pick a canary, blue-green, or rolling strategy to determine how traffic moves, and optionally gate a canary rollout on [live metrics](/docs/dedicated-endpoints/rollout-metric-gates) so it pauses automatically if the new deployment regresses. Start a rollout with the `tg beta endpoints rollout` CLI command or from the endpoint's **Rollouts** tab in the console, then pause, resume, promote, or cancel it at any point while it runs. ## Together CLI v2.34.0 Version 2.34.0 of the Together CLI and Python SDK carries the rollouts release above (the SDK surface is `client.beta.endpoints.rollouts`) and also adds: * `tg files check` now rejects Parquet files larger than the maximum supported file size instead of passing them through format validation. See the [CLI reference](/reference/cli/getting-started). ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `openai/gpt-oss-20b`. Recommended replacement: `Qwen/Qwen3.5-9B`. Supported by on-demand dedicated endpoints. * `google/gemma-4-31B-it`. Recommended replacement: `zai-org/GLM-5.3-Flash`. Supported by on-demand dedicated endpoints. * `thinkingmachines/Inkling-Small`. Recommended replacement: `zai-org/GLM-5.3-Flash`. Supported by on-demand dedicated endpoints. * `intfloat/multilingual-e5-large-instruct`. Not available as an on-demand dedicated endpoint. See [Deprecations](/docs/deprecations) for migration guidance. **September 14, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `MiniMaxAI/MiniMax-H3`: Pricing: \$0.1391/sec at 2k. **September 11, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `deepseek-ai/DeepSeek-V4.1-Flash`: 1,000,000 context length, FP8 quantization, function calling, and structured outputs. Pricing: \$0.30 input / \$1.20 output / \$0.006 cached input (per 1M tokens). ## Pricing update Fine-tuning is now priced per model instead of by parameter-count tier, and many models cost less. Each model has its own per-token rates for supervised (SFT) and preference (DPO) training, with separate rates for LoRA and full fine-tuning. See [Fine-tuning pricing](/docs/fine-tuning/pricing). ## Expert LoRA removed from FP4-served MoE models LoRA fine-tuning jobs can no longer target the expert layers (`w_up`, `w_gate`, `w_down`) of mixture-of-experts models served in FP4, MXFP4, or NVFP4, including `deepseek-ai/DeepSeek-V3.1`. These models support attention-only LoRA, and creating a job that lists an expert module returns a validation error. See [Target MoE expert layers](/docs/fine-tuning/lora-vs-full#target-moe-expert-layers). ## Model deprecations The following models have been deprecated and are no longer available for [fine-tuning](/docs/fine-tuning/supported-models): * `nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16`. * `nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16`. * `Qwen/Qwen3.5-35B-A3B-Base`. Recommended replacement: `Qwen/Qwen3.5-35B-A3B`. **September 10, 2026** ## Preemptible compute for GPU clusters Preemptible compute is now in public preview for Kubernetes GPU clusters. Alongside standard nodes, you can set a preemptible GPU target, and Together provisions toward it as spare capacity becomes available, at a flat discounted rate relative to on-demand. **What's new:** * **Preemptible GPU targets:** Set `num_preemptible_gpus` at cluster create or update from the console, CLI, or API. Together automatically provisions replacements toward the target after nodes are reclaimed. * **Five-minute drain window:** Reclaimed nodes are cordoned and emit a `TogetherPreemptionNotified` Kubernetes event, and pods receive SIGTERM with up to 300 seconds of grace to checkpoint and exit. * **Sub-hourly billing:** Usage is metered every one to two minutes, so you pay only for the time a node is live. See [Preemptible compute](/docs/preemptible-compute) for the preemption contract, scheduling guidance, and checkpoint examples. ## Together CLI v2.33.2 Version 2.33.2 of the Together CLI improves error reporting and upload feedback: * Endpoint, fine-tuning, and model commands now print the API's error message when a request fails, rather than a generic failure notice. The same goes for a missing API key or command argument. * `tg evals create` and `tg batches submit` now show a progress bar while uploading files, matching `tg files upload`. * `tg fine-tuning list-events` no longer fails on jobs with more than 20 events. * The `--scale-to-zero-window` flag has been removed from `tg beta endpoints deploy` and `tg beta endpoints update`. See the [CLI reference](/reference/cli/getting-started). **September 8, 2026** ## New models available for fine-tuning You can now fine-tune the following models: * `zai-org/GLM-5.3`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. **September 1, 2026** ## Model deprecations The following models are deprecated and will be removed from serverless on September 14, 2026: * `openai/gpt-oss-20b`. Recommended replacement: `Qwen/Qwen3.5-9B`. * `google/gemma-4-31B-it`. Recommended replacement: `zai-org/GLM-5.3-Flash`. * `thinkingmachines/Inkling-Small`. Recommended replacement: `zai-org/GLM-5.3-Flash`. * `intfloat/multilingual-e5-large-instruct`. All except `intfloat/multilingual-e5-large-instruct` remain available through on-demand [dedicated endpoints](/docs/dedicated-endpoints). See [Deprecations](/docs/deprecations) for migration options. **August 31, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Qwen/Qwen3.8-Flash`: 1,000,000 context length. Pricing: \$0.15 input / \$0.47 output (per 1M tokens). **August 29, 2026** ## `active_sessions` autoscaling metric for TTS Dedicated endpoint autoscaling now accepts `active_sessions`, which targets concurrent open client WebSocket sessions per replica on a TTS deployment (`AVERAGE_VALUE` only). The default `inflight_requests` metric also covers TTS handlers, so HTTP TTS traffic can keep scaling without a policy change. See [Configure autoscaling](/docs/dedicated-endpoints/scaling#scaling-metrics). **August 28, 2026** ## Start now option for scheduled capacity clusters When you create a scheduled capacity cluster in the [console](https://api.together.ai/clusters), you can check **Start now** to provision it immediately instead of picking a future start date. **Start now** is available only when the selected capacity pool window includes today's date. You still choose an end date within the pool window. See [Schedule a cluster](/docs/gpu-clusters-management#schedule-a-cluster). ## GPU capacity request dialog In the [console](https://api.together.ai/clusters) create-cluster form, select **Need a different configuration?** to open the **Notify when available** dialog. The dialog now asks for the GPU type, number of GPUs, region, optional storage size, and start date, plus an end date for reserved or scheduled capacity. It also shows an estimated cost. See [Request capacity](/docs/gpu-clusters-management#request-capacity). ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `zai-org/GLM-5.3`: 1,000,000 context length, FP4 quantization, function calling and structured outputs. Pricing: \$1.40 input / \$4.40 output / \$0.26 cached input (per 1M tokens). **August 27, 2026** ## Billing usage API (beta) `GET /billing/usage` returns organization-wide usage and cost line items, filterable by month. The endpoint is in beta and enabled per organization. See [Get billing usage](/reference/billing-usage). ## File upload progress in the CLI and Python SDK `tg files upload` and `tg files check` now show a progress bar in interactive terminals. The Python SDK accepts an optional `progress_callback` on `client.files.upload()` that receives upload progress events. See the [files CLI reference](/reference/cli/files) and [Data preparation](/docs/fine-tuning/data-preparation). ## Slurm cluster kubeconfig for project members Project members can now download the cluster kubeconfig for Slurm clusters from the cluster details page, matching Kubernetes cluster behavior. See [Download cluster kubeconfig](/docs/gpu-clusters-management#download-cluster-kubeconfig). ## Legacy API key regeneration Legacy API keys can now be regenerated by any admin or editor of the default project. Legacy keys appear in the project's API keys table with a **Deprecated** badge. See [Legacy API keys](/docs/api-keys-authentication#legacy-api-keys). ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `nvidia/Nemotron-3-ultra-550b-a55b`. * `pearl-ai/gemma-4-31b-it`. * `deepseek-ai/DeepSeek-V4-Pro`. Use `deepseek-ai/DeepSeek-V4-Pro-0813` instead. * `moonshotai/Kimi-K2.7-Code`. `deepseek-ai/DeepSeek-V4-Pro` and `moonshotai/Kimi-K2.7-Code` remain available through on-demand [dedicated endpoints](/docs/dedicated-endpoints). See [Deprecations](/docs/deprecations) for migration options. **August 26, 2026** ## Batch jobs in the CLI The Together CLI now includes a `tg batches` command group for [batch inference](/docs/inference/batch/overview): * `tg batches submit` uploads a local JSONL file (or takes an existing file ID) and creates a job against `chat.completions`, `audio.transcriptions`, or `audio.translations`. * `tg batches list`, `retrieve`, and `cancel` manage the job lifecycle, with `ls` and `get` as aliases. * `tg batches download` streams results to stdout, or writes the output and error files to disk with `--output`. See the [batches CLI reference](/reference/cli/batches). ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `zai-org/GLM-5.3-Flash`: 1,000,000 context length, FP8 quantization, function calling and structured outputs. Pricing: \$0.15 input / \$0.50 output / \$0.03 cached input (per 1M tokens). **August 25, 2026** ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `google/gemma-3n-E4B-it`. * `meta-llama/Llama-Guard-4-12B`. These models are not supported by on-demand dedicated endpoints. See [Deprecations](/docs/deprecations) for migration options. ## New models available for fine-tuning You can now fine-tune the following models: * `Qwen/Qwen3.8-27B`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. ## Longer context for GLM-5.2 `zai-org/GLM-5.2` on [serverless](/docs/serverless/models) now accepts a 1,000,000-token context length, up from 512,000. Pricing is unchanged. See the [GLM-5.2 quickstart](/docs/glm-5.2-quickstart). **August 24, 2026** ## Quick reprovision for pending GPU cluster nodes You can now run **Quick reprovision** as a [manual node repair](/docs/node-repair#manual-node-repair) on nodes that are still in the **Pending** or **Scheduling** phase. The other repair actions stay disabled for nodes in those phases. Nodes with an unset or **Unknown** phase still don't offer a **Repair** action. See [Start a manual repair](/docs/node-repair#start-a-manual-repair). ## Fine-tuning quality improvements Training quality has improved for fine-tuning on the following models: * `Qwen/Qwen3.5-0.8B`. * `Qwen/Qwen3.5-2B`. * `Qwen/Qwen3.5-4B`. * `Qwen/Qwen3.5-9B`. * `Qwen/Qwen3.5-27B`. * `Qwen/Qwen3.5-35B-A3B`. * `Qwen/Qwen3.5-35B-A3B-Base`. * `Qwen/Qwen3.5-122B-A10B`. * `Qwen/Qwen3.5-397B-A17B`. * `Qwen/Qwen3.6-27B`. * `Qwen/Qwen3.6-35B-A3B`. * `nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16`. * `nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16`. Other models are unchanged. No actions or setting changes are required to get the improvement. To pick it up on a model you've already tuned, start a new job with the same data and settings. A job you run after this release will not reproduce the loss curve of an earlier run on the same data and settings. **August 21, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `deepcogito/cogito-v2-1-671b`. See [Deprecations](/docs/deprecations) for migration options. **August 20, 2026** ## Fully automatic confirmation policy for node auto repair [Auto node repair](/docs/node-repair#auto-node-repair) can now close the loop end to end. Under the new **Fully automatic** confirmation policy, health checks detect the fault, the system generates a repair recommendation, and auto repair executes it without waiting for approval. Clusters continue to use **Approve before repair** by default. **What's new:** * **Confirmation policy toggle:** Choose between **Approve before repair** and **Fully automatic** under **Auto-remediation policy** on the **Repairs** tab. * **Per-fault scoping:** Under **Fully automatic**, use **Repair actions** to check which fault groups (**Migrate to new host**, **Reprovision**, **VM reboot**) run unattended. Destructive repairs can stay gated on approval while transient ones clear on their own. * **Job interruption controls:** **Wait for idle**, **Grace period**, **Maximum wait**, and **Do not interrupt running jobs** let the wait policy protect in-flight training and inference work in place of a review step. * **Audit trail:** Automatically approved repairs record **Auto-Approved** in the repair's **Reviewed by** field, alongside the alert evidence that triggered them. See [Confirmation policy](/docs/node-repair#confirmation-policy) for details. ## Dedicated endpoint create form uses deployment profiles The console create-endpoint and new-deployment forms always show **Deployment profiles** choice cards. Separate **Quantization**, **Hardware**, LoRA, and speculative-decoding controls are removed. Each card pins hardware, quantization, and decoding options from the profile's certified config. Project and organization models list every certified config with known hardware. Supported catalog models still require a profile-certified or org-runtime-certified config. See [Manage endpoints and deployments](/docs/dedicated-endpoints/manage#create-an-endpoint) and the [quickstart](/docs/dedicated-endpoints/quickstart). **August 19, 2026** ## ACH bank transfers generally available ACH bank transfers are now available to all customers, not just those with an enterprise contract. Link a U.S. bank account with instant verification from your [billing settings](https://api.together.ai/settings/organization/~current/billing), set it as your default payment method, and purchase credits directly from your bank account. Credits are deposited after the ACH payment clears (usually 1–3 business days). Auto-recharge still requires a card as the default payment method. See [Payment methods & invoices](/docs/billing-payment-methods#ach-bank-transfers). ## GPU cluster size picker follows live capacity When you create or edit a GPU cluster in the [console](https://api.together.ai/clusters), the GPU size picker lists every full-node multiple of 8 GPUs, up to the capacity currently available for that GPU type and region. It no longer stops at a fixed ceiling of 1,024 GPUs. See [Scale a cluster](/docs/gpu-clusters-management#scale-a-cluster). ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `black-forest-labs/FLUX.1-schnell`. * `Qwen/Qwen2.5-7B`. * `moonshotai/Kimi-K2.6`. See [Deprecations](/docs/deprecations) for migration options. **August 18, 2026** ## Hybrid scheduled capacity clusters When you create a scheduled capacity cluster that starts now, you can mix capacity pool GPUs with prepaid reserved GPUs from outside the pool. The cluster details page shows how the cluster's GPUs split between the two. * **Console:** Set the pool GPU count under **Select Capacity Pool GPU Count**. To add reserved GPUs, turn on **Add compute outside your capacity pool** and set **Reserved GPUs**. * **API and CLI:** Pass `num_capacity_pool_gpus` and `num_reserved_gpus` so they sum to `num_gpus`. See [Capacity types](/docs/gpu-clusters-overview#capacity-types), the [quickstart](/docs/gpu-clusters-quickstart), and [Create a hybrid scheduled capacity cluster](/docs/gpu-clusters-management#create-a-hybrid-scheduled-capacity-cluster). ## Unknown fields rejected on dedicated endpoints API The [dedicated model inference](/docs/dedicated-endpoints/overview) management API now rejects unknown JSON request-body fields and unknown query parameters with HTTP `400`. The response names the field (for example `unknown field "inactive_timeout"`) instead of silently ignoring it. Remove retired or misspelled keys from clients that still send them. See [Troubleshooting](/docs/dedicated-endpoints/manage#troubleshooting) and [Error codes](/docs/error-codes). **August 17, 2026** ## Project visibility Projects now support three visibility levels. An **open** project lets any organization member discover and join it. A **closed** project is discoverable, but joining requires an admin to grant access. A **private** project is visible only to existing collaborators and organization admins. Choose a level when you create a project, or change it at any time from [**Project Settings**](https://api.together.ai/settings/projects/~current). See [Project visibility](/docs/projects#project-visibility). ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `deepseek-ai/DeepSeek-V4-Pro-0813`: 1,048,576 context length, NVFP4 quantization. Pricing: \$1.32 input / \$3.96 output / \$0.13 cached input (per 1M tokens). ## Multi-project resource scoping Multi-project is now enabled for every organization. Clusters, fine-tuned models, endpoints, evaluations, files, and API keys are fully scoped to projects. The early-access limitations on project isolation no longer apply. See [Projects](/docs/projects). **August 13, 2026** ## New models available for fine-tuning You can now fine-tune the following models: * `zai-org/GLM-5.2`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. ## Fine-tuning model limits in the CLI `tg fine-tuning model-limits` (alias `tg ft model-limits`) queries [`GET /fine-tunes/models/limits`](/reference/get-fine-tunes-models-limits) for a base model's capability flags and hyperparameter bounds. Use `--json` for the full response body. See [Model limits](/reference/cli/finetune#model-limits). ## Tokenized dataset download in fine-tune events When a fine-tuning job finishes uploading its tokenized dataset archive, the `tokenized_dataset_upload_complete` event message includes the CLI command to download it (`tg ft download-tokenized-dataset `). The message appears in the console **Events** tab and in [`GET /fine-tunes/{id}/events`](/reference/get-fine-tunes-id-events). See [Download the tokenized dataset](/docs/fine-tuning/monitoring#download-the-tokenized-dataset). ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `deepseek-ai/DeepSeek-V4-Flash-0731`. ## Endpoint events in the CLI `tg beta endpoints events` lists a [dedicated endpoint's](/docs/dedicated-endpoints/overview) audit and lifecycle events from the terminal: replica scaling, traffic shifts, status changes, and pauses across every deployment under the endpoint. See [Monitoring endpoint events](/docs/dedicated-endpoints/monitoring#events) and the [`tg beta endpoints events` CLI command](/reference/cli/endpoints#events). ## Fine-tuning limits and tokenized datasets in the CLI Two new fine-tuning commands are available: * `tg ft model-limits ` prints a model's fine-tuning constraints, including sequence-length, batch-size, and LoRA rank limits. * `tg ft download-tokenized-dataset ` downloads the tokenized dataset a job trained on, so you can audit exactly what the model saw. See the [fine-tuning CLI reference](/reference/cli/finetune). **August 12, 2026** ## Leave a project from the console Project collaborators can now leave a project themselves, from their own row in [**Settings > Project > Collaborators**](https://api.together.ai/settings/projects/~current/collaborators) or from the Projects list in [**Organization Settings**](https://api.together.ai/settings/organization/~current). Organization members cannot leave the organization's default project, and the last project admin must promote another collaborator before leaving. See [Leaving a project](/docs/projects#leaving-a-project). ## Dedicated API keys for Vercel projects Connecting a Vercel project from [Integrations settings](https://api.together.ai/settings/integrations) now creates a dedicated API key for each linked Vercel project, set as the `TOGETHER_API_KEY` environment variable in that Vercel project. See [Vercel integration](/docs/api-keys-authentication#vercel-integration). ## Non-interactive cluster deletes in the Together CLI `tg beta clusters delete` and `tg beta clusters storage delete` no longer hang waiting for confirmation when run in scripts or CI. Both commands now honor the global `--non-interactive` and `--json` flags. In interactive sessions, pass the new `--force` flag to skip the confirmation prompt. See [Delete a cluster](/reference/cli/clusters#delete-a-cluster) in the CLI reference. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Qwen/Qwen3.8-2.4T-A95B`: FP4 quantization. Pricing: \$2.50 input / \$6.25 output / \$0.50 cached input (per 1M tokens). ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-FP8`. **August 11, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `meta-models/Muse-Glimmer-30B`: 131,072 context length, FP8 quantization. Pricing: \$0.35 input / \$1.50 output / \$0.04 cached input (per 1M tokens). * `ByteDance/Seedance-2.5`: Pricing: \$0.115/sec at 480p. ## New models available for fine-tuning You can now fine-tune the following models: * `deepseek-ai/DeepSeek-V4-Flash-0731`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. **August 10, 2026** ## Tokenized dataset download in the fine-tuning console Open a job on the [fine-tuning jobs dashboard](https://api.together.ai/fine-tuning). When the job has a tokenized dataset archive, the job details show a **Tokenized dataset** row with **Download**. Selecting **Download** opens a presigned archive URL in a new tab. The same archive is available from the API and CLI. See [Download tokenized dataset](/reference/cli/finetune#download-tokenized-dataset). ## Non-interactive fine-tune deletion in the CLI `tg fine-tuning delete` now honors global non-interactive mode. `--non-interactive`, `--json`, and non-TTY sessions skip the confirmation prompt, so scripts and CI no longer need `--force` for unattended deletes. See [Delete](/reference/cli/finetune#delete). **August 8, 2026** ## Longer context for GLM-5.2 `zai-org/GLM-5.2` on [serverless](/docs/serverless/models) now accepts a 512,000-token context length, up from 262,144. Pricing is unchanged. See the [GLM-5.2 quickstart](/docs/glm-5.2-quickstart). **August 7, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Prism-ML/Ternary-Bonsai-27B`: 262,144 context length. Pricing: Free. * `prunaai/p-image-ideogram`: Pricing: from \$0.00225 per image. * `black-forest-labs/FLUX-3`: Pricing: \$0.17/sec at 720p. ## Expert LoRA for DeepSeek-V3.1 LoRA fine-tuning jobs on `deepseek-ai/DeepSeek-V3.1` can now target the MoE expert layers. See [Target MoE expert layers](/docs/fine-tuning/lora-vs-full#target-moe-expert-layers) for how to enable it. ## API key expiration at creation When you create a project API key in the console, you can optionally set an expiration date. Select **Set an expiration date**, then choose **1 hour**, **1 day**, **7 days**, **30 days**, or a custom date. See [Authentication](/docs/api-keys-authentication#create-an-api-key). **August 6, 2026** ## Fine-tune tokenized dataset download You can download the tokenized dataset archive generated for a fine-tuning job. Call [`GET /fine-tunes/{id}/download-tokenized-dataset`](/reference/get-fine-tunes-id-download-tokenized-dataset) for a presigned URL, or use the CLI: ```bash theme={null} tg fine-tuning download-tokenized-dataset [FT_ID] --output-dir ./tokenized ``` See [Download tokenized dataset](/reference/cli/finetune#download-tokenized-dataset) for flags and output formats. **August 3, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `deepseek-ai/DeepSeek-V4-Flash-0731`: 1,000,000 context length, FP4 quantization. Pricing: \$0.14 input / \$0.28 output / \$0.03 cached input (per 1M tokens). ## New models available for fine-tuning You can now fine-tune the following models: * `deepseek-ai/DeepSeek-V4-Flash`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. **July 31, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `thinkingmachines/Inkling-Small`: 524,288 context length. Pricing: \$0.50 input / \$1.20 output (per 1M tokens). ## Model upload progress in the console While a remote model upload is pending or running, the [Models](https://api.together.ai/models) page shows an **Uploading** badge on the model under **My models** and floats it to the top of the list. Opening the model shows a live **Upload progress** event log until the job finishes. See [Check upload status](/docs/dedicated-endpoints/custom-models#check-upload-status). **July 30, 2026** ## OIDC kubeconfig verify access updates In the GPU clusters console, the **OIDC Kubeconfig** dialog **Verify access** step now includes a copyable cache-clear command. After a role or permissions change (new RBAC bindings or an IdP group change), clear the cached OIDC token so the next `kubectl` login picks up the new access. On Together-managed OIDC clusters, the step also now suggests `kubectl get pods` instead of `kubectl get nodes`. Members on those clusters typically have namespace-scoped RBAC, so listing nodes returns `403 Forbidden` even when authentication works. See [Set up OIDC authentication](/docs/cluster-oidc#token-lifetime-and-refresh). **July 29, 2026** ## Models page visibility filter The [Models](https://api.together.ai/models) page now lists Internal-visibility models from every project in your organization under **My models**, not only from the selected project. A **Visibility** filter lets you show **Internal** models, **Private** models, or both. See [Upload a fine-tuned model](/docs/dedicated-endpoints/custom-models#create-the-model). ## Project scoping in the console Fine-tuning, Files, and Evaluations are now available in the Projects UI. Create and manage fine-tuning jobs, uploaded files, and evaluations within a project from the console, not just with project-scoped API keys. See [Projects](/docs/projects). ## Model deprecations The following models have been deprecated and are no longer available for [fine-tuning](/docs/fine-tuning/supported-models): * `nvidia/NVIDIA-Nemotron-Nano-9B-v2`. * `Qwen/Qwen3-Next-80B-A3B-Instruct`. * `Qwen/Qwen3-Next-80B-A3B-Thinking`. * `Qwen/Qwen3-0.6B`. * `Qwen/Qwen3-0.6B-Base`. * `Qwen/Qwen3-1.7B`. * `Qwen/Qwen3-1.7B-Base`. * `Qwen/Qwen3-4B`. * `Qwen/Qwen3-4B-Base`. * `Qwen/Qwen3-8B`. * `Qwen/Qwen3-8B-Base`. * `Qwen/Qwen3-14B`. * `Qwen/Qwen3-14B-Base`. * `Qwen/Qwen3-32B`. * `Qwen/Qwen3-30B-A3B-Base`. * `Qwen/Qwen3-30B-A3B`. * `Qwen/Qwen3-30B-A3B-Instruct-2507`. * `Qwen/Qwen3-235B-A22B`. * `Qwen/Qwen3-235B-A22B-Instruct-2507`. * `Qwen/Qwen3-Coder-30B-A3B-Instruct`. * `Qwen/Qwen3-Coder-480B-A35B-Instruct`. * `Qwen/Qwen3-VL-8B-Instruct`. * `Qwen/Qwen3-VL-32B-Instruct`. * `Qwen/Qwen3-VL-30B-A3B-Instruct`. * `Qwen/Qwen3-VL-235B-A22B-Instruct`. * `Qwen/Qwen2.5-72B-Instruct`. * `Qwen/Qwen2.5-72B`. * `Qwen/Qwen2.5-32B-Instruct`. * `Qwen/Qwen2.5-32B`. * `Qwen/Qwen2.5-14B-Instruct`. * `Qwen/Qwen2.5-14B`. * `Qwen/Qwen2.5-7B-Instruct`. * `Qwen/Qwen2.5-7B`. * `Qwen/Qwen2.5-3B-Instruct`. * `Qwen/Qwen2.5-3B`. * `Qwen/Qwen2.5-1.5B-Instruct`. * `Qwen/Qwen2.5-1.5B`. * `Qwen/Qwen2-72B-Instruct`. * `Qwen/Qwen2-72B`. * `Qwen/Qwen2-7B-Instruct`. * `Qwen/Qwen2-7B`. * `Qwen/Qwen2-1.5B-Instruct`. * `Qwen/Qwen2-1.5B`. * `moonshotai/Kimi-K2.5`. * `moonshotai/Kimi-K2-Thinking`. * `moonshotai/Kimi-K2-Instruct-0905`. * `moonshotai/Kimi-K2-Instruct`. * `moonshotai/Kimi-K2-Base`. * `zai-org/GLM-5`. * `zai-org/GLM-4.7`. * `zai-org/GLM-4.6`. * `deepseek-ai/DeepSeek-R1-0528`. * `deepseek-ai/DeepSeek-R1`. * `deepseek-ai/DeepSeek-V3-0324`. * `deepseek-ai/DeepSeek-V3`. * `deepseek-ai/DeepSeek-V3.1-Base`. * `deepseek-ai/DeepSeek-V3-Base`. * `deepseek-ai/DeepSeek-R1-Distill-Llama-70B`. * `deepseek-ai/DeepSeek-R1-Distill-Llama-70B-32k`. * `deepseek-ai/DeepSeek-R1-Distill-Llama-70B-131k`. * `deepseek-ai/DeepSeek-R1-Distill-Qwen-14B`. * `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B`. * `meta-llama/Llama-4-Scout-17B-16E`. * `meta-llama/Llama-4-Maverick-17B-128E`. * `meta-llama/Llama-3.3-70B-32k-Instruct-Reference`. * `meta-llama/Llama-3.3-70B-131k-Instruct-Reference`. * `meta-llama/Llama-3.2-3B-Instruct`. * `meta-llama/Llama-3.2-3B`. * `meta-llama/Llama-3.2-1B-Instruct`. * `meta-llama/Llama-3.2-1B`. * `meta-llama/Meta-Llama-3.1-8B-131k-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-8B-Reference`. * `meta-llama/Meta-Llama-3.1-8B-131k-Reference`. * `meta-llama/Meta-Llama-3.1-70B-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-70B-32k-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-70B-131k-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-70B-Reference`. * `meta-llama/Meta-Llama-3.1-70B-32k-Reference`. * `meta-llama/Meta-Llama-3.1-70B-131k-Reference`. * `meta-llama/Meta-Llama-3.1-405B-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-405B-Reference`. * `meta-llama/Meta-Llama-3.1-405B-10k-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-405B-10k-Reference`. * `meta-llama/Meta-Llama-3.1-405B-8k-Instruct-Reference`. * `meta-llama/Meta-Llama-3.1-405B-8k-Reference`. * `meta-llama/Meta-Llama-3-8B-Instruct`. * `meta-llama/Meta-Llama-3-8B`. * `meta-llama/Meta-Llama-3-70B-Instruct`. * `google/gemma-3-270m`. * `google/gemma-3-270m-it`. * `google/gemma-3-1b-it`. * `google/gemma-3-1b-pt`. * `google/gemma-3-4b-it`. * `google/gemma-3-4b-it-VLM`. * `google/gemma-3-4b-pt`. * `google/gemma-3-12b-it`. * `google/gemma-3-12b-it-VLM`. * `google/gemma-3-12b-pt`. * `google/gemma-3-27b-it`. * `google/gemma-3-27b-it-VLM`. * `google/gemma-3-27b-pt`. * `mistralai/Mixtral-8x7B-v0.1`. * `mistralai/Mistral-7B-Instruct-v0.2`. * `mistralai/Mistral-7B-v0.1`. * `togethercomputer/llama-2-7b-chat`. The following models have been deprecated and are no longer available on serverless: * `Wan-AI/Wan2.2-I2V-A14B`. * `Wan-AI/Wan2.2-T2V-A14B`. See [Deprecations](/docs/deprecations) for migration options. **July 28, 2026** ## A/B variant percent updates in the CLI `tg beta endpoints update` now accepts `--ab-percent` to change a variant's traffic percentage in an existing A/B experiment. The flag takes percentage from or returns it to the control only. Other variants stay unchanged. The control must remain at least 1%, and `--percent` on `tg beta endpoints ab` is limited to 1–99. See [Ramp the variant](/docs/dedicated-endpoints/ab-tests#ramp-the-variant) and the [endpoints CLI reference](/reference/cli/endpoints#update). ## Deploy replica bound inference `tg beta endpoints deploy` now infers a missing replica bound: `--min-replicas` alone mirrors into the max (including `0` to create a deployment stopped), and `--max-replicas 0` alone lowers the min to `0`. On `tg beta endpoints update`, stopping a deployment still requires both `--min-replicas 0` and `--max-replicas 0`. Passing a single zero bound is an error. See the [endpoints CLI reference](/reference/cli/endpoints#deploy). ## CLI upgrade notices The Together CLI now detects when a newer release is available and prints an upgrade notice at most once per day. Interactive sessions offer to run the upgrade in place, using the command that matches your install (`uv`, `pipx`, or `pip`). Set `TOGETHER_DISABLE_VERSION_CHECK=1` to turn the check off. See [Get started](/reference/cli/getting-started#upgrade-notices). ## Select dedicated endpoints in evaluations In the [evaluations console](https://api.together.ai/evaluations), live [dedicated model inference](/docs/dedicated-endpoints/overview) endpoints now appear under **My Endpoints** in the model picker. Legacy dedicated endpoints appear under **My Legacy Endpoints**. Only endpoints with at least one live deployment are listed. See [Supported models](/docs/evaluations-supported-models#dedicated-models). ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `MiniMaxAI/MiniMax-M2.7`. See [Deprecations](/docs/deprecations) for migration options. **July 27, 2026** ## GPU quota rejections return HTTP 429 Creating or updating a [dedicated endpoint](/docs/dedicated-endpoints/manage) deployment that would exceed your project or organization GPU quota now returns HTTP `429` with a message that names the GPU type and the would-be usage against the limit. Platform-wide capacity checks return the same status and ask you to retry later. See [Error codes](/docs/error-codes) and [Troubleshooting](/docs/dedicated-endpoints/manage#troubleshooting). ## CLI get by endpoint or deployment name `tg beta endpoints get` now accepts endpoint and deployment names in addition to IDs (`ep_...`, `dep_...`). You can also pass the name or ID directly as `tg beta endpoints `. If a bare deployment name matches more than one deployment, the CLI asks for a deployment ID or a fully qualified name. See [Get](/reference/cli/endpoints#get). ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `moonshotai/Kimi-K3`: 1,000,000 context length. Pricing: \$3.00 input / \$15.00 output / \$0.30 cached input (per 1M tokens). Supports function calling, structured outputs, and vision inputs. See [Kimi K3 quickstart](/docs/kimi-k3-quickstart) for details. ## New models available for fine-tuning You can now fine-tune the following models: * `Qwen/Qwen3.6-27B`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. **July 24, 2026** ## Python SDK realtime transcription The Together Python SDK now includes `client.beta.realtime.transcription()` for streaming speech-to-text over WebSocket. Install with `pip install "together[realtime]"`. The session reconnects with audio replay on transient drops, exposes normalized events such as `TranscriptDelta` and `TranscriptCompleted`, and supports application-level failover across endpoints with `RealtimeConnectionError` (`code="no_healthy_workers"`) and `session.pending_audio()`. See [Streaming transcription](/docs/inference/transcription/streaming). ## Fine-tuning comparison metrics filtering The [fine-tuning comparison view](https://api.together.ai/fine-tuning?view=comparison) now includes the same **Metrics filtering** control as the single-job Metrics tab. Adjust **Sampling rate** and **Step range**, then select **Apply** to re-fetch metrics for every selected job with matching filters. See [View metrics in the dashboard](/docs/fine-tuning/monitoring#view-metrics-in-the-dashboard). ## Cancel API key expiration You can remove a scheduled expiration from a project API key in the console. Open the three-dot menu next to a key that has a future expiration date, select **Cancel expiration**, and confirm. The key stays active and no longer expires automatically. See [Authentication](/docs/api-keys-authentication#best-practices). **July 23, 2026** ## Dedicated containers OpenAI-compatible endpoints [Dedicated container inference](/docs/dedicated-container-inference) now supports HTTP server mode for synchronous, OpenAI-compatible endpoints. Run your worker without the `--queue` flag, wire an OpenAI route with Sprocket, and call it with the OpenAI SDK or plain HTTP, with no Together-specific request shapes. See [Serve an OpenAI-compatible endpoint](/docs/dedicated-containers-openai). ## Fine-tuning output object names Fine-tune retrieve and list-checkpoints responses now include qualified Together model registry names alongside object IDs. On [`GET /fine-tunes/{id}`](/reference/get-fine-tunes-id), use `model_object_name` and `adapter_object_name` (LoRA jobs) for the final artifacts in `/` form. On [`GET /fine-tunes/{id}/checkpoints`](/reference/get-fine-tunes-id-checkpoint), each entry adds `object_name` with the same naming pattern (including `-` or `-adapter` suffixes). Names are resolved on retrieve only, not on list jobs. If the project slug cannot be resolved, the name field falls back to the object ID. On a completed job in the [fine-tuning jobs dashboard](https://api.together.ai/jobs), **Output model** shows the same qualified `model_object_name` and links to the registry model page. See [Model registry object IDs](/docs/fine-tuning/deployment#model-registry-object-ids). ## Fine-tuning checkpoint CLI output `tg fine-tuning list-checkpoints` now displays registry artifact IDs in the table output. The **Registry Artifact** column shows `object_id@object_revision_id`, and a copyable **Registry artifacts** block prints below the table. See [List checkpoints](/reference/cli/finetune#list-checkpoints). ## Fine-tuning preview CLI command `tg fine-tuning preview` samples rows from an uploaded JSONL training file and shows how a base model tokenizes them before you start a job. The table output highlights masked tokens, trained spans, and truncation. Pass `--json` for the full response. See [Preview](/reference/cli/finetune#preview). ## Worker engine cache metrics Dedicated endpoint Prometheus metrics now expose `worker_engine_kv_cache_utilization` and `worker_engine_cache_hit_rate` gauges. Use them to track KV-cache pressure and prefix-reuse efficiency on deployment workers. See [Monitor endpoints and deployments](/docs/dedicated-endpoints/monitoring). **July 22, 2026** ## GPU cluster host power-cycle repairs Node repair now includes a **Cycle** action, which cordons the bare-metal host and power-cycles it through its baseboard management controller (BMC). The repair preserves local scratch data, and the node keeps its host and node identity. Cycle is available only on supported hardware and for accounts where Together has enabled it. * **Console:** Select **Cycle** in the repair dialog, or choose it as the override action when you approve a recommendation from the **Repairs** tab. * **CLI:** Pass `--mode HOST_POWER_CYCLE` to `tg beta clusters remediations create`. * **API and SDK:** Set `mode` to `REMEDIATION_MODE_HOST_POWER_CYCLE` when you create a remediation. See [Node repair](/docs/node-repair) and the [clusters CLI reference](/reference/cli/clusters#create-a-node-remediation). ## Cluster remediation mode override `tg beta clusters remediations approve` now accepts a `--mode` flag to override the recommended repair action when you approve a node remediation. Choose reboot, quick reprovision, migrate to new host, or remove without changing the recommendation in the console first. See [Node repair](/docs/node-repair#override-the-recommended-action) and the [clusters CLI reference](/reference/cli/clusters). **July 21, 2026** ## GPU cluster add-on CLI flags `tg beta clusters create` and `tg beta clusters update` now expose flags for Headlamp and Slurm Web cluster add-ons. * **Create:** Pass `--headlamp-addon` or `--slurm-web-addon` to enable an add-on at cluster creation. * **Update:** Pass `--headlamp` / `--no-headlamp` or `--slurm-web` / `--no-slurm-web` to toggle add-ons on an existing cluster. See the [clusters CLI reference](/reference/cli/clusters). ## MoE expert-LoRA target modules Fine-tuning jobs on supported mixture-of-experts models can now target expert feed-forward layers instead of attention projections. Set `lora_trainable_modules` to `w_up,w_gate,w_down` to train a compact shared-factor adapter across experts, useful when adapting domain knowledge rather than attention patterns. See [Target MoE expert layers](/docs/fine-tuning/lora-vs-full#target-moe-expert-layers). ## Jig environment variable collision validation `jig deploy` now rejects configs where the same name appears in both `[tool.jig.deploy.environment_variables]` and secrets. The error lists each colliding name so you can remove the duplicate or unset the secret before redeploying. See [Secrets](/docs/deployments-jig#secrets). ## New models available for fine-tuning You can now fine-tune the following models: * `zai-org/GLM-5.1`. * `zai-org/GLM-5`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. ## Pairwise InfiniBand write bandwidth health check You can now run a Pairwise InfiniBand Write Bandwidth active health check on GPU clusters. It measures `ib_write_bw` throughput between exactly two nodes across InfiniBand rails, with configurable RDMA memory and traffic direction. See [Health checks](/docs/health-checks) for the available tests, thresholds, and results. **July 20, 2026** ## Fine-tuning metrics dashboard Fine-tuning jobs now have a **Metrics** tab in the [web dashboard](https://api.together.ai/fine-tuning) that charts training progress. Metrics stream in live while a job runs and stay available after it completes. **What's new:** * **Live training curves:** Watch training loss, learning rate, and gradient norm update as the job trains, without leaving the dashboard. * **Preference-tuning metrics:** DPO and other preference jobs add reward accuracy, reward margin, chosen and rejected rewards and log-probabilities, and approximate KL. * **Interactive charts:** Zoom and pan across all charts on a shared step axis, switch the x-axis between step and time, toggle linear or logarithmic scales, and sync a hover crosshair across every metric. * **Compare runs:** Overlay metrics from multiple jobs to [compare fine-tuning runs](https://api.together.ai/fine-tuning?view=comparison) side by side. ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `deepseek-ai/DeepSeek-V4-Flash`. ## Model revision validation status Model and adapter revision APIs now return `validationStatus`, `lastValidatedAt`, and `validationErrors` on each revision. Poll validation before you pin a revision in a deployment. A revision must reach `REVISION_VALIDATION_STATUS_SUCCESS` before it can deploy when referenced explicitly. See [Check revision validation](/docs/dedicated-endpoints/custom-models#check-revision-validation). ## GPU cluster reserved GPU increases You can now increase the prepaid reserved GPU count on a reserved cluster through the API and CLI, without changing its total `num_gpus`. Set `num_reserved_gpus` when you update the cluster. See [Manage GPU clusters](/docs/gpu-clusters-management#update-cluster-gpu-counts). **July 17, 2026** ## Privacy and training opt-in settings Training opt-in and other privacy toggles now live under **Privacy** in [Organization Settings](https://api.together.ai/settings/organization/~current). Organization admins control data-sharing settings for all traffic sent under the organization's API keys. See [Privacy and security](/docs/privacy-and-security). ## Dedicated endpoint deployment listing Endpoint get and list responses now include at most the 10 newest deployment summaries per endpoint. Use the deployments list API to retrieve every deployment on an endpoint. See [Manage endpoints and deployments](/docs/dedicated-endpoints/manage). **July 16, 2026** ## Dedicated model inference [Dedicated model inference](/docs/dedicated-endpoints/overview) (DMI) serves a model on reserved GPUs, giving you higher throughput, lower latency, and predictable performance with no hard rate limits. It uses the same [inference APIs](/docs/inference/overview#shared-inference-api) as serverless, so you can prototype on serverless and deploy on dedicated hardware without changing your application code. **What's new:** * **Deploy in one command:** `tg beta endpoints deploy` creates an endpoint, attaches a deployment, and routes all traffic to it. * **New resource model:** Compose models, configs, endpoints, deployments, and traffic splits to control how your model is served. See [Concepts](/docs/dedicated-endpoints/concepts). * **A/B tests and shadow experiments:** [Split live traffic across variants](/docs/dedicated-endpoints/ab-tests), or [mirror traffic to a new deployment](/docs/dedicated-endpoints/shadow-experiments) without serving its responses. * **Autoscaling and serving controls:** Scale on request or GPU metrics, scale to zero on idle, and tune serving behavior per deployment. See [Configure autoscaling](/docs/dedicated-endpoints/scaling). > [!NOTE] > > If you're already using dedicated endpoints, you can migrate to the v2 API by following the [migration guide](/docs/dedicated-endpoints/migrate-from-v1). ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `thinkingmachines/Inkling`: 552.8B parameters, 524,288 context length, NVFP4 quantization. Pricing: \$1.00 input / \$4.05 output / \$0.17 cached input (per 1M tokens). ## Image inputs for evaluations You can now evaluate vision-capable models on image datasets. Add an `image_data_urls` column to your evaluation dataset (a base64 image data URL, or a list of them) and the images are attached to the model and judge requests alongside the text prompt. See [Prepare a dataset](/docs/run-an-evaluation#prepare-a-dataset) for details. ## GPU cluster GPU count breakdown Cluster retrieve and list responses now include `num_reserved_gpus` and `num_capacity_pool_gpus` alongside `num_gpus`, so you can see how total capacity splits between prepaid reserved GPUs and GPUs drawn from a capacity pool. See [Manage GPU clusters](/docs/gpu-clusters-management#inspect-cluster-gpu-counts) for details. ## Remediation linked alerts Remediation retrieve and list responses now include `linked_alerts`, an array of passive health check alerts tied to the repair (including resolved alerts). See [Node repair](/docs/node-repair#linked-alerts-in-api-responses) for details. ## Clear a deployment queue The Queue API adds `POST /queue/clear` (`client.beta.jig.queue.clear`) to cancel all pending jobs for a model in one call. Running jobs are left untouched, and the response reports how many pending jobs were canceled. See [Queue API](/docs/deployments-queue#clearing-pending-jobs) for details. ## Fine-tuning artifact registry IDs Fine-tune job and checkpoint responses now include Together model registry IDs for completed artifacts. Use `model_object_id` and `model_object_revision_id` on completed jobs, `adapter_object_id` and `adapter_object_revision_id` on LoRA jobs, and `object_id` and `object_revision_id` on [list checkpoints](/reference/cli/finetune#list-checkpoints) entries to reference weights in the model registry. The [Together Python SDK](https://github.com/togethercomputer/together-py) (2.24+) and [Together TypeScript SDK](https://github.com/togethercomputer/together-typescript) expose these fields on retrieve and list-checkpoints responses. ## Together Python SDK 2.24 [Together Python SDK](https://github.com/togethercomputer/together-py) 2.24 is available. OIDC cluster SSH (`tg beta clusters ssh`) no longer requires a Together API key, and the bastion-to-target SSH hop skips host key prompts for ephemeral cluster nodes. See [SSH into a cluster](/reference/cli/clusters#ssh-into-a-cluster). **July 15, 2026** ## TogetherLink TogetherLink is an open-source launcher that connects Claude Code, Codex, ChatGPT Desktop, Pi Code, and OpenCode to models hosted by Together AI. Install with one command and run your existing tools without hand-editing provider settings. See [TogetherLink](/docs/togetherlink). ## Slurm cluster OIDC SSH Slurm GPU clusters with OIDC enabled now support browser-based SSH through the Together CLI. To sign in without uploading an SSH key, select **OIDC** on the cluster details page. Key-based SSH remains available. See [Connect over SSH](/docs/gpu-clusters-ssh). ## Fine-tuning model limits API The model limits endpoint now returns `supports_full_training` so you can check whether a model supports full fine-tuning before submitting a job. When the field is `false`, the model is LoRA-only. See [LoRA vs. full fine-tuning](/docs/fine-tuning/lora-vs-full#what-to-expect-from-full-fine-tuning). **July 14, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `google/gemma-4-12B-it`: 262,144 context length. ## GPU cluster health monitoring Passive health checks now document the full set of monitored failure signals and their recommended repair actions. Slurm node unavailability surfaces as a warning-only alert without an automated repair action. See [Health checks](/docs/health-checks#passive-health-checks) and [Node repair](/docs/node-repair#recommended-repair-actions). **July 10, 2026** ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `Qwen/Qwen3-235B-A22B-Instruct-2507-tput`. Available as an on-demand dedicated endpoint. * `meta-llama/Meta-Llama-3-8B-Instruct-Lite`. Available as an on-demand dedicated endpoint. * `zai-org/GLM-5.1`. Available as an on-demand dedicated endpoint. See [Deprecations](/docs/deprecations) for migration options. **July 9, 2026** ## TorchTitan training health check You can now run a TorchTitan training health check on your GPU clusters. It runs a short training benchmark on one or more nodes and measures steady-state model FLOPs utilization (MFU) to validate end-to-end training throughput. This feature is in preview and runs on demand on NVIDIA B200 (Blackwell) nodes. See [Health checks](/docs/health-checks) for the available tests, thresholds, and results. ## Storage performance health check You can now run a storage performance health check on your GPU clusters. It uses `fio` to validate data integrity and measure sequential read and write bandwidth on the cluster's storage volumes, and it also runs automatically during cluster acceptance testing. See [Health checks](/docs/health-checks) for the available tests, thresholds, and results. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `LiquidAI/LFM2.5-8B-A1B`: 32,768 context length. Pricing: \$0.03 input / \$0.12 output (per 1M tokens). ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `LiquidAI/LFM2-24B-A2B`. Recommended replacement: `LiquidAI/LFM2.5-8B-A1B`. See [Deprecations](/docs/deprecations) for migration options. **July 8, 2026** ## Provisioned throughput [Provisioned throughput](/docs/inference/provisioned-throughput) is now available, allowing you to reserve inference capacity for frontier open models. Commit to a one-month-or-longer term, and Together commits to throughput and reliability targets for traffic within your purchased capacity. At launch, provisioned throughput is available for `MiniMaxAI/MiniMax-M3` and `zai-org/GLM-5.2`. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `HappyHorse/HappyHorse-1.0-T2V` (text-to-video). ## Reasoning API field The `reasoning` field is now symmetric for input and output on reasoning models. Pass prior assistant reasoning back under `reasoning` for preserved thinking and multi-turn tool calling. The older `reasoning_content` key is still accepted on input for backward compatibility. See [Reasoning](/docs/inference/chat/reasoning#handle-reasoning-tokens) for details. ## Usage object shape The `usage` object varies by model. Reasoning models nest cached and reasoning token counts under `prompt_tokens_details` and `completion_tokens_details`, while some non-reasoning models return `cached_tokens` at the top level. Read both shapes defensively so clients do not silently report zero. See [OpenAI compatibility](/docs/inference/openai-compatibility#response-shape-differences) for examples. **July 7, 2026** ## Project slug editing Project admins can now change a project's slug from Project Settings. The new slug takes effect immediately. You can also copy any project's slug from the projects list in Organization Settings. Changing a slug can break API requests, scripts, and integrations that reference resources by their slug-qualified path. Update any references that rely on the old slug. See [Projects](/docs/projects#changing-a-project-slug) for details. ## GPU cluster creation region selection The create cluster flow now defaults the **Region** field to **Any region**. Together picks the region with the most available capacity for your GPU type at create time. Changing the GPU type resets the region to **Any region** and clears any selected shared volume. See the [GPU Clusters quickstart](/docs/gpu-clusters-quickstart) for the full create flow. **July 6, 2026** ## New models available for fine-tuning You can now fine-tune the following vision-language model: * `google/gemma-4-31B-it-VLM`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. ## Cost analytics units view Organization and project cost analytics now include a **Measure** control to switch between **Cost (\$)** and **Units**. Choose **Units** to chart daily billable quantities (for example, tokens) by product, line item, project, or API key instead of dollar spend. See [Cost analytics](/docs/billing-cost-analytics) for details. **July 2, 2026** ## Bring your own model: Transformers v5 [BYOM fine-tuning](/docs/fine-tuning/byom) now supports Hugging Face models built with Transformers v5 or earlier. **July 1, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `google/flash-image-3.1-lite` (Gemini 3.1 Flash-Lite Image). * `Qwen/Qwen3.6-35B-A3B-Lora`: 262,144 context length. * `alibaba/happyhorse-1.1-i2v` (image-to-video). * `alibaba/happyhorse-1.1-r2v` (reference-to-video). * `alibaba/happyhorse-1.1-t2v` (text-to-video). **June 29, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `Qwen/Qwen3.5-397B-A17B`. See [Deprecations](/docs/deprecations) for migration options. **June 26, 2026** ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `zai-org/GLM-5.1`. Available as an on-demand dedicated endpoint. * `meta-llama/Meta-Llama-3-8B-Instruct-Lite`. Available as an on-demand dedicated endpoint. * `google/gemma-3n-E4B-it`. Available as an on-demand dedicated endpoint. * `Qwen/Qwen3-235B-A22B-Instruct-2507-tput`. Available as an on-demand dedicated endpoint. * `meta-llama/Llama-Guard-4-12B`. See [Deprecations](/docs/deprecations) for migration options. **June 25, 2026** ## Seedance 2.0 adds 4K video `ByteDance/Seedance-2.0` now supports a `4k` resolution tier (up to 3840x2160), alongside the existing 480p, 720p, and 1080p tiers. Pass `resolution: "4k"` to generate at the new tier. Pricing for the higher tiers (per second of output): * 1080p: \$0.40 (text/image-to-video), from \$0.48 (video-to-video). * 4K: \$0.836 (text/image-to-video), from \$1.050 (video-to-video). See [Seedance 2.0](/docs/seedance2.5-quickstart) for details. **June 24, 2026** ## Automatic node repair for GPU clusters GPU clusters now support passive health checks and automatic node repair. Passive checks monitor your nodes continuously in the background, and when they (or active checks) detect a node-level issue, the system generates a repair recommendation for you to review and accept from the new **Repairs** tab. Together then handles the cordon, drain, remediation, and node rejoin. See [Health checks](/docs/health-checks) and [Node repair](/docs/node-repair) for details. ## Estimate fine-tuning job cost via API A new endpoint, `POST /fine-tunes/estimate-price`, returns the estimated total price of a fine-tuning job before you launch it, along with estimated training and evaluation token counts and your remaining credit limit. Call it from the Python SDK or TypeScript SDK with the same parameters you plan to submit to the create-job endpoint. See [Fine-tuning pricing](/docs/fine-tuning/pricing#estimate-job-cost) for details. ## New models available for fine-tuning You can now fine-tune the following models: * `moonshotai/Kimi-K2.7-Code`. * `moonshotai/Kimi-K2.6`. See [Supported models](/docs/fine-tuning/supported-models) for the full list. **June 23, 2026** ## Whoami API endpoint Use `GET /whoami` to confirm which API key, project, and organization are authenticating a request. The response includes the project slug used in dedicated endpoint model names. See [Whoami](/reference/whoami) for details. ## Early stopping for fine-tuning Fine-tuning jobs now support early stopping, which halts training when validation loss stops improving. This reduces cost and helps avoid overfitting on long runs. Enable it by setting `early_stopping_enabled=true` on job creation along with a `validation_file` and `n_evals >= early_stopping_patience + early_stopping_warmup_evals + 1`. Tune behavior with `early_stopping_patience`, `early_stopping_min_delta`, and `early_stopping_warmup_evals`. When training halts early, the job still finishes with status `completed`. The response sets `early_stopped=true` and exposes the winning checkpoint via `early_stopping_best_step` and `early_stopping_best_metric`. See [Early stopping](/docs/fine-tuning/early-stopping) for details. ## Audio transcription upload limit Direct (binary) audio uploads for transcription and translation are now capped at 80 MB per request. For larger files, host the audio at a public HTTPS URL and pass that URL as the `file` field, which supports up to 1 GB. When sending a binary upload, place the `model` form field before the `file` field in the multipart body. See [Transcribe audio](/docs/inference/transcription/overview#limits) for details. **June 22, 2026** ## Attach LoRA adapters to a dedicated endpoint You can now attach multiple LoRA adapters to a single LoRA-enabled dedicated endpoint so they share the same hardware, instead of deploying one endpoint per adapter. Manage bindings from the [Python SDK](/python-library), the TypeScript SDK, the CLI, or the API: * `together endpoints adapters add :` * `together endpoints adapters list ` * `together endpoints adapters remove :` This feature is in preview. See [Attach a LoRA adapter to an endpoint](/docs/dedicated-endpoints/v1/lora-adapter). ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `zai-org/GLM-5`. Recommended replacement: `zai-org/GLM-5.2`. See [Deprecations](/docs/deprecations) for migration options. **June 17, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `zai-org/GLM-5.2`: 262K context length, FP4 quantization. Pricing: \$1.40 input / \$4.40 output / \$0.26 cached input (per 1M tokens). Supports function calling and structured outputs. ## Organization and project role labels Organization members now use the Admin and Developer labels, and project collaborators now use the Admin and Editor labels. Permissions are unchanged, but the labels make organization-wide access and project-scoped editing clearer. See [Roles & permissions](/docs/roles-permissions) for details. **June 15, 2026** ## Model deprecations The following models are scheduled for deprecation and will no longer be available on serverless after June 29, 2026: * `Qwen/Qwen3.5-397B-A17B`. Recommended replacement: `MiniMaxAI/MiniMax-M3`, available as an on-demand dedicated endpoint. See [Deprecations](/docs/deprecations) for migration options. **June 13, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `moonshotai/Kimi-K2.7-Code`: 262,144 context length, FP4 quantization. Pricing: \$0.95 input / \$4.00 output / \$0.19 cached input (per 1M tokens). Supports function calling and structured outputs. **June 12, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `MiniMaxAI/MiniMax-M3`: 524,288 context length, FP4 quantization. Pricing: \$0.30 input / \$1.20 output / \$0.06 cached input (per 1M tokens). **June 11, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `mistralai/Voxtral-Mini-3B-2507`. Available as an on-demand dedicated endpoint. See [Deprecations](/docs/deprecations) for migration options. **June 9, 2026** ## Pricing update The following changes are effective June 9, 2026: **New cached input pricing** (per 1M tokens): * `zai-org/GLM-5.1`: \$0.26 cached input (81% discount from \$1.40 standard input). * `Qwen/Qwen3.5-397B-A17B`: \$0.35 cached input (42% discount from \$0.60 standard input). **Price decrease** for `deepseek-ai/DeepSeek-V4-Pro` (per 1M tokens): * Input: \$2.10 → \$1.74. * Output: \$4.40 → \$3.48. * Cached input: \$0.20 (unchanged). See [Serverless models](/docs/serverless/models) for the full pricing catalog. **June 8, 2026** ## Server-side validation for fine-tuning datasets Files uploaded for fine-tuning now go through full server-side schema validation during ingestion, with the result exposed on the file object. Poll the Files API and read `processing_status` (`COMPLETED`, `INVALID_FORMAT`, or `FAILED`) plus `validation_report` to detect dataset issues programmatically before launching a job, like missing `role` fields or malformed conversation turns. Errors include a user-facing reason, so you can fix the dataset and re-upload without trial-and-error training runs. For example: ``` Line 7: messages[1] must contain a role field ``` **June 4, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8`. Recommended replacement: `MiniMaxAI/MiniMax-M2.7`, available as an on-demand dedicated endpoint. See [Deprecations](/docs/deprecations) for migration options. **June 1, 2026** ## Fine-tuning job metrics API A new API endpoint, `GET /fine-tunes/{id}/metrics`, returns training metrics for a fine-tuning job (e.g. loss curves and other per-step values) so you can monitor progress programmatically without opening the dashboard. See the [API reference](/reference/get-fine-tunes-id-metrics) and [Fine-tuning training metrics](/docs/fine-tuning-training-metrics) for details. ## Slurm startup scripts for GPU Clusters GPU clusters now support Slurm startup scripts (lifecycle hook scripts that run at node startup, job allocation, and job completion). Use them to install packages at boot, configure SSH sessions, or run per-job prolog and epilog actions across worker, login, and controller nodes. See [Slurm startup scripts](/docs/slurm-startup-scripts) for details. ## Evaluations: single-pass compare mode The `compare` evaluator now accepts a `disable_position_bias_correction` parameter. By default, the judge runs each comparison twice (A→B then B→A) and reconciles verdicts to cancel position bias. Setting `disable_position_bias_correction` to `true` runs a single pass, cutting judge cost and latency in half. See the [evaluations reference](/docs/evaluations-reference#evaluation-type-parameters) for details. ## Billing documentation updates Updated billing docs for multiple payment methods, separate invoice addresses, ACH payment behavior, auto-recharge limits with bank transfers, and prepaid-only access (no negative balance limits). See [Payment methods & invoices](/docs/billing-payment-methods), [Credits](/docs/billing-credits), and [Billing troubleshooting](/docs/billing-troubleshooting). **May 29, 2026** ## Pricing update The following models have updated pricing, effective May 29, 2026. All usage from that date forward will be billed at the new rates (per 1M tokens): * `Qwen/Qwen3.5-9B`: \$0.10 → \$0.17 (input), \$0.15 → \$0.25 (output). * `meta-llama/Meta-Llama-3-8B-Instruct-Lite`: \$0.10 → \$0.14 (input), \$0.10 → \$0.14 (output). * `meta-llama/Llama-3.3-70B-Instruct-Turbo`: \$0.88 → \$1.04 (input), \$0.88 → \$1.04 (output). See [Serverless models](/docs/serverless/models) for the full pricing catalog. **May 27, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `black-forest-labs/FLUX.1-krea-dev`. See [Deprecations](/docs/deprecations) for migration options. **May 25, 2026** ## New serverless models The following image and video models are now available on [serverless](/docs/serverless/models): **Image** * `ByteDance/Seedream-5.0-lite`. **Video** * `alibaba/happyhorse-1.0-i2v` (image-to-video). * `alibaba/happyhorse-1.0-r2v` (reference-to-video). * `google/veo-3.1`. * `google/veo-3.1-lite`. ## New dedicated endpoint models The following models are now available for deployment on [dedicated endpoints](/docs/dedicated-endpoints/models): * `google/gemma-3-1b-it`. * `google/gemma-3-27b-it`. * `google/gemma-3-27b-it-lora`. * `google/gemma-4-31B-it-lora`. * `google/medgemma-27b-text-it`. * `allenai/Molmo-7B-D-0924`. * `meta-llama/Llama-3.2-3B-Instruct`. * `meta-llama/Llama-4-Scout-17B-16E-Instruct-FP8-Lora`. * `Qwen/Qwen2.5-14B`. * `Qwen/Qwen2.5-32B`. * `Qwen/Qwen3-235B-A22B-Instruct-2507-FP8`. * `Qwen/Qwen2-72B`. * `arcee-ai/trinity-mini`. * `BAAI/bge-base-en-v1.5`. * `minimax/speech-2.8-turbo`. * `rime-labs/rime-mist-v3`. * `rime-labs/rime-mist-v3-omni`. ## Seedance 2.0 quickstart A quickstart is now available for [Seedance 2.0](/docs/seedance2.5-quickstart), ByteDance's unified multimodal audio-video generation model. The guide covers text-to-video, image-to-video, video extension, and instruction-based editing. **May 22, 2026** ## GPU clusters: external OIDC authentication and RBAC GPU clusters now support external OpenID Connect (OIDC) authentication, allowing each team member to access the cluster's Kubernetes API using their organization's identity provider: Google, Okta, Auth0, Microsoft Entra ID, and others. With OIDC enabled, access is managed through standard Kubernetes RBAC: admins bind permissions to individual user identities, and each user authenticates via their browser using SSO. This replaces shared kubeconfig credentials with per-user tokens, per-user audit trails, and clean revocation. Currently this feature is only supported for Kubernetes clusters. OIDC must be configured at cluster creation time. See [Set up OIDC authentication](/docs/cluster-oidc) for the full setup guide. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Qwen/Qwen3.7-Max`. Pricing: \$2.50 input / \$7.50 output (per 1M tokens). **May 21, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `moonshotai/Kimi-K2.5`. See [Deprecations](/docs/deprecations) for migration options. **May 15, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `pearl-ai/gemma-4-31b-it`: 32,000 context length, INT8 quantization. Pricing: \$0.28 input / \$0.86 output (per 1M tokens). **May 14, 2026** ## Model deprecations The following models have been deprecated and are no longer available on serverless: * `deepseek-ai/DeepSeek-R1`. * `deepseek-ai/DeepSeek-V3.1`. * `Qwen/Qwen3-Coder-Next-FP8`. ## Upcoming pricing update The following model will have updated pricing, effective May 21, 2026: * `google/gemma-4-31b-it`: \$0.20 → \$0.39 (input), \$0.50 → \$0.97 (output) per 1M tokens. All usage from that date forward will be billed at the new rate. **May 8, 2026** ## External collaborators for projects You can now invite users from outside your organization to collaborate on a project. Enable **Allow external collaborators** on the project's settings page, then add them like any other collaborator. The feature is currently in beta. See [roles & permissions](/docs/roles-permissions#external-collaborators-beta) for more details. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `alibaba/happyhorse-1.0-t2v`: \$0.24/sec at 1080p. * `ByteDance/Seedance-2.0`: \$0.16/sec at 720p. **May 7, 2026** ## Together CLI v2.10 The Together CLI has been updated with `tg` as the canonical command name and a refreshed command tree. Subcommands are now clearer and more consistent across fine-tuning, endpoints, evals, files, clusters, and jig. See [CLI reference](/reference/cli/getting-started) for details. ## Speech-to-text and translation: new audio formats The `/v1/audio/transcriptions` and `/v1/audio/translations` endpoints now accept `.ogg`, `.opus`, and `.aac` files in addition to `.wav`, `.mp3`, `.m4a`, `.webm`, and `.flac`. ## Speech-to-text: task field is now optional in verbose JSON responses The `task` field has been removed from the required fields of `AudioTranscriptionVerboseJsonResponse` and `AudioTranslationVerboseJsonResponse`. Clients that previously asserted on its presence should treat it as optional. **May 6, 2026** ## Slurm-on-Kubernetes v1.0 for all new Slurm clusters All newly provisioned Slurm GPU clusters now run on a new Slurm-on-Kubernetes stack with significant reliability improvements. Existing clusters can be migrated in place. **What's new:** * **Self-healing worker daemons:** The Slurm worker daemon is now supervised and auto-restarts on crash, so transient failures recover without operator intervention or impact on healthy nodes. * **Durable job accounting:** Job history (`sacct`) is now persisted on durable, PVC-backed storage. Restarts and pod reschedules no longer wipe accounting data. * **Correct process tracking and cleanup:** Job processes (including daemonized children) are tracked at the kernel cgroup level and reliably cleaned up at job completion. No more orphaned processes holding GPU memory or `/dev/shm`. * **Zombie reaping:** A dedicated init process reaps orphaned children, preventing PID-table exhaustion from blocking new jobs. * **GPU state correctness:** The Slurm GPU view is rebuilt fresh on every node start, eliminating "GPU not found" failures after pod reschedules. * **Per-cluster GPU utilization metrics:** DCGM metrics are now exposed in your cluster's Grafana dashboards for fine-grained utilization visibility. See [Slurm configuration](/docs/slurm-configuration) for more details. **May 1, 2026** ## Model deprecations The following model has been deprecated and is no longer available on serverless: * `MiniMaxAI/MiniMax-M2.5`. **April 30, 2026** ## Text-to-speech: pronunciation\_dict parameter A new `pronunciation_dict` parameter is available for TTS requests. Pass a list of `"/"` rules (e.g., `["omg/oh my god"]`) to override how the model pronounces specific tokens. ## Together Deployments: custom metric autoscaling Deployments can now autoscale on any Prometheus metric exposed by your worker's `/metrics` endpoint. Set `metric = "CustomMetric"` and provide a `custom_metric_name` (e.g., `vllm:num_requests_running`) along with a `target` to scale on application-specific signals. **April 28, 2026** ## Fine-tuning: new supported models The following models are now available for fine-tuning: * `Qwen/Qwen3.6-35B-A3B`. * `google/gemma-4-31B-it`. * `google/gemma-4-26B-A4B-it`. **April 24, 2026** ## DeepSeek-V4-Pro on serverless `deepseek-ai/DeepSeek-V4-Pro` has been added to serverless. * Context length: 512,000. * Pricing: \$2.10 input / \$4.40 output / \$0.20 cached input (per 1M tokens). * Quantization: FP4. * Function calling and structured outputs supported. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `deepcogito/cogito-v2-1-671b`. * `google/veo-3.1-test-debug`. * `vidu/vidu-q3`. * `vidu/vidu-q3-turbo`. * `Wan-AI/wan2.7-i2v`. * `Wan-AI/wan2.7-r2v`. ## Pricing update: no-packing fine-tuning jobs Rolled out a pricing update for no-packing fine-tuning jobs. When the no-packing option is chosen, the number of training dataset tokens is now calculated as `len(dataset) * max_seq_length` to account for the compute used by packing-free jobs. * `max_seq_length` is configurable in both the SDK and UI. * Price prediction reflects these changes, so if no-packing is chosen you can control the cost of the job by adjusting the sequence length. **April 22, 2026** ## Dynamic rate limits and prepaid billing * Build Tiers 1–5, Scale, and Enterprise tier labels have been retired. Dynamic rate limits are now live for all users. * Billing has moved to a fully prepaid model. * Model-specific tier gates have been removed. The platform-wide \$5 credit purchase is the only gate. ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `moonshotai/Kimi-K2.6`. **April 15, 2026** ## Pricing update The following model has updated pricing, effective April 15, 2026: * **`google/gemma-3n-E4B-it`:** \$0.02 → \$0.06 (input), \$0.04 → \$0.12 (output) per 1M tokens. **April 14, 2026** ## Model deprecations The following models have been deprecated and are no longer available: * `Qwen/Qwen3-VL-8B-Instruct`. * `Qwen/Qwen3-235B-A22B-Thinking-2507`. * `mistralai/Mixtral-8x7B-Instruct-v0.1`. **April 11, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `MiniMaxAI/MiniMax-M2.7`. **April 8, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `google/gemma-4-31B-it`. * `zai-org/GLM-5.1`. **April 2, 2026** ## Model deprecations The following models have been deprecated and are no longer available: * `zai-org/GLM-4.5-Air-FP8`. * `zai-org/GLM-4.7`. * `Qwen/Qwen3-Next-80B-A3B-Instruct`. **March 31, 2026** ## Model deprecations The following model has been deprecated and is no longer available: * `meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8`. **March 10, 2026** ## Cached input token pricing Cached input token pricing is now available: * `MiniMaxAI/MiniMax-M2.5`: \$0.06 per 1M cached input tokens (80% off standard input price). **March 7, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Qwen/Qwen3.5-9B`. **March 6, 2026** ## Model deprecations The following models have been deprecated and are no longer available: * `mixedbread-ai/Mxbai-Rerank-Large-V2`. * `moonshotai/Kimi-K2-Thinking`. * `meta-llama/Llama-3.2-3B-Instruct-Turbo`. * `moonshotai/Kimi-K2-Instruct-0905`. **February 25, 2026** ## Model deprecations The following models have been deprecated and are no longer available: * `black-forest-labs/FLUX.1-dev`. * `black-forest-labs/FLUX.1-dev-lora`. * `black-forest-labs/FLUX.1-kontext-dev`. * `Qwen/Qwen3-VL-32B-Instruct`. * `mistralai/Ministral-3-14B-Instruct-2512`. * `Qwen/Qwen3-Next-80B-A3B-Thinking`. * `Alibaba-NLP/gte-modernbert-base`. * `BAAI/bge-base-en-v1.5`. * `meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo`. * `meta-llama/Llama-Guard-3-11B-Vision-Turbo`. * `meta-llama/LlamaGuard-2-8b`. * `marin-community/marin-8b-instruct`. * `nvidia/NVIDIA-Nemotron-Nano-9B-v2`. **February 16, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Qwen/Qwen3.5-397B-A17B`. **February 15, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `MiniMaxAI/MiniMax-M2.5`. **February 13, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `zai-org/GLM-5`. **February 12, 2026** ## Dedicated container inference launch Together AI has officially launched [Dedicated Container Inference](https://www.together.ai/dedicated-container-inference) (DCI), formerly known as BYOC. DCI lets you containerize, deploy, and scale custom models on Together AI. * [Blog post](https://www.together.ai/blog/dedicated-container-inference). * [Documentation](/docs/dedicated-container-inference). * [Getting started](/docs/containers-quickstart#tutorials). **February 6, 2026** ## Model deprecations The following models have been deprecated and are no longer available: * `togethercomputer/m2-bert-80M-32k-retrieval`. * `Salesforce/Llama-Rank-V1`. * `togethercomputer/Refuel-Llm-V2`. * `togethercomputer/Refuel-Llm-V2-Small`. * `Qwen/Qwen3-235B-A22B-fp8-tput`. * `qwen-qwen2-5-14b-instruct-lora`. * `meta-llama/Llama-4-Scout-17B-16E-Instruct`. * `Qwen/Qwen2.5-72B-Instruct-Turbo`. * `meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo`. * `BAAI/bge-large-en-v1.5`. **February 4, 2026** ## Python SDK v2.0 general availability Together AI is releasing the **Python SDK v2.0**, a new, type-safe, OpenAPI-driven client designed to be faster, easier to maintain, and ready for everything Together AI is building next. * **Install:** `pip install together` or `uv add together`. * **Migration guide:** A detailed [Python SDK Migration Guide](/docs/pythonv2-migration-guide) covers API-by-API changes, type updates, and troubleshooting tips. * **Code and docs:** Access the [Together Python v2 repo](https://github.com/togethercomputer/together-py) and [reference docs](/reference/chat-completions-1) with code examples. * **Main goal:** Replace the legacy v1 Python SDK with a modern, strongly-typed, OpenAPI-generated client that matches the API surface more closely and stays in lock-step with new features. * **Net new:** All new features will be built in version 2 moving forward. This first version already includes beta APIs for instant clusters. **February 3, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `Qwen/Qwen3-Coder-Next-FP8`. ## Model deprecations The following models have been deprecated and are no longer available: * `deepseek-ai/DeepSeek-R1-0528-tput`. **January 29, 2026** ## Model redirects The following models are now being automatically redirected to their upgraded versions. See the [Model Lifecycle Policy](/docs/deprecations#model-lifecycle-policy) for details. | Original model | Redirects to | | :- | :- | | `mistralai/Mistral-7B-Instruct-v0.3` | `mistralai/Ministral-3-14B-Instruct-2512` | | `zai-org/GLM-4.6` | `zai-org/GLM-4.7` | These are same-lineage upgrades with compatible behavior. If you need the original version, deploy it as a [dedicated endpoint](/docs/dedicated-endpoints). **January 27, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `moonshotai/Kimi-K2.5`. **January 23, 2026** ## Model redirects The following models are now being automatically redirected to their upgraded versions. See the [Model Lifecycle Policy](/docs/deprecations#model-lifecycle-policy) for details. | Original model | Redirects to | | :- | :- | | `DeepSeek-V3-0324` | `DeepSeek-V3.1` | These are same-lineage upgrades with compatible behavior. If you need the original version, deploy it as a [dedicated endpoint](/docs/dedicated-endpoints). **January 21, 2026** ## Prompt caching now enabled by default for dedicated model inference Prompt caching is now **automatically enabled** for all newly created dedicated endpoints. This change improves performance and reduces costs by default. **What's changing:** * The `disable_prompt_cache` field (API), `--no-prompt-cache` flag (CLI), and related SDK parameters are now **deprecated**. * Prompt caching will always be enabled. The field is accepted but ignored after deprecation. **Timeline:** * **Now:** Field is deprecated. Setting it has no effect (prompt caching is always on). * **February 2026:** Field will be removed. **Action required:** * `--no-prompt-cache` in CLI commands has no effect. You can remove it. * `disable_prompt_cache` from API requests has no effect. You can remove it. * SDK calls that set this parameter have no effect. You can remove it. No changes are required for existing endpoints. This only affects endpoint creation. **January 9, 2026** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `zai-org/GLM-4.7`. **January 5, 2026** ## Model deprecations The following models have been deprecated and are no longer available: * `Qwen/Qwen2.5-VL-72B-Instruct`. **December 23, 2025** ## Model deprecations The following models have been deprecated and are no longer available: * `deepseek-ai/DeepSeek-R1-Distill-Llama-70B`. * `meta-llama/Meta-Llama-3-70B-Instruct-Turbo`. * `black-forest-labs/FLUX.1-schnell-free`. * `meta-llama/Meta-Llama-Guard-3-8B`. **December 17, 2025** ## Model redirects The following models are now being automatically redirected to their upgraded versions. See the [Model Lifecycle Policy](/docs/deprecations#model-lifecycle-policy) for details. | Original model | Redirects to | | :- | :- | | `Kimi-K2` | `Kimi-K2-0905` | | `DeepSeek-V3` | `DeepSeek-V3-0324` | | `DeepSeek-R1` | `DeepSeek-R1-0528` | These are same-lineage upgrades with compatible behavior. If you need the original version, deploy it as a [dedicated endpoint](/docs/dedicated-endpoints). **December 12, 2025** ## Python SDK v2.0 release candidate Together AI is releasing the **Python SDK v2.0 Release Candidate**, a new, OpenAPI-generated, strongly-typed client that replaces the legacy v1.0 package and brings the SDK into lock-step with the latest platform features. * **Install:** `pip install together==2.0.0a9`. * **RC period:** The v2.0 RC window starts today and will run for approximately one month. During this time Together will iterate quickly based on developer feedback and may make a few small, well-documented breaking changes before GA. * **Type-safe, modern client:** Stronger typing across parameters and responses, keyword-only arguments, explicit `NOT_GIVEN` handling for optional fields, and rich `together.types.*` definitions for chat messages, eval parameters, and more. * **Redesigned error model:** Replaces `TogetherException` with a new `TogetherError` hierarchy, including `APIStatusError` and specific HTTP status code errors such as `BadRequestError (400)`, `AuthenticationError (401)`, `RateLimitError (429)`, and `InternalServerError (5xx)`, plus transport (`APIConnectionError`, `APITimeoutError`) and validation (`APIResponseValidationError`) errors. * **New Jobs API:** Adds first-class support for the Jobs API (`client.jobs.*`) so you can create, list, and inspect asynchronous jobs directly from the SDK without custom HTTP wrappers. * **New Hardware API:** Adds the Hardware API (`client.hardware.*`) to discover available hardware, filter by model compatibility, and compute effective hourly pricing from `cents_per_minute`. * **Raw response and streaming helpers:** New `.with_raw_response` and `.with_streaming_response` helpers make it easier to debug, inspect headers and status codes, and stream completions via context managers with automatic cleanup. * **Code interpreter sessions:** Adds session management for the code interpreter (`client.code_interpreter.sessions.*`), enabling multi-step, stateful code-execution workflows that were not possible in the legacy SDK. * **High compatibility for core APIs:** Most core usage patterns, including `chat.completions`, `completions`, `embeddings`, `images.generate`, audio transcription/translation/speech, `rerank`, `fine_tuning.create/list/retrieve/cancel`, and `models.list`, are designed to be drop-in compatible between v1 and v2. * **Targeted breaking changes:** Some APIs (Files, Batches, Endpoints, Evals, code interpreter, select fine-tuning helpers) have updated method names, parameters, or response shapes. These are fully documented in the Python SDK Migration Guide and Breaking Changes notes. * **Migration resources:** A dedicated Python SDK Migration Guide is available with API-by-API before/after examples, a feature parity matrix, and troubleshooting tips to help teams smoothly transition from v1 to v2 during the RC period. **December 8, 2025** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `mistralai/Ministral-3-14B-Instruct-2512`. **November 10, 2025** ## New serverless models The following models are now available on [serverless](/docs/serverless/models): * `zai-org/GLM-4.6`. * `moonshotai/Kimi-K2-Thinking`. **November 3, 2025** ## Real-time text-to-speech and speech-to-text Together AI expands audio capabilities with real-time streaming for both TTS and STT, new models, and speaker diarization. * **Real-time text-to-speech:** WebSocket API for lowest-latency interactive applications. * **New TTS models:** Orpheus 3B (`canopylabs/orpheus-3b-0.1-ft`) and Kokoro 82M (`hexgrad/Kokoro-82M`), supporting REST, streaming, and WebSocket endpoints. * **Real-time speech-to-text:** WebSocket streaming transcription with Whisper for live audio applications. * **Voxtral model:** New Mistral AI speech recognition model (`mistralai/Voxtral-Mini-3B-2507`) for audio transcriptions. * **Speaker diarization:** Identify and label different speakers in audio transcriptions with a free `diarize` flag. * **TTS WebSocket endpoint:** `/v1/audio/speech/websocket`. * **STT WebSocket endpoint:** `/v1/realtime`. See the [Text-to-speech guide](/docs/inference/text-to-speech/overview) and [Speech-to-text guide](/docs/inference/transcription/overview). **October 31, 2025** ## Image model deprecations The following image models have been deprecated and are no longer available: * `black-forest-labs/FLUX.1-pro` (calls to FLUX.1-pro will now redirect to FLUX.1.1-pro). * `black-forest-labs/FLUX.1-Canny-pro`. **October 21, 2025** ## Video generation API and 40+ new image and video models Together AI expands into multimedia generation with comprehensive video and image capabilities. [Read more](https://www.together.ai/blog/40-new-image-and-video-models). * **New video generation API:** Create high-quality videos with models like OpenAI Sora 2, Google Veo 3.0, and Minimax Hailuo. * **40+ image and video models:** Including Google Imagen 4.0 Ultra, Gemini Flash Image 2.5 (Nano Banana), ByteDance SeeDream, and specialized editing tools. * **Unified platform:** Combine text, image, and video generation through the same APIs, authentication, and billing. * **Production-ready:** Serverless endpoints with transparent per-model pricing and enterprise-grade infrastructure. * **Video endpoints:** `/videos/create` and `/videos/retrieve`. * **Image endpoint:** `/images/generations`. **September 15, 2025** ## Improved batch inference API * **Streamlined UI:** Create and track batch jobs in an intuitive interface. No complex API calls required. * **Universal model access:** The batch inference API now supports all serverless models and private deployments, so you can run batch workloads on exactly the models you need. * **Massive scale jump:** Rate limits are up from 10M to 30B enqueued tokens per model per user, a 3,000x increase. Need more? Together will work with you to customize. * **Lower cost:** For most serverless models, the batch inference API runs at 50% the cost of the real-time API, making it the most economical way to process high-throughput workloads. **September 13, 2025** ## Qwen3-Next-80B models New Qwen3-Next-80B models are now available for both thinking and instruction tasks. * Model ID: `Qwen/Qwen3-Next-80B-A3B-Thinking`. * Model ID: `Qwen/Qwen3-Next-80B-A3B-Instruct`. **September 10, 2025** ## Fine-tuning: new large models supported Enhanced fine-tuning capabilities with expanded model support. [Read more](https://www.together.ai/blog/fine-tuning-updates-sept-2025). * `openai/gpt-oss-120b`. * `deepseek-ai/DeepSeek-V3.1`. * `deepseek-ai/DeepSeek-V3.1-Base`. * `deepseek-ai/DeepSeek-R1-0528`. * `deepseek-ai/DeepSeek-R1`. * `deepseek-ai/DeepSeek-V3-0324`. * `deepseek-ai/DeepSeek-V3`. * `deepseek-ai/DeepSeek-V3-Base`. * `Qwen/Qwen3-Coder-480B-A35B-Instruct`. * `Qwen/Qwen3-235B-A22B` (context length 32,768 for SFT and 16,384 for DPO). * `Qwen/Qwen3-235B-A22B-Instruct-2507` (context length 32,768 for SFT and 16,384 for DPO). * `meta-llama/Llama-4-Maverick-17B-128E`. * `meta-llama/Llama-4-Maverick-17B-128E-Instruct`. * `meta-llama/Llama-4-Scout-17B-16E`. * `meta-llama/Llama-4-Scout-17B-16E-Instruct`. ## Fine-tuning: increased maximum context lengths ### DeepSeek models * DeepSeek-R1-Distill-Llama-70B: SFT 8,192 → 24,576. DPO 8,192 → 8,192. * DeepSeek-R1-Distill-Qwen-14B: SFT 8,192 → 65,536. DPO 8,192 → 12,288. * DeepSeek-R1-Distill-Qwen-1.5B: SFT 8,192 → 131,072. DPO 8,192 → 16,384. ### Google Gemma models * gemma-3-1b-it: SFT 16,384 → 32,768. DPO 16,384 → 12,288. * gemma-3-1b-pt: SFT 16,384 → 32,768. DPO 16,384 → 12,288. * gemma-3-4b-it: SFT 16,384 → 131,072. DPO 16,384 → 12,288. * gemma-3-4b-pt: SFT 16,384 → 131,072. DPO 16,384 → 12,288. * gemma-3-12b-pt: SFT 16,384 → 65,536. DPO 16,384 → 8,192. * gemma-3-27b-it: SFT 12,288 → 49,152. DPO 12,288 → 8,192. * gemma-3-27b-pt: SFT 12,288 → 49,152. DPO 12,288 → 8,192. ### Qwen models * Qwen3-0.6B / Qwen3-0.6B-Base: SFT 8,192 → 32,768. DPO 8,192 → 24,576. * Qwen3-1.7B / Qwen3-1.7B-Base: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen3-4B / Qwen3-4B-Base: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen3-8B / Qwen3-8B-Base: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen3-14B / Qwen3-14B-Base: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen3-32B: SFT 8,192 → 24,576. DPO 8,192 → 4,096. * Qwen2.5-72B-Instruct: SFT 8,192 → 24,576. DPO 8,192 → 8,192. * Qwen2.5-32B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 12,288. * Qwen2.5-32B: SFT 8,192 → 49,152. DPO 8,192 → 12,288. * Qwen2.5-14B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2.5-14B: SFT 8,192 → 65,536. DPO 8,192 → 16,384. * Qwen2.5-7B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2.5-7B: SFT 8,192 → 131,072. DPO 8,192 → 16,384. * Qwen2.5-3B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2.5-3B: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2.5-1.5B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2.5-1.5B: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2-72B-Instruct / Qwen2-72B: SFT 8,192 → 32,768. DPO 8,192 → 8,192. * Qwen2-7B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2-7B: SFT 8,192 → 131,072. DPO 8,192 → 16,384. * Qwen2-1.5B-Instruct: SFT 8,192 → 32,768. DPO 8,192 → 16,384. * Qwen2-1.5B: SFT 8,192 → 131,072. DPO 8,192 → 16,384. ### Meta Llama models * Llama-3.3-70B-Instruct-Reference: SFT 8,192 → 24,576. DPO 8,192 → 8,192. * Llama-3.2-3B-Instruct: SFT 8,192 → 131,072. DPO 8,192 → 24,576. * Llama-3.2-1B-Instruct: SFT 8,192 → 131,072. DPO 8,192 → 24,576. * Meta-Llama-3.1-8B-Instruct-Reference: SFT 8,192 → 131,072. DPO 8,192 → 16,384. * Meta-Llama-3.1-8B-Reference: SFT 8,192 → 131,072. DPO 8,192 → 16,384. * Meta-Llama-3.1-70B-Instruct-Reference: SFT 8,192 → 24,576. DPO 8,192 → 8,192. * Meta-Llama-3.1-70B-Reference: SFT 8,192 → 24,576. DPO 8,192 → 8,192. ### Mistral models * mistralai/Mistral-7B-v0.1: SFT 8,192 → 32,768. DPO 8,192 → 32,768. * teknium/OpenHermes-2p5-Mistral-7B: SFT 8,192 → 32,768. DPO 8,192 → 32,768. ## Fine-tuning: Hugging Face integrations * Fine-tune any \< 100B parameter CausalLM from Hugging Face Hub. * Support for DPO variants such as LN-DPO, DPO+NLL, and SimPO. * Support fine-tuning with maximum batch size. * Public `fine-tunes/models/limits` and `fine-tunes/models/supported` endpoints. * Automatic filtering of sequences with no trainable tokens (e.g., if a sequence prompt is longer than the model's context length, the completion is pushed outside the window). **September 9, 2025** ## Together instant clusters general availability Self-service NVIDIA GPU clusters with API-first provisioning. [Read more](https://www.together.ai/blog/together-instant-clusters-ga). * New API endpoints for cluster management: * `/v1/gpu_cluster`: Create and manage GPU clusters. * `/v1/shared_volume`: High-performance shared storage. * `/v1/regions`: Available data center locations. * Support for NVIDIA Blackwell (HGX B200) and Hopper (H100, H200) GPUs. * Scale from single-node (8 GPUs) to hundreds of interconnected GPUs. * Pre-configured with Kubernetes, Slurm, and networking components. **September 8, 2025** ## Serverless LoRA and dedicated model inference support for evaluations You can now run evaluations: * Using serverless LoRA models, including supported LoRA fine-tuned models. (Serverless LoRA inference has since been discontinued. Fine-tuned adapters are served through [dedicated endpoints](/docs/fine-tuning/deployment).) * Using [dedicated model inference](/docs/dedicated-endpoints), including fine-tuned models deployed via dedicated endpoints. **September 5, 2025** ## Kimi-K2-Instruct-0905 Upgraded version of Moonshot's 1 trillion parameter MoE model with enhanced performance. [Read more](https://www.together.ai/models/kimi-k2-0905). * Model ID: `moonshot-ai/Kimi-K2-Instruct-0905`. **August 27, 2025** ## DeepSeek-V3.1 Upgraded version of DeepSeek-R1-0528 and DeepSeek-V3-0324. [Read more](https://www.together.ai/blog/deepseek-v3-1-hybrid-thinking-model-now-available-on-together-ai). * **Dual modes:** Fast mode for quick responses, and thinking mode for complex reasoning. * **671B total parameters**, with 37B active parameters. * Model ID: `deepseek-ai/DeepSeek-V3.1`. ## Model deprecations The following models have been deprecated and are no longer available: * `meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo`. * `black-forest-labs/FLUX.1-canny`. * `meta-llama/Llama-3-8b-chat-hf`. * `black-forest-labs/FLUX.1-redux`. * `black-forest-labs/FLUX.1-depth`. * `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B`. * `NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO`. * `meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo`. * `meta-llama-llama-3-3-70b-instruct-lora`. * `Qwen/Qwen2.5-14B`. * `meta-llama/Llama-Vision-Free`. * `Qwen/Qwen2-72B-Instruct`. * `google/gemma-2-27b-it`. * `meta-llama/Meta-Llama-3-8B-Instruct`. * `perplexity-ai/r1-1776`. * `nvidia/Llama-3.1-Nemotron-70B-Instruct-HF`. * `Qwen/Qwen2-VL-72B-Instruct`. **August 19, 2025** ## GPT-OSS fine-tuning support Fine-tune OpenAI's open-source models to create domain-specific variants. [Read more](https://www.together.ai/blog/fine-tune-gpt-oss-models-into-domain-experts-together-ai). * Supported models: `gpt-oss-20B` and `gpt-oss-120B`. * Supports 16K context SFT and 8K context DPO. **August 5, 2025** ## OpenAI GPT-OSS models OpenAI's first open-weight models are now accessible through Together AI. [Read more](https://www.together.ai/blog/announcing-the-availability-of-openais-open-models-on-together-ai). * Model IDs: `openai/gpt-oss-20b`, `openai/gpt-oss-120b`. **July 29, 2025** ## VirtueGuard Enterprise-grade guard model for safety monitoring with **8ms response time**. [Read more](https://www.together.ai/blog/virtueguard). * Real-time content filtering and bias detection. * Prompt injection protection. * Model ID: `VirtueAI/VirtueGuard-Text-Lite`. **July 28, 2025** ## Together Evaluations framework Benchmarking platform using LLM-as-a-judge methodology for model performance assessment. [Read more](https://www.together.ai/blog/introducing-together-evaluations). * Create custom LLM-as-a-judge evaluation suites for your domain. * Supports `compare`, `classify`, and `score` functionality. * Compare models, prompts, and LLM configs. Score and classify LLM outputs. **July 25, 2025** ## Qwen3-Coder-480B Agentic coding model with top SWE-Bench Verified performance. [Read more](https://www.together.ai/blog/qwen-3-coder). * **480B total parameters**, with 35B active (MoE architecture). * **256K context length** for entire codebase handling. * **Leading SWE-Bench scores** on software engineering benchmarks. * Model ID: `Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8`. **July 17, 2025** ## NVIDIA HGX B200 hardware support Record-breaking serverless inference speed for DeepSeek-R1-0528 using NVIDIA's Blackwell architecture. [Read more](https://www.together.ai/blog/fastest-inference-for-deepseek-r1-0528-with-nvidia-hgx-b200). * Dramatically improved throughput and lower latency. * Same API endpoints and pricing. * Model ID: `deepseek-ai/DeepSeek-R1`. **July 14, 2025** ## Kimi-K2-Instruct Moonshot AI's 1 trillion parameter MoE model with frontier-level performance. [Read more](https://www.together.ai/blog/kimi-k2-leading-open-source-model-now-available-on-together-ai). * Excels at tool use and multi-step tasks, with strong multilingual support. * Strong agentic and function calling capabilities. * Model ID: `moonshotai/Kimi-K2-Instruct`. **July 10, 2025** ## Whisper speech-to-text APIs High-performance audio transcription that's 15x faster than OpenAI, with support for files over 1 GB. [Read more](https://www.together.ai/blog/speech-to-text-whisper-apis). * Multiple audio formats with timestamp generation. * Speaker diarization and language detection. * Use the `/audio/transcriptions` and `/audio/translations` endpoints. * Model ID: `openai/whisper-large-v3`. **July 8, 2025** ## SOC 2 Type II compliance certification Achieved enterprise-grade security compliance through an independent audit of security controls. [Read more](https://www.together.ai/blog/soc-2-compliance). * Simplified vendor approval and procurement. * Reduced due diligence requirements. * Support for regulated industries. # Set up OIDC authentication Source: https://docs.together.ai/docs/cluster-oidc Authenticate team members to a GPU cluster's Kubernetes API using your organization's identity provider. External OpenID Connect (OIDC) lets each team member authenticate to a GPU cluster's Kubernetes API using their own identity from your organization's identity provider (IdP), such as Google, Okta, Auth0, or Microsoft Entra ID. Standard Kubernetes role-based access control (RBAC) then controls what each team member can do. Use OIDC when you want per-user audit trails, per-user revocation, and least-privilege access through RBAC. You may not need it if you're the only operator, or if you never use the Kubernetes API directly. > [!NOTE] > > If your cluster's OIDC issuer is `https://dex..cloud.together.ai/t-`, it uses [Together-managed OIDC](/docs/cluster-together-oidc) instead. Team members sign in with their Together account, and their access follows their project role. ## How it works Kubernetes' API server can validate JSON Web Tokens (JWTs) issued by an external OIDC provider. When a user runs `kubectl`, the OIDC kubeconfig calls a local helper that handles login interactively, then attaches the resulting token to every API request. > [accordion] OIDC flow > > The flow has four stages: **login**, **token**, **validate**, and **authorize**. > > **1. Login** > > The user runs a `kubectl` command. `kubectl` sees the exec plugin in the OIDC kubeconfig and invokes `kubectl-together_login`. The plugin opens the user's default browser and redirects to the IdP's authorization endpoint with a Proof Key for Code Exchange (PKCE) challenge. The user signs in to the IdP with their organization credentials. > > **2. Token** > > The IdP issues a signed ID token (a JWT) and redirects back to `http://localhost:8000` or `:18000`, where the plugin is listening. The plugin caches the token under `$HOME/.kube/cache/oidc-login/` and returns it to `kubectl`. > > **3. Validate** > > `kubectl` sends the API request with the token in the `Authorization: Bearer …` header. The Kubernetes API server validates the token by fetching the IdP's public signing keys from its OIDC discovery document (`/.well-known/openid-configuration`), verifying the token's signature, and checking that the `iss` and `aud` claims match the issuer URL and client ID configured on the cluster. A failure here returns `401 Unauthorized`. > > **4. Authorize** > > The API server reads the configured username claim (`email`, `preferred_username`, or `sub`) and uses it as the user identity for RBAC. It evaluates ClusterRoleBindings and RoleBindings to decide whether the request is allowed. No matching binding returns `403 Forbidden`. > > ```mermaid theme={null} > sequenceDiagram > participant User as User (kubectl) > participant Plugin as Login Plugin > participant IdP as Your Identity Provider > participant K8s as Kubernetes API Server > > User->>Plugin: kubectl get pods > Plugin->>IdP: Opens browser for login > IdP-->>Plugin: Returns signed JWT (ID token) > Plugin-->>User: Passes token to kubectl > User->>K8s: API request + Bearer token > K8s->>K8s: Validates JWT signature, issuer, audience > K8s->>K8s: Extracts username from token claims > K8s->>K8s: Evaluates RBAC rules > K8s-->>User: Response (or 403 if no RBAC match) > ``` ## Username claim The *username claim* is the field in the OIDC token that Kubernetes uses as the identity for RBAC. The supported claims are `email`, `preferred_username`, and `sub`. Choose one that your IdP reliably provides. The claim sets the format of the identity, which is the exact value you pass as `--user` when you create RBAC bindings: * `email` produces `user@company.com`, used as-is. * `sub` produces `#`, for example `https://accounts.google.com#105010678054620911233`. * `preferred_username` produces `#`, for example `https://login.microsoftonline.com//v2.0#user@company.com`. The `email` claim gives the simplest RBAC setup, because its value needs no issuer prefix. ## Requirements To set up OIDC authentication, you need: * An OIDC-compatible identity provider, such as Google, Okta, Auth0, or Entra ID. * A [GPU cluster](/docs/gpu-clusters-overview) with external OIDC enabled. You can enable OIDC only [when you create the cluster](#set-up-the-cluster-admin). * `kubectl` installed locally. * The cluster's [admin kubeconfig](/docs/gpu-clusters-management#download-cluster-kubeconfig), which the admin uses to create RBAC bindings. Only project admins can download it. ## Set up the cluster (admin) Complete these tasks as a project admin. When you're done, share this page with your team members so they can [connect to the cluster](#connect-to-the-cluster-user). **1. Create an OIDC application in your identity provider** Create an OIDC client or application in your identity provider with these settings: * **Redirect URIs:** `http://localhost:8000` and `http://localhost:18000`. * **Auth method:** Authorization code flow with PKCE. * **Scopes:** Always include `openid`. Add `email` if your username claim is `email`, or `profile` if it's `preferred_username`. The `sub` claim needs no additional scopes. The generated OIDC kubeconfig requests the scopes for your username claim through `--oidc-extra-scope`, so your IdP application only needs to allow them. Record the application's **Issuer URL** and **Client ID**, which you enter when you enable OIDC on the cluster. If your provider requires a client secret, record the **Client Secret** too. Team members set it on their own machines, as described in [Set the OIDC client secret](#connect-to-the-cluster-user). > [!NOTE] > > **Issuer URL formats by provider:** > > * **Auth0:** The issuer URL must end with a trailing slash, for example `https://your-tenant.auth0.com/`. Without it, OIDC discovery fails. > * **Okta:** Use the full authorization server URL, including `/oauth2/default`, for example `https://your-org.okta.com/oauth2/default`. The bare Okta domain returns `invalid_client`. > * **Google:** The issuer URL is always `https://accounts.google.com`. **2. Enable external OIDC on the cluster** > [!WARNING] > > **Configure OIDC when you create the cluster:** You can't add or change it after the cluster is created. 1. Go to [**GPU Clusters**](https://api.together.ai/clusters) → **Create cluster**, and set **Orchestration** to **Kubernetes**. 2. Under **Cluster add-ons**, set **Use custom OIDC** to **Yes**. The OIDC fields below the toggle become editable. 3. Optionally, select a **Quick setup** preset (**Google**, **Okta**, **Auth0**, or **Entra ID**) to prefill provider defaults. 4. Enter the **Issuer URL** and **Client ID** from your OIDC application, and set **Username Claim** to `email`, `preferred_username`, or `sub`. 5. Wait for **Provider verification** to check the discovery document, reachability, and required claims. 6. Complete the rest of the form, then select **Create Cluster** and **Confirm & Create**. **3. Grant RBAC permissions** OIDC users have no access to the cluster until you create Kubernetes RBAC bindings for their identities. Create the bindings with the [admin kubeconfig](/docs/gpu-clusters-management#download-cluster-kubeconfig), not the OIDC kubeconfig, because OIDC users can't grant themselves permissions. The console doesn't configure a groups claim, so bind each user individually. To bind groups instead, you need `oidc_config.group_claim`, which you can set only when you create the cluster through the API or SDK. Set `--user` to the exact identity Kubernetes extracts from the token. Its format depends on your [username claim](#username-claim): > [tab] email > > ```bash theme={null} > kubectl create clusterrolebinding my-user-admin \ > --clusterrole=cluster-admin \ > --user="user@company.com" > ``` > [tab] sub > > ```bash theme={null} > # Format: # > kubectl create clusterrolebinding my-user-admin \ > --clusterrole=cluster-admin \ > --user="https://accounts.google.com#105010678054620911233" > ``` > [tab] preferred\_username > > ```bash theme={null} > # Format: # > kubectl create clusterrolebinding my-user-admin \ > --clusterrole=cluster-admin \ > --user="https://login.microsoftonline.com//v2.0#user@company.com" > ``` ## Connect to the cluster (user) Each team member completes these tasks on their local machine. **1. Download the OIDC kubeconfig** Only project admins can see the OIDC kubeconfig in the console. The file contains no credentials, so admins can share it with editors. If you're a project editor, ask a project admin for the file, then save it to `$HOME/.kube/my-cluster-oidc.yaml`. If you're a project admin, download it once the cluster's status is **Ready**: 1. Open the [cluster details page](/docs/gpu-clusters-management). 2. In the sidebar, find **OIDC Kubeconfig** and select **View**. 3. Copy the kubeconfig content and save it to `$HOME/.kube/my-cluster-oidc.yaml`: ```bash theme={null} # Create the .kube directory if it doesn't exist. mkdir -p $HOME/.kube # Reads the kubeconfig from your clipboard. Run this immediately after copying from the console. pbpaste > $HOME/.kube/my-cluster-oidc.yaml # macOS ``` > [!TIP] > > On Linux, replace `pbpaste` with `xclip -selection clipboard -o`. On any platform, you can also paste the content into the file with a text editor, or select **Download** instead of **View** and save the downloaded file to the same path. **2. Install the login helper** The OIDC kubeconfig calls an exec plugin that handles browser-based login and token caching. The **OIDC Kubeconfig** dialog's **Quick setup** shows which plugin your cluster needs. If you're a project editor, ask the project admin who shared your kubeconfig. If **Quick setup** shows `together-login`, download the binary for your platform from the [`together-kubelogin` releases](https://github.com/togethercomputer/together-kubelogin/releases/latest), verify its checksum, and move it onto your `PATH`: > [tab] macOS Apple Silicon > > ```bash theme={null} > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_darwin_arm64.zip > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_darwin_arm64.zip.sha256 > shasum -a 256 -c kubectl-together_login_darwin_arm64.zip.sha256 > unzip -o kubectl-together_login_darwin_arm64.zip kubectl-together_login > sudo mv kubectl-together_login /usr/local/bin/ > rm kubectl-together_login_darwin_arm64.zip kubectl-together_login_darwin_arm64.zip.sha256 > ``` > [tab] macOS Intel > > ```bash theme={null} > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_darwin_amd64.zip > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_darwin_amd64.zip.sha256 > shasum -a 256 -c kubectl-together_login_darwin_amd64.zip.sha256 > unzip -o kubectl-together_login_darwin_amd64.zip kubectl-together_login > sudo mv kubectl-together_login /usr/local/bin/ > rm kubectl-together_login_darwin_amd64.zip kubectl-together_login_darwin_amd64.zip.sha256 > ``` > [tab] Linux amd64 > > ```bash theme={null} > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_linux_amd64.zip > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_linux_amd64.zip.sha256 > sha256sum -c kubectl-together_login_linux_amd64.zip.sha256 > unzip -o kubectl-together_login_linux_amd64.zip kubectl-together_login > sudo mv kubectl-together_login /usr/local/bin/ > rm kubectl-together_login_linux_amd64.zip kubectl-together_login_linux_amd64.zip.sha256 > ``` > [tab] Linux arm64 > > ```bash theme={null} > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_linux_arm64.zip > curl -fsSL -O https://github.com/togethercomputer/together-kubelogin/releases/latest/download/kubectl-together_login_linux_arm64.zip.sha256 > sha256sum -c kubectl-together_login_linux_arm64.zip.sha256 > unzip -o kubectl-together_login_linux_arm64.zip kubectl-together_login > sudo mv kubectl-together_login /usr/local/bin/ > rm kubectl-together_login_linux_arm64.zip kubectl-together_login_linux_arm64.zip.sha256 > ``` Verify the installation: ```bash theme={null} kubectl together-login --help ``` If **Quick setup** shows `kubelogin` instead, your cluster uses [Together-managed OIDC](/docs/cluster-together-oidc), and its kubeconfig calls `kubectl oidc-login`. Install [int128/kubelogin](https://github.com/int128/kubelogin) with `brew install kubelogin` or `kubectl krew install oidc-login`. **3. Set the OIDC client secret** Skip this task unless your provider requires a client secret. Most don't, because the kubeconfig uses PKCE (`S256`) by default, but some, such as Google, require one even for desktop or native PKCE flows. If yours does, get the secret from your admin and set it for the current session: ```bash theme={null} export OIDC_CLIENT_SECRET="" ``` > [!WARNING] > > **Don't store the secret in shell config files such as `.bashrc` or `.zshrc`:** Set it per session, or inject it with a secrets manager. **4. Verify access** Test your access with the OIDC kubeconfig: ```bash theme={null} # Clear any cached tokens from previous attempts. rm -rf $HOME/.kube/cache/oidc-login/ # Test access using the OIDC kubeconfig. kubectl --kubeconfig=$HOME/.kube/my-cluster-oidc.yaml get nodes ``` A browser opens for login. Sign in with your IdP credentials, then check the result: * **Success:** The command lists the cluster's nodes. You're authenticated and authorized. * **`403 Forbidden`:** Authentication worked, but no RBAC binding exists for your identity. Ask your admin to complete [Grant RBAC permissions](#set-up-the-cluster-admin). If you're a project editor on a [Together-managed OIDC](/docs/cluster-together-oidc) cluster, you get read-only access that excludes nodes, so `get nodes` returns `403`. [Verify with `get pods`](#403-forbidden) instead. ## Revoking access To revoke a user's access: 1. Remove their RBAC binding from the cluster: ```bash theme={null} kubectl delete clusterrolebinding my-user-admin ``` 2. Remove the user from your IdP, or from the relevant group, to prevent new tokens from being issued. Existing tokens will continue to work until they expire. For immediate revocation, perform both steps together. ## Token lifetime and refresh OIDC tokens are short-lived (typically one hour, depending on your IdP configuration). When a token expires, the login plugin opens a browser automatically so you can sign in again. If your IdP supports refresh tokens, the plugin can renew the token without a login prompt. The plugin caches tokens locally in `$HOME/.kube/cache/oidc-login/`. To force a fresh login, clear the cache: ```bash theme={null} kubectl together-login clean ``` On Together-managed OIDC clusters, which use `kubelogin`, run `kubectl oidc-login clean` instead. Deleting the cache directory works with either plugin: ```bash theme={null} rm -rf $HOME/.kube/cache/oidc-login/ ``` > [!WARNING] > > **After a role or permissions change, clear the OIDC token cache:** When your role changes, for example through new RBAC bindings or a change to your IdP group, the cached token may still carry the old identity or claims until it expires. Once you clear the cache, the next `kubectl` call starts a fresh login that picks up the new access. ## Troubleshooting ### `403 Forbidden` Authentication succeeded, but no RBAC binding grants your identity the required permissions. > [!NOTE] > > **On Together-managed OIDC clusters, verify with `get pods`:** A cluster uses Together-managed OIDC if the **OIDC Kubeconfig** dialog's **Quick setup** shows `kubelogin`. On these clusters, project editors get [read-only access](/docs/cluster-together-oidc#default-access) that excludes nodes, so `get nodes` returns `403 Forbidden` for them. Run `get pods` instead: > > ```bash theme={null} > kubectl --kubeconfig=$HOME/.kube/my-cluster-oidc.yaml get pods > ``` **Fix:** * Confirm the exact identity your [username claim](#username-claim) produces, such as `user@company.com` or an issuer-prefixed `sub` value. The binding's `--user` value must match it. * Ask a project admin to [create a ClusterRoleBinding or RoleBinding](#set-up-the-cluster-admin) for your identity. * If your role recently changed, [clear the OIDC token cache](#token-lifetime-and-refresh) so the next login picks up the new access. ### `401 Unauthorized` or "provide credentials" Token validation failed at the API server. **Fix:** * Check the cluster's OIDC configuration against the token. The issuer URL must match the token's `iss` claim, the client ID must match its `aud` claim, and the token must contain the username claim. * Clear cached tokens and retry: ```bash theme={null} rm -rf $HOME/.kube/cache/oidc-login/ ``` ### `client_secret is missing` Your IdP requires a client secret that wasn't provided. **Fix:** ```bash theme={null} export OIDC_CLIENT_SECRET="" ``` ### Browser login doesn't open **Fix:** * Ensure `kubectl-together_login` is installed and on your PATH. * Run `kubectl together-login --help` to verify. ## Security best practices * Use short-lived OIDC tokens, and rely on your IdP for user lifecycle (joiners, movers, leavers). * Keep the admin kubeconfig restricted to break-glass scenarios. Use OIDC for day-to-day access. * Use `email` as the username claim for the simplest RBAC setup. Other claims require issuer-prefixed `--user` values. # Cluster storage Source: https://docs.together.ai/docs/cluster-storage Understand storage types, persistence, and best practices for GPU clusters. Together GPU clusters provide persistent shared volumes, ephemeral NVMe disks local to each node, and a `/home` directory whose persistence depends on the cluster type. > [!WARNING] > > **Local NVMe disks and other node-local storage are ephemeral:** Their data can be lost at any time during node migrations and recreations, maintenance, or other cluster operations. Always store data you need to keep on shared volumes (PVC-backed storage). ## Storage types at a glance * **Shared volumes (PVC):** Persistent. Data survives pod restarts, node events (reboots, migrations, and recreations), cluster operations, and, by default, cluster deletion. Use shared volumes for training data, checkpoints, model weights, and anything else you can't lose. * **Local NVMe disks:** Ephemeral. Fast local storage on each node. Its data can be lost during node migrations and recreations or cluster operations, so use it only for temporary scratch data, such as intermediate computation files. * **`/home` directory:** Depends on the cluster type. On Slurm clusters, `/home` is a persistent directory on the shared volume. On Kubernetes clusters, it's local to each node and ephemeral. ## Persistent storage: shared volumes Shared volumes are remote-attached, high-speed filesystems that every node in the cluster can access. When you create a cluster, you either create a new shared volume with it or attach an existing one. Data on a shared volume persists across: * Pod restarts and rescheduling. * Node reboots, migrations, recreations, and maintenance. * Cluster scaling operations. * Cluster deletion, unless you choose to delete the volume along with the cluster. When you delete a cluster but not its volume, the volume keeps billing as storage, and you can attach it to another cluster. A volume that draws its storage from a capacity pool moves to on-demand storage pricing once its reservation ends. How you access a shared volume depends on the cluster type: * **Kubernetes clusters:** The cluster provides a static PersistentVolume (PV) with the same name as your shared volume. Create a PersistentVolumeClaim (PVC) that references it, then [mount it in your pods](/docs/kubernetes-workloads#deploy-pods-with-storage). * **Slurm clusters:** The shared volume is mounted at `/data` on all compute and login nodes. **Project ownership:** By default, a new shared volume belongs to your default [project](/docs/projects). To assign it to a different project you have access to, pass `project_id` when you create the volume through the API or SDK. A volume you create with a cluster belongs to the cluster's project instead, and the API ignores `shared_volume.project_id` in the [create request](/reference/clusters-create). ## Ephemeral storage: local NVMe disks Each node has local NVMe disks for high-speed reads and writes. On Slurm clusters, this storage is mounted at `/scratch` on each compute node. > [!WARNING] > > **Data on local NVMe disks is not durable:** It can be lost without warning during: > > * Node migrations and recreations (scheduled or unscheduled). > * Cluster maintenance operations. > * Hardware failures. > * Pod rescheduling to a different node. > > Do **not** rely on local NVMe for any data you need to keep. Use it only for temporary scratch files that can be regenerated. ## `/home` directory The behavior of `/home` differs between cluster types: ### Slurm clusters On Slurm clusters, `/home` is a **persistent directory on your shared volume**, available on every compute and login node. It links to `/data/home`, so home-directory data survives node events and counts toward your shared volume's capacity. Use it for code, scripts, configuration files, logs, small datasets, model weights, and training data. Before you use `/home`, [SSH into the Slurm login node](/docs/gpu-clusters-ssh#ssh-to-slurm-login-nodes) to set up your user directory with the correct permissions. ### Kubernetes clusters On Kubernetes clusters, `/home` is **local to each node and ephemeral**. It is not shared across nodes and is subject to the same data loss risks as local NVMe storage. > [!WARNING] > > On Kubernetes clusters, do **not** store important data in `/home`. Use a shared volume (PVC) instead. ## Choose the right storage | Data | Where to store it | | - | - | | Training data, checkpoints, model weights, application state, code, and configs | Shared volume (PVC), or `/home` on Slurm clusters. | | Temporary scratch files and intermediate computation artifacts | Local NVMe disks (acceptable to lose). | ## Upload your data To upload a small dataset, copy it into a pod that mounts your shared volume: 1. Create a PVC that uses your shared volume's name as its `volumeName`, and a pod that mounts the volume. 2. Run `kubectl cp LOCAL_FILENAME YOUR_POD_NAME:/mnt/shared/`. If your pod mounts the volume at a different path, use that path instead of `/mnt/shared/`. For a large dataset, schedule a pod on the cluster that downloads it directly from S3 or your data source, as in the [example pod spec](/docs/gpu-clusters-management#upload-data). ## Next steps > [card] [Run workloads on Kubernetes](/docs/kubernetes-workloads) > > Create PVCs, mount volumes in pods, and run GPU workloads. > [card] [Manage GPU clusters](/docs/gpu-clusters-management) > > Upload data, resize storage, and monitor cluster health. # Sign in to clusters with your Together account Source: https://docs.together.ai/docs/cluster-together-oidc Use your Together account to run kubectl and SSH on a Together-managed OIDC cluster. On a GPU cluster with Together-managed OpenID Connect (OIDC), project collaborators run `kubectl` and SSH with their own Together accounts. Their access follows the [project roles](/docs/roles-permissions) you already manage in Together. There's no identity provider to set up and no shared credential to hand out. > [!TIP] > > To use your organization's own identity provider (Google, Okta, Auth0, Entra ID) instead, see [Set up OIDC authentication](/docs/cluster-oidc). ## Check whether your cluster uses Together-managed OIDC Open the cluster in the [Together AI console](https://api.together.ai/clusters). A cluster with Together-managed OIDC shows: * An **OIDC Issuer** of the form `https://dex..cloud.together.ai/t-`. * An **OIDC Kubeconfig** row whose **Quick setup** installs `kubelogin`. ## How it works Each cluster gets its own sign-in service at its issuer URL. When you run `kubectl`, the `kubelogin` plugin opens your browser to that service, which sends you to the Together sign-in page. Only collaborators on the cluster's project can sign in. After you sign in, the service issues a signed ID token that carries your email address and your project role, and `kubelogin` caches the token under `$HOME/.kube/cache/oidc-login/`. The cluster's Kubernetes API server uses your email address as your Kubernetes username and your project role as a group. Kubernetes role-based access control (RBAC) then decides what you can do, starting from the [default bindings](#default-access). ## Default access When the cluster first becomes ready, it gets one RBAC binding per project role: | Project role | Kubernetes group | ClusterRole | What it allows | | - | - | - | - | | **admin** | `proj::admin` | `cluster-admin` | Full control of the cluster. | | **editor** | `proj::member` | `view` | Read most resources in every namespace. No access to Secrets, `kubectl exec`, or nodes. | These bindings are named `ums-oidc-admin` and `ums-oidc-member`. Together creates them only once and doesn't overwrite later changes, so a cluster admin can edit them or [grant more access](#grant-more-access) with new bindings. > [!NOTE] > > Editors can run `kubectl get pods --all-namespaces`, but `kubectl get nodes` returns `403 Forbidden`, because the `view` role doesn't include nodes. ## Connect with kubectl **1. Install kubelogin** Install [int128/kubelogin](https://github.com/int128/kubelogin), which provides the `kubectl oidc-login` plugin: > [tab] Homebrew > > ```bash theme={null} > brew install kubelogin > ``` > [tab] Krew > > ```bash theme={null} > kubectl krew install oidc-login > ``` > [tab] Chocolatey > > ```bash theme={null} > choco install kubelogin > ``` **2. Save the OIDC kubeconfig** In the console, open the cluster and select **View** next to **OIDC Kubeconfig**. Copy the kubeconfig and save it to `$HOME/.kube/oidc-config.yaml`: ```bash theme={null} mkdir -p $HOME/.kube pbpaste > $HOME/.kube/oidc-config.yaml # macOS ``` On Linux, replace `pbpaste` with `xclip -selection clipboard -o`, or select **Download** instead of **View** and save the file to the same path. If you don't see the **OIDC Kubeconfig** row, ask a project admin to share theirs. The OIDC kubeconfig contains no credentials, so it's safe to share with anyone in the project. **3. Verify access** Run a `kubectl` command with the OIDC kubeconfig: ```bash theme={null} kubectl --kubeconfig=$HOME/.kube/oidc-config.yaml get pods ``` Your browser opens the Together sign-in page. After you sign in, the command runs as your email address. Later commands reuse the cached token until it expires. ## Grant more access To grant access beyond the defaults, create standard RBAC bindings with the admin kubeconfig, or with an OIDC kubeconfig signed in as a project admin. For example, to let one editor manage workloads in a namespace, bind their email address: ```bash theme={null} kubectl create rolebinding alice-edit \ --clusterrole=edit \ --user="alice@company.com" \ --namespace=team-a ``` To give every editor in the project the same access, bind their project role group instead: ```bash theme={null} kubectl create rolebinding editors-edit \ --clusterrole=edit \ --group="proj::member" \ --namespace=team-a ``` ## Revoke access To revoke a collaborator's access to the cluster: 1. Remove them from the cluster's project in [**Settings > Project > Collaborators**](https://api.together.ai/settings/projects/~current/collaborators). They can no longer sign in to the cluster, but a token they already have keeps their project role's access until it expires, up to 24 hours after sign-in. 2. Delete any RBAC bindings that name their email address. This immediately removes the access those bindings granted. ## SSH with your Together account On clusters that support OIDC SSH, the same Together sign-in gives you SSH access without an SSH key. The Together CLI's `tg clusters ssh` command signs you in through the cluster's issuer and gets a short-lived SSH certificate for your email address from the cluster's certificate authority. After you're removed from the cluster's project, you can't get a new certificate, but one you already have works until it expires. See [Connect over SSH](/docs/gpu-clusters-ssh) for the commands. ## Troubleshooting ### `403 Forbidden` You signed in, but your role doesn't allow the request. Editors can't list nodes or read Secrets by default. Run `kubectl auth whoami` with the OIDC kubeconfig to check which username and groups the cluster sees, then ask a cluster admin to [grant more access](#grant-more-access) if you need it. ### Sign-in fails in the browser The Together sign-in page only admits collaborators on the cluster's project. Check that the Together account you signed in with is a collaborator on that project. ### The browser doesn't open Check that `kubelogin` is installed and on your `PATH`: ```bash theme={null} kubectl oidc-login --help ``` ### Access didn't change after a role update Your token carries the project role you had when you signed in, so a role change takes effect at your next sign-in. Clear the cached token so the next command signs in again: ```bash theme={null} kubectl oidc-login clean ``` # Composio Source: https://docs.together.ai/docs/composio Use Composio with Together AI. Composio allows developers to integrate external tools and services into their AI applications. It handles tool calling, webhooks, authentication, and more. You need to register on a Composio account. Sign up here if you haven't already to get their API key [https://platform.composio.dev/](https://platform.composio.dev/). ## Install libraries ```shell Python theme={null} uv add together composio-togetherai ``` ```shell TypeScript theme={null} npm install @composio/core @composio/vercel @ai-sdk/togetherai ai ``` Set your `TOGETHER_API_KEY` and `COMPOSIO_API_KEY` environment variables. ```bash Shell theme={null} export TOGETHER_API_KEY=*** export COMPOSIO_API_KEY=*** ``` ## Example In this example, you will use Together AI to star a repository on GitHub using Composio Tools. ```python Python theme={null} from composio_togetherai import ComposioToolSet, App from together import Together client = Together() toolset = ComposioToolSet() ``` ```typescript TypeScript theme={null} /* We use the Vercel AI SDK with the Together provider to enable type checking to work correctly for tools and to simplify the Composio integration. This flow enables us to directly execute tool calls without having to use composio.provider.handleToolCalls. */ import { Composio } from "@composio/core"; import { VercelProvider } from "@composio/vercel"; import { createTogetherAI } from "@ai-sdk/togetherai"; import { generateText } from "ai"; export const together = createTogetherAI({ apiKey: process.env.TOGETHER_API_KEY ?? "", }); const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY ?? "", provider: new VercelProvider(), }); ``` ### Connect your GitHub account You need to have an active GitHub Integration in Composio. See the [Composio GitHub setup video](https://www.youtube.com/watch?v=LmyWy4LiedQ). ```python Python theme={null} request = toolset.initiate_connection(app=App.GITHUB) print(f"Open this URL to authenticate: {request.redirectUrl}") ``` ```bash Shell theme={null} composio login composio add github ``` ### Get all GitHub tools You can get all the tools for a given app as shown below, but you can get specific actions and filter actions using usecase & tags. ```python Python theme={null} tools = toolset.get_tools(apps=[App.GITHUB]) ``` ```typescript TypeScript theme={null} const userId = "default"; // replace with user id from composio const tools = await composio.tools.get(userId, { toolkits: ['github'], }); ``` ### Create a chat completion with tools ```python Python theme={null} response = client.chat.completions.create( tools=tools, model="meta-models/Muse-Glimmer-30B", messages=[ { "role": "user", "content": "Star the repo 'togethercomputer/together-cookbook'", } ], ) res = toolset.handle_tool_calls(response) print(res) ``` ```typescript TypeScript theme={null} const responseGithub = await generateText({ model: together("meta-models/Muse-Glimmer-30B"), messages: [ { role: "user", content: "Star the repo 'togethercomputer/together-cookbook'", }, ], tools, toolChoice: "required", }); console.log(responseGithub); ``` ## Next steps > [!NOTE] > > ### Composio - Together AI Cookbook > > Explore the in-depth [Composio Cookbook](https://github.com/togethercomputer/together-cookbook/blob/main/agents/Composio/Agents_Composio.ipynb) to learn how to automate emails with LLMs. # Conditional workflow Source: https://docs.together.ai/docs/conditional-workflows Adapt to different tasks by conditionally navigating to various LLMs and tools. A workflow where user input is classified and directed to a specific task (can be a specific LLM, specific custom prompt, different tool calls etc.). This allows you to handle many different inputs with the appropriate set of calls. ## Workflow architecture Create an agent that conditionally routes tasks to specialized models. ![](https://mintcdn.com/togetherai-52386018/-CYPjI-GKL4GZ_Jy/images/6f2307cf0a62498e41395cd0ce0a435a731e78ae8c07ae7e4596992b202e8c22-conditional.png?fit=max\&auto=format\&n=-CYPjI-GKL4GZ_Jy\&q=85\&s=8c0e9d6cb57612ddeb9e368a7984c3ce) ## Set up client and helper functions ```python Python theme={null} import json from pydantic import ValidationError from together import Together client = Together() def run_llm(user_prompt: str, model: str, system_prompt: str = None): messages = [] if system_prompt: messages.append({"role": "system", "content": system_prompt}) messages.append({"role": "user", "content": user_prompt}) response = client.chat.completions.create( model=model, messages=messages, temperature=0.7, max_tokens=4000, ) return response.choices[0].message.content def JSON_llm(user_prompt: str, schema, system_prompt: str = None): try: messages = [] if system_prompt: messages.append({"role": "system", "content": system_prompt}) messages.append({"role": "user", "content": user_prompt}) extract = client.chat.completions.create( messages=messages, model="meta-models/Muse-Glimmer-30B", response_format={ "type": "json_schema", "json_schema": { "name": "route_selection", "schema": schema.model_json_schema(), }, }, ) return json.loads(extract.choices[0].message.content) except ValidationError as e: error_message = f"Failed to parse JSON: {e}" print(error_message) ``` ## Implement workflow ```python Python theme={null} from pydantic import BaseModel, Field from typing import Literal, Dict def router_workflow(input_query: str, routes: Dict[str, str]) -> str: """Given a `input_query` and a dictionary of `routes` containing options and details for each. Selects the best model for the task and return the response from the model. """ ROUTER_PROMPT = """Given a user prompt/query: {user_query}, select the best option out of the following routes: {routes}. Answer only in JSON format.""" # Create a schema from the routes dictionary class Schema(BaseModel): route: Literal[tuple(routes.keys())] reason: str = Field( description="Short one-liner explanation why this route was selected for the task in the prompt/query." ) # Call LLM to select route selected_route = JSON_llm( ROUTER_PROMPT.format(user_query=input_query, routes=routes), Schema ) print( f"Selected route:{selected_route['route']}\nReason: {selected_route['reason']}\n" ) # Use LLM on selected route. # Could also have different prompts that need to be used for each route. response = run_llm(user_prompt=input_query, model=selected_route["route"]) print(f"Response: {response}\n") return response ``` ```typescript TypeScript theme={null} import dedent from "dedent"; import assert from "node:assert"; import Together from "together-ai"; import { z } from "zod"; const client = new Together(); const prompts = [ "Produce python snippet to check to see if a number is prime or not.", "Plan and provide a short itinerary for a 2 week vacation in Europe.", "Write a short story about a dragon and a knight.", ]; const modelRoutes = { "zai-org/GLM-5.3": "Best model choice for code generation tasks.", "meta-models/Muse-Glimmer-30B": "Best model choice for story-telling, role-playing and fantasy tasks.", "moonshotai/Kimi-K3": "Best model for reasoning, planning and multi-step tasks", }; const schema = z.object({ route: z.enum(Object.keys(modelRoutes) as [keyof typeof modelRoutes]), reason: z.string(), }); const jsonSchema = z.toJSONSchema(schema); async function routerWorkflow( inputQuery: string, routes: { [key: string]: string }, ) { const routerPrompt = dedent` Given a user prompt/query: ${inputQuery}, select the best option out of the following routes: ${Object.keys(routes) .map((key) => `${key}: ${routes[key]}`) .join("\n")} Answer only in JSON format.`; // Call LLM to select route const routeResponse = await client.chat.completions.create({ messages: [ { role: "system", content: routerPrompt }, { role: "user", content: inputQuery }, ], model: "meta-models/Muse-Glimmer-30B", response_format: { type: "json_schema", json_schema: { name: "route_selection", schema: jsonSchema, }, }, }); const content = routeResponse.choices[0].message?.content; assert(typeof content === "string"); const selectedRoute = schema.parse(JSON.parse(content)); // Use LLM on selected route. // Could also have different prompts that need to be used for each route. const response = await client.chat.completions.create({ messages: [{ role: "user", content: inputQuery }], model: selectedRoute.route, }); const responseContent = response.choices[0].message?.content; console.log(`${responseContent}\n`); } async function main() { for (const prompt of prompts) { console.log(`Task ${prompts.indexOf(prompt) + 1}: ${prompt}`); console.log("===================="); await routerWorkflow(prompt, modelRoutes); } } main(); ``` ## Example usage ```python Python theme={null} prompt_list = [ "Produce python snippet to check to see if a number is prime or not.", "Plan and provide a short itinerary for a 2 week vacation in Europe.", "Write a short story about a dragon and a knight.", ] model_routes = { "zai-org/GLM-5.3": "Best model choice for code generation tasks.", "meta-models/Muse-Glimmer-30B": "Best model choice for story-telling, role-playing and fantasy tasks.", "moonshotai/Kimi-K3": "Best model for reasoning, planning and multi-step tasks", } for i, prompt in enumerate(prompt_list): print(f"Task {i+1}: {prompt}\n") print(20 * "==") router_workflow(prompt, model_routes) ``` ## Use cases * Routing easy/common questions to smaller models like Llama 3.1 8B and hard/unusual questions to more capable models like DeepSeek V3 and Llama 3.3 70B to optimize cost and speed. * Directing different types of customer service queries (general questions, refund requests, technical support) into different downstream processes, prompts, and tools. * Different LLMs or model configurations excel at different tasks (e.g., writing summaries vs. generating code). Using a router, you can automatically detect the user's intent and send the input to the best-fit model. * Evaluating whether a request meets certain guidelines or triggers specific filters (e.g., checking if content is disallowed). Based on the classification, forward it to the appropriate next LLM call or step. * If one model's output doesn't meet a certain confidence threshold or fails for some reason, route automatically to a fallback model. > [!NOTE] > > ### Conditional workflow cookbook > > For a more detailed walk-through refer to the [notebook here](https://togetherai.link/agent-recipes-deep-dive-routing). # Quickstart Source: https://docs.together.ai/docs/containers-quickstart Deploy your first container with dedicated container inference and send it a job through the managed queue in 20 minutes. Dedicated container inference runs your own Docker container on Together's managed GPU infrastructure. You bring the container, and Together handles provisioning, autoscaling, networking, and observability. Use it when you need to run your own model or inference code, such as a custom architecture, a modified vLLM or SGLang engine, or an audio, image, or video model, without managing GPU servers yourself. This quickstart deploys the hello-world example from the Sprocket repository, a minimal [Sprocket](/docs/deployments-sprocket) worker that returns a greeting. You build and deploy the container with the [Jig CLI](/docs/deployments-jig), send the worker a job through the managed queue, read back the result, and delete the deployment. ## Requirements * **Dedicated container inference access:** Contact your account representative or the [sales team](https://www.together.ai/contact-sales) to enable dedicated container inference for your organization. * **Together API key:** The `curl` commands in steps 5 to 7 read your key from the `TOGETHER_API_KEY` environment variable, so export it before you start. * **Docker:** Jig uses your local Docker to build and push the container image. See the [Docker installation guide](https://docs.docker.com/engine/install). * **uv:** For installing the Together CLI. See [uv's installation guide](https://docs.astral.sh/uv/getting-started/installation/). ## Step 1: Install the Together CLI Install the Together CLI, which includes the Jig commands (`tg beta jig`) that build and deploy your container: ```shell theme={null} uv tool install "together[cli]" --upgrade ``` Log in to authenticate the CLI: ```shell theme={null} tg login ``` ## Step 2: Clone the Sprocket examples Clone the Sprocket repository, which contains the example workers: ```shell Shell theme={null} git clone git@github.com:togethercomputer/sprocket.git cd sprocket ``` The worker's code is in `sprocket/examples/hello-world`. Sprocket calls `setup()` once when the worker starts and `predict()` once per job. Here, `predict()` reads `name` from the job's arguments and returns a greeting: ```python hello_world.py theme={null} import os import sprocket class HelloWorld(sprocket.Sprocket): def setup(self) -> None: self.greeting = "Hello" def predict(self, args: dict) -> dict: name = args.get("name", "world") return {"message": f"{self.greeting}, {name}!"} if __name__ == "__main__": queue_name = os.environ.get("TOGETHER_DEPLOYMENT_NAME", "hello-world") sprocket.run(HelloWorld(), queue_name) ``` ## Step 3: Build and deploy the container Jig reads the deployment configuration from the worker's `pyproject.toml`. The example worker uses this one: ```toml pyproject.toml theme={null} [project] name = "hello-world" version = "0.1.0" dependencies = ["sprocket"] [[tool.uv.index]] name = "together-pypi" url = "https://pypi.together.ai/" [tool.uv.sources] sprocket = { index = "together-pypi" } [tool.jig.image] python_version = "3.11" cmd = "python3 hello_world.py --queue" copy = ["hello_world.py"] [tool.jig.deploy] gpu_type = "none" gpu_count = 0 cpu = 1 memory = 2 storage = 10 port = 8000 min_replicas = 1 max_replicas = 1 ``` The `[tool.jig.image]` table tells Jig how to build the image, and `[tool.jig.deploy]` sets the deployment's resources and replica bounds. This example runs a single CPU-only replica. Jig uses `name` under `[project]` as the deployment name, which must be globally unique. Change `hello-world` to a name of your own in `examples/hello-world/pyproject.toml`, and use that name in place of `hello-world` in the commands in steps 5 to 7. Move into the example's folder and deploy it. The `deploy` command builds the Docker image from the example, pushes it to Together's private registry, and creates the deployment: ```shell Shell theme={null} cd examples/hello-world tg beta jig deploy ``` ## Step 4: Check that the deployment is running Poll the deployment's status with `watch`. macOS doesn't include `watch` by default, so install it first with `brew install watch` or your package manager of choice: ```shell Shell theme={null} watch 'tg beta jig status' ``` Wait until the deployment shows `running` and its replicas are ready, then press `Ctrl+C` to stop watching. > [!NOTE] > > You can also check deployment status in the [Together AI console](https://api.together.ai/containers). ## Step 5: Test the health endpoint Call the deployment's health endpoint to confirm the worker is up: ```shell Shell theme={null} curl https://api.together.ai/v1/deployment-request/hello-world/health \ -H "Authorization: Bearer $TOGETHER_API_KEY" ``` A healthy worker responds with: ```json theme={null} {"status": "healthy"} ``` ## Step 6: Submit a job Submit a job to the deployment's queue. The `model` field takes your deployment name, and `predict()` receives `payload` as its arguments: ```shell Shell theme={null} curl -X POST "https://api.together.ai/v1/queue/submit" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "hello-world", "payload": {"name": "Together"}, "priority": 1 }' ``` The response contains the job's `request_id`. Copy it for the next step: ```json theme={null} { "request_id": "req_abc123" } ``` ## Step 7: Get the job result Check the job's status. Replace `req_abc123` with the `request_id` from step 6, a UUIDv7 value such as `019ba379-92da-71e4-ac40-d98059fd67c7`: ```shell Shell theme={null} curl "https://api.together.ai/v1/queue/status?model=hello-world&request_id=req_abc123" \ -H "Authorization: Bearer $TOGETHER_API_KEY" ``` When the job is complete, `status` is `done` and `outputs` holds the worker's greeting: ```json theme={null} { "request_id": "req_abc123", "model": "hello-world", "status": "done", "outputs": {"message": "Hello, Together!"} } ``` ## Step 8: View the logs Stream your deployment's logs: ```shell Shell theme={null} tg beta jig logs --follow ``` ## Step 9: Delete the deployment The deployment keeps a replica running until you delete it, because `min_replicas` is `1`. When you're done, delete the deployment: ```shell Shell theme={null} tg beta jig destroy ``` ## Next steps Now that you've deployed your first container, explore the full platform: > [card] [Dedicated container inference overview](/docs/dedicated-container-inference) > > Read the architecture and core concepts. > [card] [Jig CLI](/docs/deployments-jig) > > Build, push, and deploy containers, and manage secrets and volumes. > [card] [Sprocket SDK](/docs/deployments-sprocket) > > Build queue-integrated inference workers. > [card] [API reference](/reference/deployments-list) > > Call the REST API for deployments, secrets, and queues. ### Tutorials > [card] [Image generation with FLUX.2](/docs/dedicated-containers-image) > > Run single-GPU inference with 4-bit quantization. > [card] [Video generation with Wan 2.1](/docs/dedicated-containers-video) > > Run multi-GPU inference with torchrun. > [card] [Serve an OpenAI-compatible endpoint](/docs/dedicated-containers-openai) > > Run in HTTP server mode behind the OpenAI Images API. > [card] [Deploy a prebuilt vLLM image](/docs/dedicated-containers-vllm) > > Serve Qwen2.5-VL from the stock vLLM image, with no Sprocket code and no Docker build. # CrewAI Source: https://docs.together.ai/docs/crewai Use CrewAI with Together AI models to orchestrate AI agent systems. CrewAI is an open source production-grade framework for orchestrating AI agent systems. It enables multiple AI agents to collaborate effectively by assuming roles and working toward shared goals. The framework supports both simple automations and complex applications that require coordinated agent behavior. ## Install libraries ```shell Shell theme={null} uv add crewai ``` Set your Together API key: ```shell Shell theme={null} export TOGETHER_API_KEY=*** ``` ## Example ```python Python theme={null} import os from crewai import LLM, Task, Agent, Crew llm = LLM( model="together_ai/meta-models/Muse-Glimmer-30B", api_key=os.environ.get("TOGETHER_API_KEY"), base_url="https://api.together.ai/v1", ) research_agent = Agent( llm=llm, role="Research Analyst", goal="Find and summarize information about specific topics", backstory="You are an experienced researcher with attention to detail", verbose=True, # Enable logging for debugging ) research_task = Task( description="Conduct a thorough research about AI Agents.", expected_output="A list with 10 bullet points of the most relevant information about AI Agents", agent=research_agent, ) # Execute the crew crew = Crew( agents=[research_agent], tasks=[research_task], verbose=True, ) result = crew.kickoff() # Accessing the task output task_output = research_task.output print(task_output) ``` ## Example output ```text theme={null} [2025-03-09 16:20:14][🚀 CREW 'CREW' STARTED, 42A4F700-E955-4794-B6F3-6EA6EF279E93]: 2025-03-09 16:20:14.069394 [2025-03-09 16:20:14][📋 TASK STARTED: CONDUCT A THOROUGH RESEARCH ABOUT AI AGENTS.]: 2025-03-09 16:20:14.085335 [2025-03-09 16:20:14][🤖 AGENT 'RESEARCH ANALYST' STARTED TASK]: 2025-03-09 16:20:14.096438 # Agent: Research Analyst ## Task: Conduct a thorough research about AI Agents. [2025-03-09 16:20:14][🤖 LLM CALL STARTED]: 2025-03-09 16:20:14.096671 [2025-03-09 16:20:18][✅ LLM CALL COMPLETED]: 2025-03-09 16:20:18.993612 # Agent: Research Analyst ## Final Answer: * AI Agents are computer programs that use artificial intelligence (AI) to perform tasks that typically require human intelligence, such as reasoning, problem-solving, and decision-making. They can be used in a variety of applications, including virtual assistants, customer service chatbots, and autonomous vehicles. * There are several types of AI Agents, including simple reflex agents, model-based reflex agents, goal-based agents, and utility-based agents. Each type of agent has its own strengths and weaknesses, and is suited to specific tasks and environments. * AI Agents can be classified into two main categories: narrow or weak AI, and general or strong AI. Narrow AI is designed to perform a specific task, while general AI is designed to perform any intellectual task that a human can. * AI Agents use a variety of techniques to make decisions and take actions, including machine learning, deep learning, and natural language processing. They can also use sensors and other data sources to perceive their environment and make decisions based on that information. * One of the key benefits of AI Agents is their ability to automate repetitive and mundane tasks, freeing up human workers to focus on more complex and creative tasks. They can also provide 24/7 customer support and help to improve customer engagement and experience. * AI Agents can be used in a variety of industries, including healthcare, finance, and transportation. For example, AI-powered chatbots can be used to help patients schedule appointments and access medical records, while AI-powered virtual assistants can be used to help drivers navigate roads and avoid traffic. * Despite their many benefits, AI Agents also have some limitations and challenges. For example, they can be biased if they are trained on biased data, and they can struggle to understand the nuances of human language and behavior. * AI Agents can be used to improve decision-making and problem-solving in a variety of contexts. For example, they can be used to analyze large datasets and identify patterns and trends, and they can be used to simulate different scenarios and predict outcomes. * The development and use of AI Agents raises important ethical and social questions, such as the potential impact on employment and the need for transparency and accountability in AI decision-making. It is essential to consider these questions and develop guidelines and regulations for the development and use of AI Agents. * The future of AI Agents is likely to involve the development of more advanced and sophisticated agents that can learn and adapt in complex and dynamic environments. This may involve the use of techniques such as reinforcement learning and transfer learning, and the development of more human-like AI Agents that can understand and respond to human emotions and needs. [2025-03-09 16:20:19][✅ AGENT 'RESEARCH ANALYST' COMPLETED TASK]: 2025-03-09 16:20:19.012674 [2025-03-09 16:20:19][✅ TASK COMPLETED: CONDUCT A THOROUGH RESEARCH ABOUT AI AGENTS.]: 2025-03-09 16:20:19.012784 [2025-03-09 16:20:19][✅ CREW 'CREW' COMPLETED, 42A4F700-E955-4794-B6F3-6EA6EF279E93]: 2025-03-09 16:20:19.027344 ``` # Overview Source: https://docs.together.ai/docs/dedicated-container-inference Deploy your own containers on Together's managed GPU infrastructure with automatic scaling, job queues, and built-in observability. > [!NOTE] > > Dedicated container inference is available through the Together sales team. [Contact sales](https://www.together.ai/contact-sales) to get access. > [!TIP] > > Using a coding agent? Install the [together-ai](https://github.com/togethercomputer/skills/tree/main/skills/together-ai) skill to let your agent write correct dedicated container code automatically. See [agent skills](/docs/agent-skills) for details. Dedicated container inference lets you run your own Dockerized inference workloads on Together's managed GPU infrastructure. You bring the container, and Together handles compute provisioning, autoscaling, networking, and observability. * **Fast setup:** Wrap and deploy your model in 20 minutes. * **Priority queueing:** The managed job queue runs higher-priority jobs first, so you can serve your most valuable traffic ahead of the rest. * **Scale with demand:** Together adds replicas as traffic grows, up to thousands of GPUs, and can scale down to zero when idle. You deploy with the [Jig CLI](/docs/deployments-jig) in one of two ways: **Build a custom worker:** Use the [Sprocket SDK](/docs/deployments-sprocket) in your container to connect your inference code to Together's managed [job queue](/docs/deployments-queue), then build, push, and deploy the Docker image with Jig. **[Deploy a prebuilt image](/docs/dedicated-containers-vllm):** To serve an off-the-shelf image like stock vLLM, deploy it as-is with Jig. You don't write Sprocket code or build an image. ![Dedicated container inference architecture](https://mintcdn.com/togetherai-52386018/guu83tcrNiDPEySM/images/dedicatedcontainers.svg?fit=max\&auto=format\&n=guu83tcrNiDPEySM\&q=85\&s=1697805b576af1b144ac6f280e829ecc) *** ## Quickstart To deploy a custom worker with the [Jig CLI](/docs/deployments-jig), run three commands: ```bash theme={null} # scaffold the jig config next to your inference code tg beta jig init # build, push, and deploy the container in one step tg beta jig deploy # watch the deployment come up tg beta jig status ``` > [card] [Deploy your first container](/docs/containers-quickstart) > > Deploy a sample inference worker, submit a job, and get the result. ## Concepts > [card] [Architecture](/docs/together-deployments) > > Learn the deployment lifecycle and autoscaling, and troubleshoot common issues. > [card] [Jig CLI](/docs/deployments-jig) > > Build and deploy containers, and manage secrets and volumes. > [card] [Sprocket SDK](/docs/deployments-sprocket) > > Write inference workers with `setup()` and `predict()`. > [card] [Queue API](/docs/deployments-queue) > > Submit asynchronous jobs with priorities and track their progress. ## Tutorials > [card] [Image generation](/docs/dedicated-containers-image) > > Generate images with FLUX.2 on a single GPU. > [card] [Video generation](/docs/dedicated-containers-video) > > Generate video with Wan 2.1 across multiple GPUs using `torchrun`. > [card] [OpenAI-compatible endpoint](/docs/dedicated-containers-openai) > > Serve FLUX.2 behind the OpenAI Images API. > [card] [Prebuilt vLLM image](/docs/dedicated-containers-vllm) > > Serve Qwen2.5-VL from the stock vLLM image, with no Sprocket code and no Docker build. ## Reference > [card] [Jig CLI](/reference/cli/jig) > > Look up CLI commands and `pyproject.toml` configuration. > [card] [Sprocket SDK](/reference/dci-reference-sprocket) > > Look up base classes, file handling, and errors. > [card] [REST API](/reference/deployments-list) > > Look up the deployments, secrets, storage, and queue endpoints. # Image generation with FLUX.2 Source: https://docs.together.ai/docs/dedicated-containers-image Deploy a FLUX.2 image generation model on Together's managed GPU infrastructure with dedicated container inference. This example demonstrates deploying a text-to-image model with dedicated container inference. You'll build a Sprocket worker that generates images from text prompts and deploy it to Together's managed GPU infrastructure. ## What you'll learn * Deploying a custom model with Sprocket and Jig. * Returning base64-encoded images from your worker. * Submitting jobs via the Queue API and polling for results. * Configuring autoscaling for production workloads. ## Requirements * **Dedicated containers access:** [Contact sales](https://www.together.ai/contact-sales) to enable it for your organization. * **Docker:** For building container images. [Install Docker](https://docs.docker.com/engine/install). * **Together CLI:** Install or upgrade with `uv tool install "together[cli]" --upgrade`. Install the Together Python SDK in the project you submit jobs from: ```shell theme={null} uv add together ``` Authenticate the CLI: ```shell theme={null} tg login ``` ## Overview This example deploys a FLUX.2 text-to-image model as a dedicated container. The Sprocket worker handles job processing, and Together manages GPU provisioning, autoscaling, and observability. **What gets deployed:** * A Sprocket worker running on an H100 GPU. * Queue-based job processing for async image generation. * Automatic scaling based on queue depth. ## How it works 1. **Build:** Jig builds a Docker image from your `pyproject.toml` configuration. 2. **Push:** The image is pushed to Together's private container registry. 3. **Deploy:** Together provisions an H100 GPU and starts your container. 4. **Queue:** Jobs are submitted to the managed queue and processed by your Sprocket worker. 5. **Scale:** The autoscaler adjusts replicas based on queue depth. ## Project structure ```text theme={null} flux2-dev/ ├── pyproject.toml # Configuration and dependencies └── run.py # Sprocket worker implementation ``` ## Implementation ### Sprocket worker code ```python run.py theme={null} import base64 import logging from io import BytesIO import sprocket import torch from diffusers import Flux2Pipeline logging.basicConfig(level=logging.INFO) class Flux2Sprocket(sprocket.Sprocket): def setup(self) -> None: model_id = "diffusers/FLUX.2-dev-bnb-4bit" device = "cuda" if torch.cuda.is_available() else "cpu" logging.info(f"Loading Flux2 pipeline from {model_id} on {device}...") self.pipe = Flux2Pipeline.from_pretrained( model_id, torch_dtype=torch.bfloat16 ).to(device) logging.info("Pipeline loaded successfully!") def predict(self, args: dict) -> dict: prompt = args.get("prompt", "a cat") # Optional parameters with defaults num_inference_steps = args.get("num_inference_steps", 28) guidance_scale = args.get("guidance_scale", 4.0) # Generate image logging.info(f"Generating image for prompt: {prompt[:50]}...") image = self.pipe( prompt=prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, ).images[0] # Convert to base64 buffered = BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() logging.info("Image generated successfully") return {"image": img_str, "format": "png", "encoding": "base64"} if __name__ == "__main__": sprocket.run(Flux2Sprocket()) ``` ### Configuration ```toml pyproject.toml theme={null} [project] name = "sprocket-flux2-dev" version = "0.1.0" dependencies = [ "diffusers==0.36.0", "transformers==4.57.6", "torch==2.6.0", "pillow==12.2.0", "accelerate==1.13.0", "sprocket==0.1.8", "torchvision==0.21.0", "bitsandbytes==0.48.2", "safetensors==0.6.2", ] [[tool.uv.index]] name = "together-pypi" url = "https://pypi.together.ai/" [tool.uv.sources] sprocket = { index = "together-pypi" } [tool.jig.image] python_version = "3.11" # triton (via bitsandbytes) JIT-compiles CUDA kernels at import time, needs gcc system_packages = ["gcc", "g++"] cmd = "python3 run.py --queue" auto_include_git = false copy = ["run.py"] [tool.jig.deploy] description = "Flux2-dev Image Generation with Sprocket" gpu_type = "h100-80gb" gpu_count = 1 cpu = 4 memory = 32 port = 8000 min_replicas = 1 max_replicas = 1 ``` ## Key concepts ### Base64 image encoding Images are returned as base64-encoded strings for JSON compatibility: ```python theme={null} def predict(self, args: dict) -> dict: # Generate the image image = self.pipe(prompt=args["prompt"]).images[0] # Encode as PNG in base64 buffered = BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() return {"image": img_str, "format": "png", "encoding": "base64"} ``` **Decoding on the client:** ```python theme={null} import base64 from PIL import Image from io import BytesIO # Decode the response image_data = base64.b64decode(response["image"]) image = Image.open(BytesIO(image_data)) image.save("output.png") ``` ### Generation parameters FLUX.2 supports several parameters to control generation: | Parameter | Default | Description | | - | - | - | | `prompt` | `"a cat"` | Text description of the image | | `num_inference_steps` | `28` | Denoising steps (more = better quality, slower) | | `guidance_scale` | `4.0` | How closely to follow the prompt (higher = more literal) | ```python theme={null} image = self.pipe( prompt=prompt, num_inference_steps=28, # Default for good quality/speed balance guidance_scale=4.0, # Moderate guidance ).images[0] ``` ## Deployment ### Deploy From the `flux2-dev` directory, deploy the worker and follow its startup logs: ```shell Shell theme={null} # Deploy (builds, pushes, and creates deployment) tg beta jig deploy # Or deploy with cache warmup to reduce cold start latency tg beta jig deploy --warmup # Monitor startup (model download takes a few minutes on first deploy) tg beta jig logs --follow ``` ### Check deployment status ```shell Shell theme={null} # View deployment status and replica health tg beta jig status ``` Wait until the deployment shows `running` and replicas are ready before submitting jobs. ### Submit jobs Jobs are submitted to the managed queue and processed asynchronously. You'll need to poll for the result. ```python Python SDK theme={null} from together import Together import base64 import time from io import BytesIO from PIL import Image client = Together(api_key="xxx") deployment = "sprocket-flux2-dev" # Submit job to queue job = client.beta.jig.queue.submit( model=deployment, payload={ "prompt": "A serene Japanese garden with cherry blossoms", "num_inference_steps": 28, "guidance_scale": 4.0, }, ) print(f"Job submitted: {job.request_id}") # Poll for completion while True: status = client.beta.jig.queue.retrieve( request_id=job.request_id, model=deployment, ) if status.status == "done": # Decode and save the image image_data = base64.b64decode(status.outputs["image"]) image = Image.open(BytesIO(image_data)) image.save("output.png") print("Image saved to output.png") break elif status.status == "failed": print(f"Job failed: {status.error}") break else: print(f"Status: {status.status}") time.sleep(2) ``` ```python requests theme={null} import base64 import time import requests from io import BytesIO from PIL import Image api_key = "your_key_here" deployment = "sprocket-flux2-dev" # Submit job to queue response = requests.post( "https://api.together.ai/v1/queue/submit", headers={"Authorization": f"Bearer {api_key}"}, json={ "model": deployment, "payload": { "prompt": "A serene Japanese garden with cherry blossoms", "num_inference_steps": 28, "guidance_scale": 4.0, }, }, ) job = response.json() print(f"Job submitted: {job['request_id']}") # Poll for completion while True: status_response = requests.get( f"https://api.together.ai/v1/queue/status?request_id={job['request_id']}&model={deployment}", headers={"Authorization": f"Bearer {api_key}"}, ) status = status_response.json() if status["status"] == "done": # Decode and save the image image_data = base64.b64decode(status["outputs"]["image"]) image = Image.open(BytesIO(image_data)) image.save("output.png") print("Image saved to output.png") break elif status["status"] == "failed": print(f"Job failed: {status.get('error')}") break else: print(f"Status: {status['status']}") time.sleep(2) ``` ```shell cURL theme={null} # Submit job curl -X POST https://api.together.ai/v1/queue/submit \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "sprocket-flux2-dev", "payload": { "prompt": "A futuristic cityscape at night with neon lights", "num_inference_steps": 28, "guidance_scale": 4.0 } }' # Response: {"request_id": "req_abc123", "status": "pending"} # Poll for result (replace REQUEST_ID with actual value) curl "https://api.together.ai/v1/queue/status?request_id=REQUEST_ID&model=sprocket-flux2-dev" \ -H "Authorization: Bearer $TOGETHER_API_KEY" # When status is "done", decode the image from outputs.image ``` ## Input parameters | Parameter | Type | Default | Description | | - | - | - | - | | `prompt` | string | `"a cat"` | Text description of the image to generate | | `num_inference_steps` | int | `28` | Number of denoising steps | | `guidance_scale` | float | `4.0` | Classifier-free guidance scale | ## Output ```json theme={null} { "image": "iVBORw0KGgoAAAANSUhEUgAA...", "format": "png", "encoding": "base64" } ``` * `image`: Base64-encoded PNG image data. * `format`: Image format (always `"png"`). * `encoding`: Encoding type (always `"base64"`). ### Batch processing and autoscaling The configuration above can be updated to include autoscaling by increasing the `max_replicas` parameter. Then when the queue backlog grows, more replicas are added automatically. When workers are idle, replicas are removed (down to `min_replicas`). To scale more aggressively for high-throughput workloads: ```toml theme={null} [tool.jig.deploy] min_replicas = 2 # Always keep 2 warm replicas max_replicas = 50 # Scale up to 50 replicas [tool.jig.deploy.autoscaling] metric = "QueueBacklogPerWorker" target = 0.9 # More aggressive scaling (more workers than needed) ``` To scale to zero when idle, specify `min_replicas = 0` (saves costs but adds cold start latency): ```toml theme={null} [tool.jig.deploy] min_replicas = 0 max_replicas = 10 ``` ## Cleanup When you're done, delete the deployment: ```shell Shell theme={null} tg beta jig destroy ``` ## Next steps > [card] [Video generation with Wan 2.1](/docs/dedicated-containers-video) > > Run multi-GPU inference with torchrun. > [card] [Serve an OpenAI-compatible endpoint](/docs/dedicated-containers-openai) > > Serve the same model behind the OpenAI Images API. > [card] [Quickstart](/docs/containers-quickstart) > > Deploy your first container in 20 minutes. > [card] [Sprocket SDK reference](/reference/dci-reference-sprocket) > > Full SDK reference for workers. > [card] [Jig CLI reference](/reference/cli/jig) > > CLI commands and configuration options. > [card] [Deployments API reference](/reference/deployments-list) > > REST API for deployments, secrets, storage, and queues. # Serve an OpenAI-compatible endpoint Source: https://docs.together.ai/docs/dedicated-containers-openai Deploy a custom model behind an OpenAI-compatible endpoint using dedicated containers. This guide deploys FLUX.2 behind an OpenAI-compatible `/v1/images/generations` endpoint using Sprocket and Jig. Clients call it with the OpenAI SDK or plain HTTP, with no Together-specific request or response shapes. Two things make a container OpenAI-compatible: * **HTTP server mode:** Run the worker without the `--queue` flag. Requests go straight to your container and return synchronously, instead of through the managed queue. * **`predict_path`:** Pass the OpenAI route to `sprocket.run()`. In HTTP server mode the raw JSON request body is passed straight to `predict()`, so `predict()` owns both parsing the OpenAI request and returning the OpenAI response shape. ## Requirements * **Together API key:** Get one from [together.ai](https://together.ai). * **Dedicated containers access:** [Contact sales](https://www.together.ai/contact-sales) to enable it for your organization. * **Docker:** For building container images. [Install Docker](https://docs.docker.com/engine/install). * **Together CLI:** Install or upgrade with `uv tool install "together[cli]" --upgrade`. * **Hugging Face token:** The FLUX.2 weights are gated. Request access to [black-forest-labs/FLUX.2-klein-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B). ## HTTP server mode vs queue mode The [image generation example](/docs/dedicated-containers-image) serves the same model family through the managed queue. The difference is entirely in how requests are served: | | Queue mode | HTTP server mode (this guide) | | - | - | - | | Startup command | `python3 run.py --queue` | `python3 run.py` | | Request shape | Your own payload dict | Whatever your route expects (here, OpenAI) | | How you call it | Submit to the queue with the SDK or `curl`, then poll | OpenAI client or `curl` against the endpoint URL | | Best for | Long-running jobs that need durability and progress tracking | Synchronous requests and OpenAI-compatible clients | ## Write the worker The worker validates the OpenAI Images request with Pydantic, generates the image(s), and returns the OpenAI response shape. The last line sets the endpoint path: ```python run.py theme={null} import base64 import time from io import BytesIO from typing import Literal import sprocket import torch from diffusers import Flux2KleinPipeline from pydantic import BaseModel, Field, ValidationError # FLUX.2-klein is distilled for few-step inference. NUM_INFERENCE_STEPS = 4 GUIDANCE_SCALE = 1.0 class ImageGenerationRequest(BaseModel): """The subset of the OpenAI Images API this worker accepts.""" prompt: str = Field(min_length=1) model: str | None = None n: int = Field(default=1, ge=1, le=10) size: str = Field(default="1024x1024", pattern=r"^\d+x\d+$") response_format: Literal["b64_json"] = "b64_json" class Flux2OpenAISprocket(sprocket.Sprocket): def setup(self) -> None: self.pipe = Flux2KleinPipeline.from_pretrained( "black-forest-labs/FLUX.2-klein-9B", torch_dtype=torch.bfloat16, ).to("cuda") def _generate_one(self, req: ImageGenerationRequest) -> str: width, height = (int(d) for d in req.size.split("x")) image = self.pipe( prompt=req.prompt, width=width, height=height, num_inference_steps=NUM_INFERENCE_STEPS, guidance_scale=GUIDANCE_SCALE, ).images[0] buffer = BytesIO() image.save(buffer, format="PNG") return base64.b64encode(buffer.getvalue()).decode() def predict(self, args: dict) -> dict: try: req = ImageGenerationRequest.model_validate(args) except ValidationError as e: raise ValueError(f"invalid request: {e}") from e return { "created": int(time.time()), "data": [ {"b64_json": self._generate_one(req)} for _ in range(req.n) ], } if __name__ == "__main__": sprocket.run(Flux2OpenAISprocket(), predict_path="/v1/images/generations") ``` Three details to note: * **`predict_path` sets the route:** Without it, the worker serves `POST /generate`. Setting it to `/v1/images/generations` is what lets OpenAI clients call the deployment unmodified. The path can't collide with the reserved `/health` and `/metrics` routes. * **`predict()` owns the contract:** Pydantic rejects bad types, out-of-range `n`, or an unsupported `response_format` before generation runs. The returned dict is sent back as the JSON response body, so it must match the OpenAI response shape exactly. * **`b64_json` only:** Returning base64 keeps the image in the response with no external storage dependency, and it is what `gpt-image-1` itself returns. Serving the `url` response format would require publicly fetchable storage, which this guide doesn't cover. To support more of the OpenAI Images API (`quality`, `output_format`, `output_compression`), add the fields to `ImageGenerationRequest` and map them to pipeline arguments. Pydantic ignores fields you don't declare, so clients sending extra OpenAI parameters won't get errors. ## Configure the deployment ```toml pyproject.toml theme={null} [project] name = "flux2-openai" version = "0.1.0" requires-python = ">=3.11" dependencies = [ "diffusers==0.38.0", "transformers==4.57.1", "torch==2.6.0", "torchvision==0.21.0", "pillow==12.2.0", "accelerate==1.13.0", "safetensors==0.7.0", "sprocket==0.1.8", "pydantic==2.12.3", ] [[tool.uv.index]] name = "together-pypi" url = "https://pypi.together.ai/" [tool.uv.sources] sprocket = { index = "together-pypi" } [tool.jig.image] python_version = "3.11" cmd = "python3 run.py" auto_include_git = false copy = ["run.py"] [tool.jig.deploy] description = "FLUX.2 with an OpenAI-compatible endpoint" gpu_type = "h100-80gb" gpu_count = 1 cpu = 4 memory = 32 storage = 50 port = 8000 min_replicas = 1 max_replicas = 1 ``` Unlike the queue examples, `cmd` has no `--queue` flag, so the worker runs in HTTP server mode. The example also pins one always-on replica so requests never wait for a cold start. ## Set the Hugging Face token The model weights are gated, so the container needs your Hugging Face token at runtime. Store it as a [secret](/reference/cli/jig#jig-secrets-set): ```shell theme={null} tg beta jig secrets set --name HF_TOKEN --value ``` ## Deploy ```shell theme={null} # Build, push, and create the deployment tg beta jig deploy # Monitor startup (model download takes a few minutes on first deploy) tg beta jig logs --follow # Confirm the deployment is running tg beta jig status ``` Then get the endpoint URL: ```shell theme={null} tg beta jig endpoint ``` The URL has the form `https://api.together.ai/v1/deployment-request/`. Requests to any path under it are forwarded to your container, authenticated with your Together API key. Your worker never handles auth. ## Call the endpoint Point any OpenAI client at the endpoint URL plus `/v1`, using your Together API key: ```python OpenAI Python SDK theme={null} import base64 import os from openai import OpenAI client = OpenAI( base_url="https://api.together.ai/v1/deployment-request/flux2-openai/v1", api_key=os.environ["TOGETHER_API_KEY"], ) result = client.images.generate( model="black-forest-labs/FLUX.2-klein-9B", prompt="a cat sitting on a red chair", n=1, size="1024x1024", response_format="b64_json", ) with open("out.png", "wb") as f: f.write(base64.b64decode(result.data[0].b64_json)) ``` ```bash cURL theme={null} curl "$(tg beta jig endpoint)/v1/images/generations" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "black-forest-labs/FLUX.2-klein-9B", "prompt": "a cat sitting on a red chair", "n": 1, "size": "1024x1024", "response_format": "b64_json" }' ``` The response is the standard OpenAI Images shape: ```json theme={null} { "created": 1700000000, "data": [{ "b64_json": "iVBORw0KGgoAAAANSUhEUgAA..." }] } ``` ### Supported parameters | Parameter | Notes | | - | - | | `prompt` | Required. | | `model` | Accepted for compatibility. The deployment serves one model. | | `n` | 1 to 10, default 1. | | `size` | `WIDTHxHEIGHT`, default `1024x1024`. | | `response_format` | Only `b64_json` is supported. | Any other OpenAI parameter is accepted and ignored, so standard clients work without modification. ## Clean up Delete the deployment when you're done: ```shell theme={null} tg beta jig destroy ``` ## Next steps > [card] [Image generation with queues](/docs/dedicated-containers-image) > > Serve the same model through the managed queue for async jobs. > [card] [Sprocket overview](/docs/deployments-sprocket) > > Understand queue mode, HTTP server mode, and the worker lifecycle. > [card] [Sprocket SDK reference](/reference/dci-reference-sprocket) > > Full reference for `sprocket.run()`, including `predict_path`. > [card] [Jig CLI reference](/reference/cli/jig) > > All deploy, secrets, and endpoint commands. # Video generation with Wan 2.1 Source: https://docs.together.ai/docs/dedicated-containers-video Deploy a multi-GPU video generation model on Together's managed GPU infrastructure using dedicated containers. This example demonstrates deploying a multi-GPU video generation model using dedicated containers. You'll build a Sprocket worker that uses `torchrun` for distributed inference across multiple GPUs and deploy it to Together's managed infrastructure. ## What you'll learn * Deploying multi-GPU models with Sprocket and Jig. * Using `use_torchrun=True` for distributed inference. * Automatic file upload with `FileOutput`. * Submitting jobs via the queue API and polling for results. ## Requirements * **Together API key:** Get one from [together.ai](https://together.ai). * **Dedicated containers access:** [Contact sales](https://www.together.ai/contact-sales) to enable it for your organization. * **Docker:** For building container images. [Install Docker](https://docs.docker.com/engine/install). * **Together CLI:** Install or upgrade with `uv tool install "together[cli]" --upgrade`. Set your API key: ```shell theme={null} export TOGETHER_API_KEY=your_key_here ``` Install the Together Python SDK in the project you submit jobs from: ```shell theme={null} uv add together ``` ## Overview This example deploys a Wan 2.1 text-to-video model as a dedicated container with multi-GPU support. The Sprocket worker handles distributed inference across two GPUs, and Together manages provisioning, autoscaling, and observability. **Output specs:** * Resolution: 480×832. * Frames: 81 (5.4 seconds at 15fps). * Format: MP4. **Why multi-GPU?** * Video generation requires significant VRAM for temporal attention. * Context parallelism splits the sequence dimension across GPUs. * 2x H100 allows comfortable generation without memory pressure. ## How it works 1. **Build:** Jig builds a Docker image from your `pyproject.toml` configuration. 2. **Push:** The image is pushed to Together's private container registry. 3. **Deploy:** Together provisions 2x H100 GPUs and starts your container. 4. **Torchrun:** Sprocket's `use_torchrun=True` launches child processes (one per GPU). 5. **Queue:** Jobs are submitted to the managed queue, broadcast to all GPU ranks, and processed in parallel. ## Project structure ```text theme={null} sprocket_wan2.1/ ├── pyproject.toml # Configuration and dependencies └── run_wan.py # Distributed Sprocket worker ``` ## Implementation ### Sprocket worker code ```python run_wan.py theme={null} from typing import Optional import torch import torch.distributed as dist from diffusers import WanPipeline from diffusers.utils import export_to_video from para_attn.context_parallel import init_context_parallel_mesh from para_attn.context_parallel.diffusers_adapters import parallelize_pipe import sprocket class WanSprocket(sprocket.Sprocket): def setup(self) -> None: dist.init_process_group() torch.cuda.set_device(dist.get_rank()) pipe = WanPipeline.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers") self.pipe = pipe.to("cuda") para_mesh = init_context_parallel_mesh(self.pipe.device.type) parallelize_pipe(self.pipe, mesh=para_mesh) def predict(self, args: dict) -> Optional[dict]: video = self.pipe( prompt=args["prompt"], negative_prompt="", height=480, width=832, num_frames=81, num_inference_steps=int(args.get("num_inference_steps", 30)), output_type="pil" if dist.get_rank() == 0 else "pt", ).frames[0] if dist.get_rank() == 0: print("Saving video to output.mp4") export_to_video(video, "output.mp4", fps=15) return {"url": sprocket.FileOutput("output.mp4")} if __name__ == "__main__": sprocket.run(WanSprocket(), use_torchrun=True) ``` ### Configuration ```toml pyproject.toml theme={null} [project] name = "sprocket-wan" version = "0.1.0" dependencies = [ "diffusers==0.33.0", "transformers==4.48.3", "para_attn==0.3.38", "ftfy==6.3.1", "accelerate==1.13.0", "einops==0.8.2", "omegaconf==2.3.0", "pillow==12.2.0", "ffmpeg-python==0.2.0", "opencv-python==4.13.0.92", "torch==2.6.0", "sprocket==0.1.8", ] [[tool.uv.index]] name = "together-pypi" url = "https://pypi.together.ai/" [tool.uv.sources] sprocket = { index = "together-pypi" } [tool.jig.image] python_version = "3.11" system_packages = ["libgl1", "libglx-mesa0", "ffmpeg"] cmd = "python3 run_wan.py --queue" auto_include_git = false copy = ["run_wan.py"] [tool.jig.deploy] description = "Wan2.1 Video Generation with Sprocket" gpu_type = "h100-80gb" gpu_count = 2 cpu = 4 memory = 32 port = 8000 min_replicas = 1 max_replicas = 1 termination_grace_period_seconds = 600 ``` ## Key concepts ### How `use_torchrun=True` works When you call `sprocket.run(..., use_torchrun=True)`, Sprocket handles multi-GPU orchestration automatically. **Flow:** 1. Parent process receives a job from Together's queue. 2. Job payload is broadcast to all child processes via Unix socket. 3. Each rank executes `setup()` once at startup, then `predict()` for each job. 4. Ranks synchronize via NCCL during forward pass. 5. Only rank 0 saves output and returns result. 6. Parent uploads `FileOutput` and reports job completion. ### Distributed process initialization Each worker process must initialize its distributed context before loading the model: ```python theme={null} def setup(self) -> None: # Required: Initialize the process group for NCCL communication dist.init_process_group() # Required: Set the correct GPU for this rank torch.cuda.set_device(dist.get_rank()) # Now load and parallelize the model... ``` When `use_torchrun=True` is passed to `sprocket.run()`, Sprocket launches torchrun internally, which sets `RANK`, `LOCAL_RANK`, `WORLD_SIZE`, and other environment variables. ### Rank 0 output pattern In distributed inference, only rank 0 should handle I/O and return results: ```python theme={null} def predict(self, args: dict) -> Optional[dict]: # Generate on all ranks (synchronized via NCCL) video = self.pipe( prompt=args["prompt"], # Rank 0 needs PIL for saving; others use tensors (less memory) output_type="pil" if dist.get_rank() == 0 else "pt", ).frames[0] # Only rank 0 saves and returns if dist.get_rank() == 0: export_to_video(video, "output.mp4", fps=15) return {"url": sprocket.FileOutput("output.mp4")} # Other ranks implicitly return None ``` **Why this pattern?** * Avoids duplicate file writes. * Reduces memory on non-rank-0 GPUs (tensor output vs PIL). * Sprocket collects output from rank 0 only. ### Automatic file upload with `FileOutput` Wrapping a path in `FileOutput` triggers automatic upload: ```python theme={null} return {"url": sprocket.FileOutput("output.mp4")} ``` **What happens:** 1. Sprocket detects the `FileOutput` in the response. 2. Uploads the file to Together's storage. 3. Replaces `FileOutput` with the access URL in the final response. The client receives (when polling job status): ```json theme={null} { "request_id": "req_abc123", "status": "done", "outputs": { "url": "https://..." } } ``` ### Multi-GPU configuration For multi-GPU deployments, configure `gpu_count` in your deployment settings and pass `use_torchrun=True` to `sprocket.run()`: ```toml theme={null} [tool.jig.deploy] gpu_count = 2 # Sprocket launches one process per GPU automatically ``` Sprocket handles launching `torchrun` internally. You don't need to include it in your `cmd`. It coordinates the parent process and GPU workers automatically. ## Deployment ### Deploy ```shell Shell theme={null} # Deploy (builds, pushes, and creates deployment) tg beta jig deploy # Or deploy with cache warmup to reduce cold start latency tg beta jig deploy --warmup # Monitor startup (model download takes a few minutes on first deploy) tg beta jig logs --follow ``` ### Check deployment status ```shell Shell theme={null} # View deployment status and replica health tg beta jig status ``` Wait until the deployment shows `running` and replicas are ready before submitting jobs. ### Submit jobs Jobs are submitted to the managed queue and processed asynchronously. Video generation typically takes 30-75 seconds depending on settings. ```python Python SDK theme={null} from together import Together import time client = Together() deployment = "sprocket-wan2.1" # Submit job to queue job = client.beta.jig.queue.submit( model=deployment, payload={ "prompt": "A serene lake at sunset with mountains in the background", "num_inference_steps": 30, }, ) print(f"Job submitted: {job.request_id}") # Poll for completion while True: status = client.beta.jig.queue.retrieve( request_id=job.request_id, model=deployment, ) print(f"Status: {status.status}") if status.status == "done": print(f"Video URL: {status.outputs['url']}") break elif status.status == "failed": print(f"Job failed: {status.error}") break time.sleep(5) ``` ```python requests theme={null} import requests import time api_key = "your_key_here" deployment = "sprocket-wan2.1" # Submit job to queue response = requests.post( "https://api.together.ai/v1/queue/submit", headers={"Authorization": f"Bearer {api_key}"}, json={ "model": deployment, "payload": { "prompt": "A cat playing with a ball of yarn", "num_inference_steps": 30, }, }, ) job = response.json() print(f"Job submitted: {job['request_id']}") # Poll for completion while True: status_response = requests.get( f"https://api.together.ai/v1/queue/status?request_id={job['request_id']}&model={deployment}", headers={"Authorization": f"Bearer {api_key}"}, ) status = status_response.json() print(f"Status: {status['status']}") if status["status"] == "done": print(f"Video URL: {status['outputs']['url']}") break elif status["status"] == "failed": print(f"Job failed: {status.get('error')}") break time.sleep(5) ``` ```shell cURL theme={null} # Submit job curl -X POST https://api.together.ai/v1/queue/submit \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "sprocket-wan2.1", "payload": { "prompt": "A serene lake at sunset with mountains in the background", "num_inference_steps": 30 } }' # Response: {"request_id": "req_abc123", "status": "pending"} # Poll for result (replace REQUEST_ID with actual value) curl "https://api.together.ai/v1/queue/status?request_id=REQUEST_ID&model=sprocket-wan2.1" \ -H "Authorization: Bearer $TOGETHER_API_KEY" # When status is "done", the video URL is in outputs.url ``` ## Input parameters | Parameter | Type | Default | Description | | - | - | - | - | | `prompt` | string | Required | Text description of the video to generate | | `num_inference_steps` | int | `30` | Number of denoising steps (higher = better quality, slower) | ## Output When the job completes, the status response contains: ```json theme={null} { "request_id": "req_abc123", "status": "done", "outputs": { "url": "https://..." } } ``` * `url`: URL to the generated MP4 video file (480×832, 81 frames, 15fps). Authenticated with your API key. ### Scaling to more GPUs To scale for higher throughput, increase `max_replicas` to add more workers: ```toml theme={null} [tool.jig.deploy] min_replicas = 1 max_replicas = 10 [tool.jig.deploy.autoscaling] metric = "QueueBacklogPerWorker" target = 1.05 ``` To scale to zero when idle, specify `min_replicas = 0` (saves costs but adds cold start latency). ## Cleanup When you're done, delete the deployment: ```shell Shell theme={null} tg beta jig destroy ``` ## Next steps > [card] [Image generation with Flux2](/docs/dedicated-containers-image) > > Run single-GPU inference with Flux2. > [card] [Serve an OpenAI-compatible endpoint](/docs/dedicated-containers-openai) > > Serve a model behind the OpenAI Images API. > [card] [Quickstart](/docs/containers-quickstart) > > Deploy your first container in 20 minutes. > [card] [Sprocket SDK reference](/reference/dci-reference-sprocket) > > Full SDK reference for workers. > [card] [Jig CLI reference](/reference/cli/jig) > > CLI commands and configuration options. > [card] [Deployments API reference](/reference/deployments-list) > > REST API for deployments, secrets, storage, and queues. # Deploy a prebuilt vLLM image Source: https://docs.together.ai/docs/dedicated-containers-vllm Serve a model from the stock vLLM Docker image with dedicated container inference. This guide uses [dedicated container inference](/docs/dedicated-container-inference) to serve [Qwen2.5-VL-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-32B-Instruct) from the public [`vllm/vllm-openai`](https://hub.docker.com/r/vllm/vllm-openai) image. vLLM already serves an OpenAI-compatible API, so you don't need a Sprocket worker or a Docker build. Jig deploys the image as-is, using two settings in `[tool.jig.deploy]`: * **`image`:** Deploy an existing image instead of building one. Jig skips `docker build` and `docker push`. * **`command`:** Override the image's startup command. Here it runs `vllm serve` with the model and serving flags. Requests go straight to vLLM's HTTP server instead of through the managed queue, so you call the deployment with any OpenAI client or `curl`, not `jig submit`. The full example is in the Sprocket repo at [`examples/qwen_vllm`](https://github.com/togethercomputer/sprocket/tree/main/examples/qwen_vllm). ## Requirements * **Together API key:** Get one from [together.ai](https://together.ai). * **Dedicated container inference access:** Contact your account representative or the [sales team](https://www.together.ai/contact-sales) to enable it for your organization. * **Together CLI:** Install with `uv tool install "together[cli]"`. * **OpenAI Python SDK:** The Python request sample uses it. Add it to your Python project with `uv add openai`. Export your API key. The deploy step and the request samples read it from `TOGETHER_API_KEY`: ```shell theme={null} export TOGETHER_API_KEY=your_key_here ``` ## Configure the deployment Create a directory with a single `pyproject.toml`: ```toml pyproject.toml theme={null} [project] name = "qwen25-vl" version = "1.0.0" [tool.jig.deploy] # Deploy an existing image instead of building one image = "vllm/vllm-openai:v0.17.1" description = "Qwen2.5-VL-32B on stock vLLM" gpu_type = "h100-80gb" gpu_count = 2 cpu = 4 memory = 64 port = 8000 min_replicas = 1 max_replicas = 10 command = [ "vllm", "serve", "Qwen/Qwen2.5-VL-32B-Instruct", "--port", "8000", "--host", "0.0.0.0", "--dtype", "bfloat16", "--limit-mm-per-prompt.image", "5", "--limit-mm-per-prompt.video", "5", "--tensor-parallel-size", "2", ] [tool.jig.deploy.autoscaling] metric = "CustomMetric" custom_metric_name = "vllm:num_requests_running" target = 4 ``` Before you deploy, check these settings: * **Pin the image tag:** This guide is tested with `v0.17.1`. Pin a specific tag, not `latest`, so a replica that restarts doesn't pick up a new vLLM release. * **Match GPUs to tensor parallelism:** Set `--tensor-parallel-size` to `gpu_count` so vLLM uses every GPU in the replica. Here, vLLM splits the 32B model in BF16 across two H100s. * **Match `port` to `--port`:** Together routes traffic to the port in `port`, so it must match the port vLLM listens on. * **Keep the default health check:** The default `health_check_path` is `/health`, which vLLM serves. The deployment reports ready once vLLM has loaded the model. * **Autoscale on vLLM's own metric:** vLLM exports Prometheus metrics on `/metrics`, so the [`CustomMetric` autoscaler](/docs/together-deployments#autoscaling) scales on `vllm:num_requests_running` with no extra code. * **Use a unique project name:** The `name` under `[project]` is the deployment name and the last segment of the endpoint URL. Deployment names must be unique, so if `qwen25-vl` is taken, change `name` and use the new name in the endpoint URL. ### Serve a different model Change the model ID in `command` and in your requests, then size `gpu_count`, `--tensor-parallel-size`, and `memory` to fit the new model. Any `vllm serve` flag can go in `command`. Qwen2.5-VL-32B-Instruct isn't gated, so this guide needs no Hugging Face token. For a gated model, store your token as a [secret](/reference/cli/jig#jig-secrets-set) before you deploy. vLLM reads `HF_TOKEN` from the environment when it downloads the weights. Run the command from the directory that contains `pyproject.toml`, so the secret attaches to this deployment: ```shell theme={null} tg beta jig secrets set --name HF_TOKEN --value your_hf_token ``` ## Deploy From the directory that contains `pyproject.toml`, create the deployment and watch it start: ```shell theme={null} # Create the deployment from the configured image tg beta jig deploy --detach # Watch vLLM start up (Ctrl+C to stop) tg beta jig logs --follow # Check readiness tg beta jig status ``` With `--detach`, `jig deploy` returns as soon as the deployment is created. Without it, the command waits for the replica to become ready, but it gives up two minutes after the container starts. vLLM takes longer than that to load the model, so the command exits with `Running but not ready after 120s` even though the deployment keeps starting. The first deploy takes 5 to 15 minutes while Together schedules two H100s, pulls the vLLM image, and vLLM downloads and loads about 65 GB of weights. The deployment is ready when `jig status` shows `Ready` for `Status` and `1/1 ready` for `Replicas`. When the deployment is ready, get the endpoint URL: ```shell theme={null} tg beta jig endpoint ``` The URL has the form `https://api.together.ai/v1/deployment-request/`. Together authenticates requests to any path under it with your Together API key, then forwards them to the container. ## Call the endpoint Point any OpenAI client at the endpoint URL plus `/v1`, using your Together API key. The `model` field must match the model ID you pass to `vllm serve` in `command`: ```python OpenAI Python SDK theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.together.ai/v1/deployment-request/qwen25-vl/v1", api_key=os.environ["TOGETHER_API_KEY"], ) response = client.chat.completions.create( model="Qwen/Qwen2.5-VL-32B-Instruct", messages=[ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png" }, }, {"type": "text", "text": "Describe this image."}, ], } ], ) print(response.choices[0].message.content) ``` ```bash cURL theme={null} curl https://api.together.ai/v1/deployment-request/qwen25-vl/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "Qwen/Qwen2.5-VL-32B-Instruct", "messages": [ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png"}}, {"type": "text", "text": "Describe this image."} ] } ] }' ``` The cURL request returns a standard OpenAI chat completion, and the Python sample prints only its `content`. A shortened response looks like this: ```json theme={null} { "id": "chatcmpl-b15bc3b243a529ed", "object": "chat.completion", "model": "Qwen/Qwen2.5-VL-32B-Instruct", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "This image depicts a serene and picturesque natural landscape, likely from a national park or wilderness area..." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 1759, "completion_tokens": 471, "total_tokens": 2230 } } ``` Other routes vLLM serves, such as `/v1/completions` and `/v1/models`, are available under the same endpoint URL. ## Delete the deployment The deployment keeps at least `min_replicas` replicas running, two H100s each, until you delete it. To delete it, run this from the directory that contains `pyproject.toml`: ```shell theme={null} tg beta jig destroy ``` ## Next steps > [card] [OpenAI-compatible endpoint with Sprocket](/docs/dedicated-containers-openai) > > Write your own worker when you need custom pre- or post-processing. > [card] [Autoscaling](/docs/together-deployments#autoscaling) > > Choose scaling metrics and targets, and see how replicas scale. > [card] [Jig CLI reference](/reference/cli/jig) > > Look up every `[tool.jig.deploy]` setting and deploy command. > [card] [Sprocket examples](https://github.com/togethercomputer/sprocket/tree/main/examples) > > Browse more deployable examples, from hello-world to speech-to-speech. # Run an A/B test Source: https://docs.together.ai/docs/dedicated-endpoints/ab-tests Compare a candidate deployment against a baseline on live traffic. Use A/B tests to split live traffic between a baseline deployment (the *control*) and one or more candidates (the *variants*) under a single endpoint, so you can compare them on real requests. ![Per-request cohort assignment. Requests flow through the endpoint router, which assigns each one to a cohort: about 95 percent go to the control and about 5 percent to the variant.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/ab-experiment-cohort-assignment.gif?s=11a40e86d796a84216ed63db5fcf3c7d) An A/B test doesn't shift the endpoint fully onto the new deployment. It maintains a fixed split, allowing you to measure how a new deployment performs before you promote it. ## How it works A/B tests compare two or more deployments on live traffic. While the A/B test is active, it subdivides the control's share of traffic among the control and its variants. Requests that would route to the control are re-sampled across the test members by the percentages you set. The rest of the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic) is unaffected. > [!WARNING] > > Test variants must be excluded from the endpoint's traffic split (weight `0` or unset). Only the control belongs in the split. A variant that has a non-zero traffic-split weight causes the test to fail to start. An A/B test needs exactly one control and at least one variant, up to 19 variants (20 members total). Each member, including the control, is assigned a percentage of the control's traffic, and the percentages must sum to 100. Because the test only subdivides traffic destined for the control, a control with `weight: 0` (or one that's absent from the traffic split) means the test receives no traffic at all. ![An A/B experiment cohort split. The endpoint router splits requests destined for the control between the control (95 percent, in the base traffic split) and the variant (5 percent, not in the base traffic split).](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/ab-experiment-cohort-split.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=7531127f0a3b04806e1e65f1a89b31fb) Deleting an A/B test ends the variant/control split immediately, returning all traffic to the control. ## Requirements You need a `READY` control deployment that is [receiving traffic](/docs/dedicated-endpoints/route-traffic), plus a model to test as the variant. The CLI's `ab` command creates the variant deployment for you. If you don't have a control yet, [create a control deployment](/docs/dedicated-endpoints/manage#create-a-deployment) first. The examples below use these example IDs, which you should replace with your own: * Endpoint: `ep_abc123`. * Control deployment: `dep_control123`. * Variant model: `ml_CbJNwQC2ZqCU2iFT3mrCh`. * Second variant model: `ml_Zk7pR2mQ9sT4vU6yB1nD3`. ## Create an A/B test > [tab] CLI > > **1. Route traffic to the control** > > Attach the control (and only the control) to the endpoint's traffic split. Pass the control's deployment ID—the CLI resolves its parent endpoint and preserves the other deployments' weights. For a single deployment, any non-zero weight routes all traffic to it: > > ```bash CLI theme={null} > tg endpoints update dep_control123 --traffic-weight 1 > ``` > > **2. Start the test** > > The CLI's `ab` command creates the variant deployment for the model you pass and starts the experiment, assigning `--percent` to the variant and the remainder to the control. Start the variant small, for example 5% (the CLI assigns the remaining 95% to the control). Percents must be integers in `[1, 99]` so the control keeps at least 1%. > > ```bash CLI theme={null} > tg endpoints ab ml_CbJNwQC2ZqCU2iFT3mrCh \ > --control dep_control123 \ > --percent 5 \ > --name sampling-tweak-v1 > ``` > > Note the experiment ID (`abx_...`) and the variant's deployment ID (`dep_...`) from the response. You use the experiment ID to adjust or delete the test, and the variant's deployment ID to ramp or promote it. > > **3. Send requests** > > [Send requests](/docs/dedicated-endpoints/requests) to the endpoint, using the endpoint string as the `model` field. > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > The console doesn't create the variant deployment for you, so first [add it to the endpoint](/docs/dedicated-endpoints/manage#create-a-deployment) at traffic weight `0`. The endpoint then has a running control in the traffic split and at least one variant at weight `0`. > > **1. Open the A/B test form** > > On the endpoint, select the **Traffic Tests** tab, then **New A/B test**. The console blocks the form until the endpoint has at least two deployments, including a running deployment that is already serving live traffic (traffic weight greater than `0`). > > **2. Name the test** > > Enter a **Name** and an optional **Description**. > > **3. Set the control and variants** > > Confirm the **Control** deployment (a running deployment that is serving live traffic) and select each **Variant** deployment, then set each member's traffic percentage. The percentages divide the control's share of traffic and must sum to 100. Keep each variant at traffic weight `0` in the endpoint's traffic split so the test can start. > > **4. Start the test** > > Select **Start A/B test**. > > ![The Start an A/B test dialog in the Together AI console, with a name field, a traffic-split bar, and Control and Variants sections that each pair a deployment with a traffic percentage.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/ab-test-create-dialog.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=8a0e28f07f7d8fc82cdd6705593ad3f0) > > The test appears in the **A/B tests** table on the Traffic Tests tab, where you can edit or stop it. > > ![The Traffic Tests tab in the Together AI console showing an A/B test row with its name, variant count, traffic split, and creation time.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/traffic-tests-populated.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=4ba28514e0b82b960e4ba59ee9ec7e67) ## Ramp the variant To change a variant's share, pass `--ab-percent` with the variant's deployment ID to `tg endpoints update`. The CLI finds the A/B test for that deployment, sets the variant to the new percent, and adjusts only the control so the members still sum to 100. Other variants stay unchanged. The deployment must be a variant in an existing experiment (not the control), and the control must remain at least 1%. Percents are integers in `[1, 99]`. ```bash CLI theme={null} tg endpoints update dep_variant456 --ab-percent 10 ``` You can also update members from the SDK or API. Set the update mask to `members`. Updating `members` replaces the whole set and re-validates the shape, so resend every member each time. The ETag is optional, but passing the current ETag guards against concurrent changes. In the console, open the test's actions menu on the **Traffic Tests** tab and select **Edit A/B test** to change member percentages. ![Ramping the variant. In week 1 the split is 95 percent control and 5 percent variant. A single update to the member set is atomic and, when an ETag is supplied, guarded against concurrent changes. In week 2 the split is 80 percent control and 20 percent variant.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/ab-experiment-ramp.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=dbe3327122c86ea3b617372638740826) ## Add more variants You can compare more than one candidate at once. Run `ab` again with the same control and a different variant model. The CLI creates the new variant deployment, finds the existing experiment for that control, and adds the deployment to it as another variant. ![A multi-way A/B experiment with one control and several variants. The control takes 70 percent and three variants take 10 percent each. An experiment can have up to 20 members, with exactly one control, and the percentages must sum to 100.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/ab-experiment-multi-way.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=edf877851d1132dba86e9243f2ff3cce) Each `ab` call carves the new variant's percentage out of the control's share and leaves the existing variants untouched. Continuing from the 90% / 10% split above, adding a second variant at 10% gives 80% control / 10% / 10%: ```bash CLI theme={null} tg endpoints ab ml_Zk7pR2mQ9sT4vU6yB1nD3 \ --control dep_control123 \ --percent 10 ``` An experiment allows up to 20 members with exactly one control, and the control's share can't drop below 1%. ## Promote a variant When you've picked a winner, the safest way to promote it is a [rollout](/docs/dedicated-endpoints/rollouts): pass `--detach` and the CLI removes the variant from the test (deleting the test if it can't continue without the variant), then shifts traffic to it while draining the control. ```bash CLI theme={null} tg endpoints rollout dep_variant456 --blue-green --detach ``` Alternatively, promote it by hand: [update the endpoint's traffic split](/docs/dedicated-endpoints/route-traffic) so the winning deployment serves all traffic, setting the winner's weight to a non-zero value and the other deployments to `0` (or delete them): ```bash CLI theme={null} tg endpoints update dep_control123 --traffic-weight 0 tg endpoints update dep_variant456 --traffic-weight 1 ``` Then [delete the test](#delete-the-test) to end the managed control/variant split. ## Delete the test Deleting an A/B test ends the variant/control split immediately. All traffic returns to the endpoint's regular traffic split, either the control, or the variant you [promoted](#promote-a-variant). The CLI's smart-delete `rm` accepts the experiment ID: ```bash CLI theme={null} tg endpoints rm abx_abc123 ``` In the console, open the test's actions menu on the **Traffic Tests** tab and select **Stop A/B test**. To clean up the member deployments, follow the teardown order in [Manage deployments](/docs/dedicated-endpoints/manage#delete-resources) for each deployment. ## Next steps > [card] [Create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment) > > Create control and variant deployments for an A/B test. > [card] [Split traffic](/docs/dedicated-endpoints/split-traffic) > > Promote a winning variant by updating the endpoint's traffic split. > [card] [Observability](/docs/dedicated-endpoints/monitoring) > > Compare control and variant deployments with per-deployment metrics. > [card] [Route traffic](/docs/dedicated-endpoints/route-traffic) > > Understand how traffic is routed across deployments under an endpoint. # Upload a LoRA adapter Source: https://docs.together.ai/docs/dedicated-endpoints/adapter Serve a custom LoRA adapter uploaded from Hugging Face or S3. Run inference on your own [low-rank adapter (LoRA)](/docs/fine-tuning/lora-vs-full) by uploading it to Together AI and deploying it for [dedicated model inference](/docs/dedicated-endpoints/overview). You can import an adapter from Hugging Face Hub or upload it from an S3 archive, whether or not you trained it on Together AI. You can also [upload a full fine-tuned model](/docs/dedicated-endpoints/custom-models) instead of an adapter. > [!NOTE] > > You don't need to upload adapters created with [post-training](/docs/post-training/overview), because their inference checkpoints are already registered on the platform. Checkpoints on [some base models](/docs/post-training/supported-models#checkpoints-and-deployment) aren't registered, so you can't deploy them. > > On [supported base models](/docs/post-training/supported-models#checkpoints-and-deployment), you can also attach several post-training adapters to one running [multi-LoRA deployment](/docs/post-training/multi-lora-deployment) of their base model and choose an adapter per request. ## Requirements An adapter is eligible for upload if it meets these requirements: * **Source:** Hugging Face Hub or an S3 presigned URL. * **Files:** The adapter directory must contain `adapter_config.json` and `adapter_model.safetensors`. * **Base model:** The adapter must target a base model that Together AI supports for dedicated inference. If you're uploading from S3, you must package the adapter files in a single archive (`.zip` or `.tar.gz`) with the files at the root of the archive, not nested inside an extra top-level directory. The presigned URL must point to the archive and have an expiration of at least 100 minutes. ## Create the adapter Register the adapter in your project before you upload weights. Every adapter must reference a [supported base model](/docs/dedicated-endpoints/models) via `baseModelId`. Give the adapter a readable name (for example `my-stsb-lora`), rather than a Hugging Face repo ID. If you pass an org-prefixed name like `predibase/glue_stsb`, the prefix will be stored on top of your project slug, and the catalog will render a doubled slug (for example `your-project/predibase/glue_stsb`). > [!TIP] > > Strip the org and pass only the bare repo name. An adapter that already has a doubled name can't be renamed, so the only fix is to delete it and re-upload under the correct name. List [supported models](/docs/dedicated-endpoints/models#list-supported-models-programmatically) and copy the `id` of the architecture the adapter targets (for example `ml_CbJNwQC2ZqCU2iFT3mrCh`). ```bash CLI theme={null} tg models create my-stsb-lora \ --type adapter \ --base-model ml_CbJNwQC2ZqCU2iFT3mrCh ``` ```python Python theme={null} from together import Together client = Together() identity = client.whoami() if identity.type != "project_api_key": raise RuntimeError("TOGETHER_API_KEY must be a project API key") project_id = identity.project.id adapter = client.models.create( project_id=project_id, type="adapter", name="my-stsb-lora", base_model_id="ml_CbJNwQC2ZqCU2iFT3mrCh", ) print(adapter) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together(); const identity = await client.whoami(); if (identity.type !== "project_api_key") { throw new Error("TOGETHER_API_KEY must be a project API key"); } const projectId = identity.project.id; const adapter = await client.models.create({ projectId, type: 'adapter', name: 'my-stsb-lora', baseModelId: 'ml_CbJNwQC2ZqCU2iFT3mrCh', }); console.log(adapter); ``` Save the returned model `id` (for example `ml_abc123`). You pass this value to the upload command in the next step. The `--type adapter` you set on create marks the record as a LoRA adapter, so the upload commands derive the type from the record and take no type flag. ### Create request fields | Field | Required | Description | | - | - | - | | `name` | Yes | Inference-addressable name for the uploaded adapter. | | `base_model_id` | Yes | `id` of the supported base model the adapter targets. | | `description` | No | Description shown in your project catalog. | ## Upload the adapter After creating the adapter record, upload its weights. Use a local upload when the files are on your machine, or a remote upload to stream them from Hugging Face or a presigned S3 URL. The adapter's type and base model come from the record you created, so you don't pass them again here. ### Upload from your machine Point the CLI at your local adapter directory: ```bash CLI theme={null} tg models upload ml_abc123 ./path/to/adapter-dir ``` ### Upload from Hugging Face or cloud storage A remote upload streams the weights server-side. Pass the source as `--from` (`remote_url` in the SDKs). The source must be one of: * A Hugging Face repo ID (`your-org/your-adapter`), optionally pinned to a revision as `your-org/your-adapter@revision`. * A Hugging Face repo URL (`https://huggingface.co/your-org/your-adapter`). * A presigned `https://` URL for an archive on Amazon S3, Google Cloud Storage, or Cloudflare R2. Other sources, such as an `s3://` path, an `http://` URL, or an IP address, are rejected before the upload starts. For a gated or private Hugging Face repo, also pass a Hugging Face token with `--token`. A presigned URL needs no token: ```bash CLI theme={null} tg models remote-uploads create ml_abc123 \ --from https://huggingface.co/your-org/your-adapter \ --token hf_your_token ``` ```python Python theme={null} from together import Together client = Together() identity = client.whoami() if identity.type != "project_api_key": raise RuntimeError("TOGETHER_API_KEY must be a project API key") project_id = identity.project.id job = client.models.remote_uploads.create( project_id=project_id, model_id="ml_abc123", remote_url="https://huggingface.co/your-org/your-adapter", token="hf_your_token", ) print(job) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together(); const identity = await client.whoami(); if (identity.type !== "project_api_key") { throw new Error("TOGETHER_API_KEY must be a project API key"); } const projectId = identity.project.id; const job = await client.models.remoteUploads.create({ projectId, modelId: 'ml_abc123', remoteUrl: 'https://huggingface.co/your-org/your-adapter', token: 'hf_your_token', }); console.log(job); ``` The response is the upload job object, with `id`, `modelId`, and `status` at the top level. Save the job `id` to [poll for status](#check-upload-status). ### Upload from the console The console combines creating the adapter record and uploading its weights into a single form. [Upload a model](https://api.together.ai/models/upload) **1. Set the upload type** Set **Upload type** to **Adapter (LoRA)**. **2. Choose the source** Under **Model source**, select **Import from Hugging Face** and enter the repo path or URL (add a **Hugging Face token** for gated or private repos), or select **Download from S3** and paste a presigned archive URL. **Upload from your machine** shows a CLI command instead, so use `tg models upload` for files on your machine. **3. Name and configure the adapter** Enter a **Model name**, choose a **Visibility**, and select the **Compatible base model** the adapter runs on top of. **4. Import** Select **Import**. The upload runs server-side, with progress shown below the form. You can leave the form: the adapter appears under **My models** with an **Uploading** badge while the job is pending or running. ![The Upload model form in the Together AI console, set to Adapter (LoRA) with Import from Hugging Face selected, showing fields for repository or URL, Hugging Face token, model name, visibility, and compatible base model.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/adapter-upload-form.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=58d17f6c5be07cc9fea09389ca2393d1) ## Check upload status Poll the remote-upload job until `status` is `REMOTE_UPLOAD_STATUS_SUCCEEDED`. The adapter is ready to deploy at that point. ```bash CLI theme={null} # One upload job tg models remote-uploads retrieve job_abc123 # All upload jobs in the project tg models remote-uploads list ``` ```python Python theme={null} from together import Together client = Together() identity = client.whoami() if identity.type != "project_api_key": raise RuntimeError("TOGETHER_API_KEY must be a project API key") project_id = identity.project.id # One upload job job = client.models.remote_uploads.retrieve( "job_abc123", project_id=project_id, ) print(job.status) # All upload jobs in the project jobs = client.models.remote_uploads.list(project_id=project_id) print(jobs) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together(); const identity = await client.whoami(); if (identity.type !== "project_api_key") { throw new Error("TOGETHER_API_KEY must be a project API key"); } const projectId = identity.project.id; // One upload job const job = await client.models.remoteUploads.retrieve('job_abc123', { projectId, }); console.log(job.status); // All upload jobs in the project const jobs = await client.models.remoteUploads.list({ projectId }); console.log(jobs); ``` Once the job reaches `REMOTE_UPLOAD_STATUS_SUCCEEDED`, confirm the files landed: ```bash CLI theme={null} tg models ls-files ml_abc123 ``` [My models](https://api.together.ai/models?category=my-models) You can also track uploads on the **My models** page in the console. While a remote upload is pending or running, the adapter floats to the top of **My models** with an **Uploading** badge. Open the adapter to watch the live **Upload progress** event log on the model detail page. The revisions table appears after the upload finishes. That list also includes Internal-visibility adapters from other projects in your organization. Use the **Visibility** filter to show only **Internal** or only **Private** adapters. ## Check revision validation After files land, Together validates the revision's weights automatically. Validation checks that the weights are in safetensors format and that the adapter is compatible with its base model. A revision must reach `REVISION_VALIDATION_STATUS_SUCCESS` before you can deploy it when you pin that revision explicitly. List revisions for an adapter: ```bash CLI theme={null} tg models ls-revisions ml_abc123 ``` The list and retrieve revision APIs also return validation fields on each revision. Replace `$PROJECT_ID` with your project ID (`proj_...`): ```bash Shell theme={null} # All revisions curl -s -H "Authorization: Bearer $TOGETHER_API_KEY" \ "https://api.together.ai/v2/projects/$PROJECT_ID/models/ml_abc123/revisions" # One revision curl -s -H "Authorization: Bearer $TOGETHER_API_KEY" \ "https://api.together.ai/v2/projects/$PROJECT_ID/models/ml_abc123/revisions/rv_abc123" ``` Each revision in the response includes: ```json theme={null} { "data": [ { "revisionId": "rv_abc123", "createdAt": "2026-07-02T20:05:00Z", "validationStatus": "REVISION_VALIDATION_STATUS_SUCCESS", "lastValidatedAt": "2026-07-02T20:06:00Z", "validationErrors": [] } ], "object": "list" } ``` ### Revision validation fields | Field | Description | | - | - | | `validationStatus` | Validation state for this revision. See the table below. | | `lastValidatedAt` | When validation last ran for this revision. Omitted until validation has started. | | `validationErrors` | Errors from the last validation run. Empty when validation succeeded or is still pending. | ### `validationStatus` values | Value | Meaning | | - | - | | `REVISION_VALIDATION_STATUS_PENDING` | Validation is queued or running. Poll until the status changes. | | `REVISION_VALIDATION_STATUS_SUCCESS` | Weights validated successfully. The revision is ready to deploy. | | `REVISION_VALIDATION_STATUS_FAILED` | Validation failed. Read `validationErrors` for the cause. | | `REVISION_VALIDATION_STATUS_ERROR` | Validation could not complete due to an internal error. Retry later or contact support. | | `REVISION_VALIDATION_STATUS_UNSPECIFIED` | Validation has not started yet. | When validation fails, each entry in `validationErrors` includes `rule`, `severity`, and `message` describing what went wrong. ## Deploy the adapter Once the upload completes, your adapter has a model ID (`ml_...`) in your project, linked to its base model. Deploy it the same way as a base model, using a [config](/docs/dedicated-endpoints/configs) for its base model. The CLI's `deploy` command creates the endpoint, attaches a deployment, and routes all traffic to it in one step. For an adapter, pass `--merge`, which deploys the adapter merged into its base model. The SDK has no single equivalent, so the Python and TypeScript samples run the same steps individually: ```bash CLI theme={null} tg endpoints deploy ml_abc123 \ --endpoint my-adapter \ --merge \ --config cr_CbzGdmn14t3HYrXXitmKa \ --project your_project_id ``` ```python Python theme={null} from together import Together client = Together() identity = client.whoami() if identity.type != "project_api_key": raise RuntimeError("TOGETHER_API_KEY must be a project API key") project_id = identity.project.id model = f"projects/{project_id}/models/ml_abc123" config = f"projects/{project_id}/configs/cr_CbzGdmn14t3HYrXXitmKa" # 1. Create the endpoint. endpoint = client.endpoints.create( project_id=project_id, name="my-adapter", ) # 2. Create a deployment bound to your adapter and config. deployment = client.endpoints.deployments.create( endpoint.id, project_id=project_id, name="prod", model=model, config=config, autoscaling={"min_replicas": 1, "max_replicas": 1}, ) # 3. Route 100% of traffic to the deployment. client.endpoints.update( endpoint.id, project_id=project_id, traffic_split=[{"deployment_id": deployment.id, "weight": 1}], ) print(endpoint.name) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together(); const identity = await client.whoami(); if (identity.type !== "project_api_key") { throw new Error("TOGETHER_API_KEY must be a project API key"); } const projectId = identity.project.id; const model = `projects/${projectId}/models/ml_abc123`; const config = `projects/${projectId}/configs/cr_CbzGdmn14t3HYrXXitmKa`; // 1. Create the endpoint. const endpoint = await client.endpoints.create({ projectId, name: 'my-adapter', }); // 2. Create a deployment bound to your adapter and config. const deployment = await client.endpoints.deployments.create( endpoint.id, { projectId, name: 'prod', model, config, autoscaling: { minReplicas: 1, maxReplicas: 1 }, }, ); // 3. Route 100% of traffic to the deployment. await client.endpoints.update(endpoint.id, { projectId, trafficSplit: [{ deploymentId: deployment.id, weight: 1 }], }); console.log(endpoint.name); ``` See [Manage deployments](/docs/dedicated-endpoints/manage) for the full deployment lifecycle. ## Run inference Once the deployment is `READY` and routable, call the endpoint by its endpoint string (`/`), the same as any other dedicated endpoint. Dedicated model inference is served at `https://api-inference.together.ai`: ```bash cURL theme={null} curl -s -X POST https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-project-slug/my-adapter", "messages": [{"role": "user", "content": "What is the capital of France?"}], "max_tokens": 128 }' | jq . ``` ```python Python theme={null} from together import Together client = Together(base_url="https://api-inference.together.ai") response = client.chat.completions.create( model="your-project-slug/my-adapter", messages=[{"role": "user", "content": "What is the capital of France?"}], max_tokens=128, ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together({ baseURL: 'https://api-inference.together.ai', }); const response = await client.chat.completions.create({ model: 'your-project-slug/my-adapter', messages: [{ role: 'user', content: 'What is the capital of France?' }], max_tokens: 128, }); console.log(response.choices[0].message.content); ``` ## Troubleshooting **"Model name already exists":** Each uploaded adapter needs a unique name. Adapter versioning isn't supported, so re-upload under a new name. **"Model not found" during upload:** Create the adapter record with `tg models create --type adapter`, then pass the returned `id` to the upload command. **Remote upload fails with `remote_url must be a Hugging Face repo (org/name or https://huggingface.co/org/name) or an https URL on Amazon S3, Google Cloud Storage, or Cloudflare R2`:** The `--from` source isn't one of the [accepted sources](#upload-from-hugging-face-or-cloud-storage). If you passed an `s3://bucket/key` path, pass a presigned `https://` URL for the same object instead. **`401` or `403` during upload:** For CLI uploads, run `tg whoami` to confirm you're logged in. For SDK uploads, confirm that `TOGETHER_API_KEY` is set. If your Together AI credentials are valid, check that your Hugging Face token has permission for private repos, or that your presigned URL is valid and hasn't expired. **Upload job stuck in `Processing`:** The job usually can't reach the source. For a presigned URL, confirm it hasn't expired. For Hugging Face, confirm your token has access to the repo. **Missing required files:** Confirm that both `adapter_config.json` and `adapter_model.safetensors` are at the root of your archive, or in the repo's **Files and versions** tab on Hugging Face. **Base model incompatibility:** Confirm that the base model you trained the adapter against is one of the [supported models](/docs/dedicated-endpoints/models) for dedicated model inference. **Adapter delete fails with `the model is referenced by a live deployment` (HTTP 400):** A deployment still references this adapter. [Stop the deployment](/docs/dedicated-endpoints/manage#stop-a-deployment), wait for `DEPLOYMENT_STATE_STOPPED`, [delete the deployment](/docs/dedicated-endpoints/manage#delete-resources), then delete the adapter with `tg models rm `. # Concepts Source: https://docs.together.ai/docs/dedicated-endpoints/concepts Understand the resource model and development workflow for dedicated model inference. Dedicated model inference (DMI) is built from a handful of resources: projects, models, configs, endpoints, deployments, and replicas. This page explains what each one is, how a request flows through them, and the workflow for deploying a model. ## Resource model There are six components involved in configuring dedicated model inference. At request time, the resources line up like this: ```mermaid theme={null} flowchart TB Client[Your application] -->|"  sends a request  "| Endpoint[Endpoint] Endpoint -->|"  routes traffic  "| DepA[Deployment A] Endpoint -->|"  routes traffic  "| DepB[Deployment B] DepA -->|"  scales  "| RA1[Replica] DepA -->|"  scales  "| RA2[Replica] DepB -->|"  scales  "| RB1[Replica] DepB -->|"  scales  "| RB2[Replica] RA1 -->|"  runs  "| Model[Model] classDef client fill:#b65a7c,stroke:#76374d,stroke-width:1.5px,color:#ffffff; classDef endpoint fill:#fc4c02,stroke:#b83702,stroke-width:1.5px,color:#ffffff; classDef deployment fill:#7f6caa,stroke:#50426e,stroke-width:1.5px,color:#ffffff; classDef replica fill:#cbd5e1,stroke:#64748b,stroke-width:1.5px,color:#132133; class Client client; class Endpoint endpoint; class DepA,DepB deployment; class RA1,RA2,RB1,RB2,Model replica; ``` ### Project Your organizational boundary. Every API key is scoped to a [project](/docs/projects), and every resource you create lives inside it. ### Model A concrete set of model weights (`ml_...`). A base model architecture can have several weights, one per quantization (for example, BF16 or FP8), and each is its own model resource. Together's [supported models](/docs/dedicated-endpoints/models) are visible from every project. When you [fine-tune a model](/docs/fine-tuning/overview) or [upload a fine-tuned model](/docs/dedicated-endpoints/custom-models), they are associated with your project. ### Config A *config* describes how a particular model weight runs: the inference engine, the parallelism and hardware (GPU type and count), and the optimization profile. It's tied to a specific weight, not to the architecture as a whole, so one weight can have more than one config. Together publishes certified configs, and you reference one by its config revision ID (`cr_...`). A config does not live inside your project. It's often part of a Together platform project rather than yours, so a config's resource path can name a different project than your deployment. List the configs for a weight with `tg models configs `. ### Deployment profile Each supported model on DMI is really a **model architecture** (for example, Llama 3.3 70B Instruct), served through a short hierarchy: * **Architecture:** The top-level entry in the [supported-models catalog](/docs/dedicated-endpoints/models). It's the model family you pick. * **Weight:** A concrete build of that architecture at one quantization (for example, BF16 or FP8). An architecture can have several weights, one per quantization. * **Config:** For a given weight, how it runs (parallelism, GPU type and count, optimization). A weight can have more than one config. A *deployment profile* is a published, certified combination that pins one weight to one config, so it fixes the quantization, parallelism, and hardware. It's the unit you select when you deploy from the catalog. Where a config is the low-level serving spec for one weight, a profile is the catalog-level pairing of a weight with a config. Each profile in the [supported-models catalog](/docs/dedicated-endpoints/models) surfaces its `quantization`, `parallelism`, `gpuType`, and `gpuCount`, along with the `config` (`cr_...`), `model` weight, and `modelName` (the model name you pass at deploy time). When an architecture has more than one profile, you pick one at deploy time by its `modelName` or by passing its config ID to `--config`. With a single profile, the CLI selects it automatically. ### Endpoint A logical grouping of deployments, and a stable inference URL for your application to call. Endpoints always live in your project, regardless of where the model or config came from. The *endpoint string* is what you pass as the `model` parameter when you call the [inference API](/docs/inference/overview#shared-inference-api). ### Deployment A *deployment* is what actually runs replicas and serves traffic. It binds a single model and a config to an endpoint with an autoscaling policy. One endpoint can host more than one deployment at the same time, and you split incoming traffic across them with [weights or A/B tests](#routing-traffic). ### Replica A *replica* is an instance of a model running on its own dedicated hardware. A replica handles requests in parallel with the other replicas in the same deployment. You can [configure autoscaling](/docs/dedicated-endpoints/scaling) to run more replicas on a deployment based on demand. ### Instance type An *instance type* is a deployable unit of GPU hardware, identified by a name like `1xnvidia-h100-80gb`. Each instance type has a [per-hour price](/docs/dedicated-endpoints/pricing) and a per-region capacity, and it is what you pay for while a replica runs. A deployment profile's hardware maps to an instance type. [Region availability](/docs/dedicated-endpoints/configs#instance-types-and-capacity) is reported as `headroom`: for each region, the API returns how many more replicas of an instance type currently fit. A headroom value of N with the `RELATION_GTE` relation means at least N units are free in that region, and the true number may be higher. Use it to pick a region with capacity before you deploy. ## Routing traffic After you create a deployment, you must [route traffic to it](/docs/dedicated-endpoints/route-traffic) before it can receive requests. The simplest routing method is to [assign weights](/docs/dedicated-endpoints/split-traffic) to each deployment. Each deployment's share of traffic is proportional to its capacity (its weight times its number of ready replicas), so traffic follows both the weights you assign and how each deployment is scaled. For more complex traffic routing patterns, you can: * [Run a rollout](/docs/dedicated-endpoints/rollouts): Move live traffic from one deployment to another in steps, without changing your endpoint URL. This is the safest way to migrate an endpoint to a new deployment. * [Run an A/B test](/docs/dedicated-endpoints/ab-tests): Set up a managed control/variant split with multiple candidates to compare deployments on live traffic. * [Run a shadow experiment](/docs/dedicated-endpoints/shadow-experiments): Copy a fraction of live traffic to a new deployment, comparing how responses differ while leaving the original deployment unaffected. No matter how you route traffic, your application always calls the same endpoint string. The endpoint routes each request to a deployment according to how you've configured the traffic split, and each deployment spreads its share of requests across its replicas. See [Route traffic](/docs/dedicated-endpoints/route-traffic#how-routing-works) for how the endpoint resolves each request through its routing stages and keeps routing sticky. ## Autoscaling Each deployment scales its replica count independently of other deployments, between a floor (`minReplicas`) and a ceiling (`maxReplicas`) that you set. The floor is how many replicas stay running at all times. The ceiling caps how far the deployment can scale up under load. See [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds) for how to set them. Running more replicas raises the requests-per-second a deployment can serve, lowering latency under high traffic and adding resiliency (if one replica fails, the others keep serving). The platform continuously adjusts the replica count to match load. It compares a [scaling metric](/docs/dedicated-endpoints/scaling#scaling-metrics) you choose against your target and computes how many replicas that implies. Timing windows let it scale up quickly and down slowly, and the result is clamped to your [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds). Each new observation feeds the next adjustment. ![The autoscaling decision loop. The scaling metric (for example inflight\_requests, observed 16 against a target of 8) sets desired replicas via ceil of replicas times observed over target (here, twice the current count). Timing windows react fast on the way up and slow on the way down, the result is clamped to the min and max replica bounds, and the difference is placed on GPUs. Observed load feeds back into the next evaluation.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/autoscaling-pipeline.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=31874b563b51d4b09b3009d1eb1cd3f3) Scaling down slowly is deliberate. On bursty traffic, tearing replicas down the moment load dips means the next burst pays for a fresh [cold start](#cold-starts). Holding them a little longer lets the deployment ride through the troughs. ![Two timelines comparing a short and a long scale-down window against the same bursty request load. With a short window, replicas drop back to the floor in every trough, so each new burst triggers a cold start. With a longer window, replicas hold above the floor through the troughs and absorb every burst without a cold start.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/scale-down-window-comparison.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=655d58bf943621a0ae6bd5efc9212af4) ## Cold starts A *cold start* is the delay before a newly started replica can serve its first request, while it loads the model weights, initializes the inference engine, and warms its cache. It scales with model size, so larger models take longer. A cold start happens whenever a stopped or scaled-to-zero deployment restarts, autoscaling adds a replica, or an unhealthy replica is replaced. To keep cold starts off latency-sensitive traffic, hold `minReplicas` at `1` or higher so at least one replica stays warm, and raise it ahead of a known spike (then lower it afterward). Stopping an idle deployment minimizes cost, but the first request afterward pays for a cold start. See [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds) for how to set these. ## Resource IDs Each resource has an ID and, in some cases, a human-readable name. You pass IDs to the management API, and the endpoint string (in the format `/`) as the `model` parameter when you call the [inference API](/docs/inference/overview#shared-inference-api). | Resource | ID format | Notes | | - | - | - | | Project | `proj_...` | Scoped to your API key. Retrieve it from the [settings page](https://api.together.ai/settings/organization/~current/projects) or with the [`whoami` endpoint](/reference/whoami). | | Model | `ml_...` | Supported models and your uploaded models both use this format. | | Config | `cr_...` | A config revision for a model. Configs are immutable. Each revision has a new ID. | | Endpoint | `ep_...` | The endpoint string used for inference requests is `/`. | | Deployment | `dep_...` | The deployment name used for management API requests is `//`. | | Rollout | `rol_...` | Tracks a [rollout](/docs/dedicated-endpoints/rollouts) that migrates traffic between two deployments on an endpoint. | The server prepends your project slug to names you choose. If you create an endpoint named `my-endpoint` in a project with slug `acme`, its endpoint string is `acme/my-endpoint`. That endpoint string is the value you send as `model` on inference requests. ## Typical workflow 1. [Select a model](/docs/dedicated-endpoints/models), and optionally [select a config](/docs/dedicated-endpoints/configs) for it. 2. Deploy it with `tg endpoints deploy`, which creates the endpoint, attaches a deployment, and routes traffic in one step. 3. [Send inference requests](/docs/dedicated-endpoints/quickstart#step-2-send-a-request), passing the endpoint string as the `model` parameter. You can also [run the endpoint, deployment, and traffic-routing steps individually](/docs/dedicated-endpoints/manage) from the CLI or the SDKs. [Follow the quickstart](/docs/dedicated-endpoints/quickstart) to walk through these steps end-to-end. ## Next steps > [card] [Quickstart](/docs/dedicated-endpoints/quickstart) > > Deploy your first endpoint and send a request. > [card] [Choose a deployment profile](/docs/dedicated-endpoints/configs) > > Find and select a published config for a model. > [card] [Create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment) > > Bind a model and config to an endpoint and split traffic. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Autoscale a deployment between replica bounds. # Choose a deployment profile Source: https://docs.together.ai/docs/dedicated-endpoints/configs Pick the hardware deployment profile that your model runs on. After [choosing](/docs/dedicated-endpoints/models) or [uploading](/docs/dedicated-endpoints/custom-models) a model, you choose a [deployment profile](/docs/dedicated-endpoints/concepts#deployment-profile): the certified pairing of a model weight (at a given quantization) with a [config](/docs/dedicated-endpoints/concepts#config) that fixes the quantization, parallelism, and hardware your deployment runs on. Together publishes one or more profiles per model. In the CLI and API, you select one by its config revision ID, passing it to `--config ` when you create a deployment. When a model has a single profile, the CLI selects it automatically. In the console, choose a **Deployment profiles** card on the [create form](/docs/dedicated-endpoints/manage#create-an-endpoint). Each card shows the profile's hardware and quantization. ## List a model's profiles Each profile is anchored by a config revision (`cr_...`). List the configs published for a model with the CLI, passing a model ID (`ml_...`) or a model name. For a public-catalog model, the [supported-models catalog](/docs/dedicated-endpoints/models#list-supported-models-programmatically) also shows each profile's quantization alongside its config: ```bash CLI theme={null} tg models configs ml_CbSJsoXB4sHXmSRLUm9es tg models configs Qwen/Qwen3.6-35B-A3B-FP8 ``` Response example: ```json theme={null} { "data": [ { "id": "", "referenceModel": "projects//models/ml_CbSJsoXB4sHXmSRLUm9es", "referenceModelId": "ml_CbSJsoXB4sHXmSRLUm9es", "projectId": "", "selectors": [ { "key": "accelerator_count", "value": "1" }, { "key": "accelerator_type", "value": "nvidia-b200-180gb" }, { "key": "optimization", "value": "balanced" }, { "key": "topology", "value": "aggregated" } ] } ], "object": "list" } ``` List and get responses return `referenceModel`, the model's resource name. The config `id` is a config revision in the format `cr_...`. Pass it as a resource name (`projects/{project_id}/configs/{config_revision_id}`) in the `config` field when you [create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment). Use the config's `projectId` from the list response for `{project_id}`. Use this command when you already have a model, including your own [uploaded fine-tuned models](/docs/dedicated-endpoints/custom-models), which aren't in the public catalog. To browse the public catalog and get certified model-and-config pairs in one call, [list supported models programmatically](/docs/dedicated-endpoints/models#list-supported-models-programmatically) instead. ## Selectors Every config carries a set of selectors that describe the hardware and serving setup: | Selector | Description | Example | | - | - | - | | `accelerator_type` | The GPU SKU the config targets. | `nvidia-b200-180gb` | | `accelerator_count` | Number of GPUs each replica uses. | `1`, `2`, `4`, `8` | | `optimization` | The serving profile. | `balanced`, `throughput`, `latency` | | `topology` | How the model is laid out across GPUs. | `aggregated` | | `adapter_mode` | Whether deployments on this profile serve attached low-rank adapters (LoRAs). See [multi-LoRA deployment](/docs/post-training/multi-lora-deployment). | `disabled`, `dynamic` | A model may have more than one published profile, for example a single-GPU profile and a multi-GPU profile at a higher price and throughput. ## Instance types and capacity A config's `accelerator_type` and `accelerator_count` selectors map to a deployable [instance type](/docs/dedicated-endpoints/concepts#instance-type), the unit of hardware you pay for while replicas run. For example, `accelerator_type: nvidia-b200-180gb` with `accelerator_count: 1` maps to the instance type `1xnvidia-b200-180gb`. To see an instance type's per-hour price and per-region capacity, query the public instance-types endpoint: ```bash Shell theme={null} curl -s -H "Authorization: Bearer $TOGETHER_API_KEY" \ https://api.together.ai/v2/public/inference-instance-types ``` Each instance type lists its `regions`, and each region reports `headroom`, a best-effort hint of how many more replicas of that instance type currently fit. A `headroom` value of N with the `RELATION_GTE` relation means at least N units are free in that region, and the true number may be higher. Use it to pick a region with capacity before you deploy. For the per-hour price of each instance type, see [Pricing](/docs/dedicated-endpoints/pricing#supported-hardware). ## Pick a profile To pick a profile, match it to your workload requirements: * **Single-GPU, balanced:** A good default for most models. Lowest cost per replica. * **Multi-GPU:** Higher throughput and lower latency for large models or heavy traffic, at a higher per-replica price. * **Latency-optimized:** When time to first token matters more than aggregate throughput. Quantization, hardware, and GPU count are set by the profile you choose, so they're fixed for the life of a deployment. To run a model on a different profile, [create a new deployment](/docs/dedicated-endpoints/manage#create-a-deployment) with a different config and [shift traffic](/docs/dedicated-endpoints/route-traffic) over to it. > [!NOTE] > > Configs are immutable. Together publishes new revisions over time, each with a new `cr_...` ID. A deployment pins the revision you selected, so its hardware and engine don't change underneath you. ## Decoding optimizations Decoding optimizations such as speculative decoding are defined in the config you select. The config's `optimization` selector (for example `balanced`, `throughput`, or `latency`) sets the serving profile, and configs that enable speculative decoding declare a draft model. When you [create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment), Together derives the speculator from the config's declared draft model and pins it at creation time. You cannot set a speculator on the deployment yourself. ### Speculative decoding Speculative decoding raises average throughput by predicting future tokens ahead of time. It usually improves performance, but it can introduce occasional tail-latency spikes that strict real-time workloads won't tolerate. If your workload is latency-sensitive, choose a config with a latency-oriented optimization profile. When a config declares a speculative-decoding draft, list and get responses include `draftModel`, the resource name of the draft model (`projects/{project_id}/models/{model_id}`). Configs without speculative decoding omit this field. ## Next steps > [card] [Create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment) > > Bind a model and config to an endpoint. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Choose replica bounds and an autoscaling metric. # Upload a fine-tuned model Source: https://docs.together.ai/docs/dedicated-endpoints/custom-models Serve a fine-tuned model uploaded from your machine, Hugging Face, or S3. Run inference on your own fine-tuned models by uploading them to Together AI and deploying them for [dedicated model inference](/docs/dedicated-endpoints/overview). You can upload models from your local machine, import them from Hugging Face Hub, or upload from an S3 archive. Uploads must be fine-tuned variants of a model architecture that Together AI already supports. You can change the weights, but the architecture must match [one of the supported models](/docs/dedicated-endpoints/models) we offer for dedicated inference. ## Requirements A model is eligible for upload if it meets these requirements: * **Source:** Your local machine, Hugging Face Hub, or an S3 presigned URL. * **Architecture:** A fine-tuned variant of a base model that Together AI [supports for dedicated inference](/docs/dedicated-endpoints/models). * **Type:** Text generation model. Meeting these requirements is necessary but not sufficient. Together AI does not accept every model: an unsupported base model, layer type, or adapter rank is rejected with an error identifying the problem at create or upload time. The model files must be in standard Hugging Face repository format, compatible with `from_pretrained`. A valid model directory contains files like: ``` config.json generation_config.json model-00001-of-00004.safetensors model-00002-of-00004.safetensors model-00003-of-00004.safetensors model-00004-of-00004.safetensors model.safetensors.index.json special_tokens_map.json tokenizer.json tokenizer_config.json ``` ### S3 archive requirements If you're uploading from S3, you must package the files in a single archive (`.zip` or `.tar.gz`) with the model files at the root of the archive. Don't nest them inside an extra top-level directory. **Correct:** The files are at the root of the archive. ``` config.json model.safetensors tokenizer.json ... ``` **Incorrect:** The files are nested inside an extra top-level directory. ``` my-model/ config.json model.safetensors tokenizer.json ... ``` To create the archive from within a model directory, run: ```bash Shell theme={null} cd /path/to/your/model tar -czvf ../model.tar.gz . ``` The presigned URL must point to the archive file in S3 and have an expiration of at least 100 minutes. ## Create the model Create the model record in your project before you upload its weights. Creating the record first gives you a model ID for the upload to attach its weights to. Every uploaded model must reference a [supported base model](/docs/dedicated-endpoints/models) via `baseModelId`. An upload can't introduce a new base architecture. Give the model a readable name (for example `gemma-4-31b-it`), rather than a Hugging Face repo ID. The base model is referenced by its `baseModelId` (`ml_...`). List the [supported models](/docs/dedicated-endpoints/models) with `tg models public --product dedicated` and copy the `baseModelId` of the architecture your fine-tune derives from (for example `ml_CbJNwQC2ZqCU2iFT3mrCh`), or pass a deployment profile's exact `modelName` (for example `Qwen/Qwen3.5-9B-FP8`). Don't use the architecture `id`, which starts with `arch_`: ```bash CLI theme={null} tg models create gemma-4-31b-it \ --base-model ml_CbJNwQC2ZqCU2iFT3mrCh ``` > [!NOTE] > > Uploaded models are Private by default, visible only in the project that owns them. Internal visibility makes a model discoverable from every project in your organization. On the [Models](https://api.together.ai/models) page, Internal models from other projects appear under **My models** alongside the selected project's own models. Use the **Visibility** filter (**Internal** or **Private**) to narrow the list. Checking both options matches either scope. Save the returned model `id` (for example `ml_abc123`). You pass this value to the upload command in the next step. Whether a record holds full weights or a low-rank adapter (LoRA) is fixed when you create it: `create` defaults `--type` to `model`, so a full model needs no type flag. To register a [LoRA adapter](/docs/dedicated-endpoints/adapter) instead, pass `--type adapter` on create. ### Create request fields | Field | Required | Description | | - | - | - | | `name` | Yes | Inference-addressable name for the uploaded model. | | `base_model_id` | Yes | `baseModelId` (`ml_...`) of the supported base model your weights derive from. | | `description` | No | Description shown in your project catalog. | ## Upload the model After creating the model record, upload its weights. Use a local upload when the files are on your machine, or a remote upload to stream them from Hugging Face or a presigned S3 URL. Pass the model `id` you saved in the previous step. ### Upload from your machine Point the CLI at your local model directory. The CLI handles the multipart upload for you: ```bash CLI theme={null} tg models upload ml_abc123 ./path/to/model-dir ``` ### Upload from Hugging Face or cloud storage A remote upload streams the weights server-side, so you don't download them locally first. Pass the source as `--from` (`remote_url` in the SDKs). The source must be one of: * A Hugging Face repo ID (`your-org/your-repo`), optionally pinned to a revision as `your-org/your-repo@revision`. * A Hugging Face repo URL (`https://huggingface.co/your-org/your-repo`). * A presigned `https://` URL on Amazon S3, Google Cloud Storage, or Cloudflare R2. Any other source, such as an `s3://` path, an `http://` URL, or an IP address, is rejected before the upload starts. For a gated or private Hugging Face repo, also pass a Hugging Face token with `--token`. A presigned URL needs no token: ```bash CLI theme={null} tg models remote-uploads create ml_abc123 \ --from https://huggingface.co/your-org/your-repo \ --token hf_your_token ``` The response is the upload job object, with `id`, `modelId`, and `status` at the top level: ```json theme={null} { "id": "job_abc123", "projectId": "proj_abc123", "modelId": "ml_abc123", "remoteUrl": "https://huggingface.co/your-org/your-repo", "status": "REMOTE_UPLOAD_STATUS_PENDING", "statusMessage": "", "restartCount": 0, "maxRestarts": 0, "createdAt": "2026-07-02T20:00:00Z", "updatedAt": "2026-07-02T20:00:00Z" } ``` Save the job `id`. You use it to poll for upload status. ### Upload from the console The console combines creating the model record and uploading its weights into a single form. [Upload a model](https://api.together.ai/models/upload) **1. Set the upload type** Leave **Upload type** set to **Full model**. **2. Choose the source** Under **Model source**, select **Import from Hugging Face** and enter the repo path or URL (add a **Hugging Face token** for gated or private repos), or select **Download from S3** and paste a presigned archive URL. **Upload from your machine** shows a CLI command instead: the browser can't upload local weights, so use [`tg models upload`](#upload-from-your-machine) for files on your machine. **3. Name and configure the model** Enter a **Model name**, choose a **Visibility**, and complete the **Compatible base model** and **Quantization** fields. **4. Import** Select **Import**. The upload runs server-side, with progress shown below the form. You can leave the form: the model appears under **My models** with an **Uploading** badge while the job is pending or running. ![The Upload model form in the Together AI console, set to Full model with Import from Hugging Face selected, showing fields for repository or URL, Hugging Face token, model name, visibility, compatible base model, and quantization.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/custom-models-upload-form.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=5a7656ead4d22854576e3388fe9a532e) ## Check upload status Poll the remote-upload job until `status` is `REMOTE_UPLOAD_STATUS_SUCCEEDED`. The model is ready to deploy at that point. ```bash CLI theme={null} # One upload job tg models remote-uploads retrieve job_abc123 # All upload jobs in the project tg models remote-uploads list ``` Once the job reaches `REMOTE_UPLOAD_STATUS_SUCCEEDED`, confirm the files landed: ```bash CLI theme={null} tg models ls-files ml_abc123 ``` [My models](https://api.together.ai/models?category=my-models) You can also track uploads on the **My models** page in the console. While a remote upload is pending or running, the model floats to the top of **My models** with an **Uploading** badge. Open the model to watch the live **Upload progress** event log on the model detail page. The revisions table appears after the upload finishes. That list also includes Internal-visibility models from other projects in your organization. Use the **Visibility** filter to show only **Internal** or only **Private** models. ## Check revision validation After files land, Together validates the revision's weights automatically. Validation checks that the weights are in safetensors format and that the config and architecture are compatible with the base model. A revision must reach `REVISION_VALIDATION_STATUS_SUCCESS` before you can deploy it when you pin that revision explicitly. List revisions for a model: ```bash CLI theme={null} tg models ls-revisions ml_abc123 ``` The list and retrieve revision APIs also return validation fields on each revision. Replace `$PROJECT_ID` with your project ID (`proj_...`): ```bash Shell theme={null} # All revisions curl -s -H "Authorization: Bearer $TOGETHER_API_KEY" \ "https://api.together.ai/v2/projects/$PROJECT_ID/models/ml_abc123/revisions" # One revision curl -s -H "Authorization: Bearer $TOGETHER_API_KEY" \ "https://api.together.ai/v2/projects/$PROJECT_ID/models/ml_abc123/revisions/rv_abc123" ``` Each revision in the response includes: ```json theme={null} { "data": [ { "revisionId": "rv_abc123", "createdAt": "2026-07-02T20:05:00Z", "validationStatus": "REVISION_VALIDATION_STATUS_SUCCESS", "lastValidatedAt": "2026-07-02T20:06:00Z", "validationErrors": [] } ], "object": "list" } ``` ### Revision validation fields | Field | Description | | - | - | | `validationStatus` | Validation state for this revision. See the table below. | | `lastValidatedAt` | When validation last ran for this revision. Omitted until validation has started. | | `validationErrors` | Errors from the last validation run. Empty when validation succeeded or is still pending. | ### `validationStatus` values | Value | Meaning | | - | - | | `REVISION_VALIDATION_STATUS_PENDING` | Validation is queued or running. Poll until the status changes. | | `REVISION_VALIDATION_STATUS_SUCCESS` | Weights validated successfully. The revision is ready to deploy. | | `REVISION_VALIDATION_STATUS_FAILED` | Validation failed. Read `validationErrors` for the cause. | | `REVISION_VALIDATION_STATUS_ERROR` | Validation could not complete due to an internal error. Retry later or contact support. | | `REVISION_VALIDATION_STATUS_UNSPECIFIED` | Validation has not started yet. | When validation fails, each entry in `validationErrors` includes `rule`, `severity`, and `message` describing what went wrong. Common causes include missing safetensors files, an invalid `config.json`, or weights that don't match the declared base model. > [!NOTE] > > Only safetensors format is supported. Models with only `.bin` or `.pt` files fail validation. ## Deploy the model Once the upload completes, your model has an ID (`ml_...`) in your project. Deploy it the same way as a base model. First, find its ID by listing the models in your project: ```bash CLI theme={null} tg models list ``` Then deploy it. The CLI's `deploy` command creates the endpoint, attaches a deployment bound to your uploaded model and a [config](/docs/dedicated-endpoints/configs), and routes all traffic to it in one step: ```bash CLI theme={null} tg endpoints deploy ml_abc123 \ --endpoint my-custom-model \ --config cr_CbzGdmn14t3HYrXXitmKa ``` Once the deployment is ready, [send a request](/docs/dedicated-endpoints/quickstart#step-2-send-a-request) to the endpoint string. See [Manage deployments](/docs/dedicated-endpoints/manage) for the individual lifecycle operations. If the model is a new version of one you're already serving, you can instead [create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment) for it under the existing endpoint and [run a rollout](/docs/dedicated-endpoints/rollouts) to move live traffic to it, without changing the endpoint URL your application calls. ## Troubleshooting **"Model not found" during upload:** Create the model record first with `tg models create`, and pass the returned `id` to the upload command. **Remote upload fails with `remote_url must be a Hugging Face repo (org/name or https://huggingface.co/org/name) or an https URL on Amazon S3, Google Cloud Storage, or Cloudflare R2`:** The `--from` source isn't one of the [accepted sources](#upload-from-hugging-face-or-cloud-storage). If you passed an `s3://bucket/key` path, pass a [presigned](#s3-archive-requirements) `https://` URL for the same object instead. **`base_model_id is required` on create:** Every uploaded model must reference a supported base model. List [supported models](/docs/dedicated-endpoints/models) and set `--base-model` to the matching `baseModelId` (`ml_...`), not the architecture `id` (`arch_...`). **`tokenizer.chat_template is not set` during chat inference:** The uploaded tokenizer doesn't define a chat template. Add a compatible `chat_template` to `tokenizer_config.json` before uploading, or use the text completions API with the prompt format expected by the model. **Model delete fails with `the model is referenced by a live deployment` (HTTP 400):** A deployment still references this model. [Stop the deployment](/docs/dedicated-endpoints/manage#stop-a-deployment), wait for `DEPLOYMENT_STATE_STOPPED`, [delete the deployment](/docs/dedicated-endpoints/manage#delete-resources), then delete the model with `tg models rm `. **Revision validation failed or still pending:** Check `validationStatus` on the revision with [Check revision validation](#check-revision-validation). Wait for `REVISION_VALIDATION_STATUS_SUCCESS` before you deploy a pinned revision. # Run your own Grafana Source: https://docs.together.ai/docs/dedicated-endpoints/grafana Scrape dedicated endpoint metrics into your own Prometheus and Grafana, import the prebuilt dashboard, and alert on errors. > [!NOTE] > > The metrics endpoint is in beta. The host and path are subject to change, and access may need to be enabled for your organization. Confirm availability with your Together AI contact before you build against it. Every project with an active deployment already has a [Grafana dashboard](/docs/dedicated-endpoints/monitoring#grafana-dashboard) that Together AI hosts and maintains. Run your own Grafana when you want to customize the dashboard, route alerts to your on-call tools, chart endpoints next to your application's metrics, or see every project in your organization in one place. In this tutorial, you'll run Prometheus and Grafana locally with Docker Compose, scrape the [Prometheus-compatible metrics endpoint](/docs/dedicated-endpoints/monitoring#prometheus-compatible-metrics-endpoint), import the same dashboard the hosted Grafana uses, and add an alert rule on the 5xx error ratio. > [!TIP] > > This tutorial uses Grafana, but any observability tool that ingests Prometheus metrics can scrape the same endpoint. For Datadog, use its [OpenMetrics integration](https://docs.datadoghq.com/integrations/openmetrics/). ![The Grafana dashboard for Together AI dedicated endpoints, showing request rate by status, 5xx error ratio, in-flight requests, and latency percentile panels, with Endpoint and Deployment filter variables at the top.](https://mintcdn.com/togetherai-52386018/FQfrqyqDpk0mNd0F/images/dedicated-endpoints/grafana-dashboard.png?fit=max\&auto=format\&n=FQfrqyqDpk0mNd0F\&q=85\&s=e5caf047c916139b7b00e10311635c16) ## Requirements * A [Together API key](https://api.together.ai/settings/api-keys) set as `TOGETHER_API_KEY` in your terminal. Prometheus and the `curl` commands authenticate with this key. * The [Together CLI](/docs/dedicated-endpoints/quickstart#requirements) installed and logged in with `tg login`. * [Docker](https://docs.docker.com/get-docker/) with the Compose plugin. * A dedicated endpoint serving traffic. The next section creates one if you don't have one already. ## Step 1: Deploy an endpoint and send traffic The dashboard only shows data for endpoints that are serving requests. If you already have a dedicated endpoint taking traffic, skip to [Find your organization ID](#step-2-find-your-organization-id). Deploy a small model on its default hardware: ```bash theme={null} tg endpoints deploy google/gemma-4-E4B-it \ --endpoint grafana-demo ``` Check its status with `tg endpoints get`, passing the deployment ID from the deploy output. Once the deployment reaches `DEPLOYMENT_STATE_READY`, send it a steady trickle of requests so every panel has data. Leave this loop running while you set up Grafana: ```bash theme={null} while true; do curl -s https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your_project_slug/grafana-demo", "messages": [{"role": "user", "content": "Write a haiku about dashboards."}], "stream": true }' > /dev/null sleep 5 done ``` Replace `your_project_slug/grafana-demo` with the endpoint string from the deploy output. Keep `"stream": true` in the request body, because the time-to-first-token panels only count streaming requests. See the [quickstart](/docs/dedicated-endpoints/quickstart) for the full deploy walkthrough. ## Step 2: Find your organization ID The metrics endpoint is scoped to your organization, so the scrape path needs your organization ID. Print it with the CLI: ```bash theme={null} tg whoami ``` ```text theme={null} Project: My Project (proj_abc123) Organization: My Organization (org_abc123) ``` Copy the `org_` value. Then confirm the metrics endpoint responds for your organization: ```bash theme={null} curl -H "Authorization: Bearer $TOGETHER_API_KEY" \ "https://o11y-de2-metrics.cloud.together.ai/organizations/org_abc123/metrics" ``` The response is a plain-text Prometheus exposition: `# TYPE` lines followed by series like `edge_inference_requests_total{endpoint_id="ep_...",status_code="200"}`. An empty response means no dedicated endpoint in the organization has served traffic recently. ## Step 3: Run Prometheus and Grafana Create a directory with three files: a Compose file, a Prometheus scrape config, and a Grafana data source definition. `docker-compose.yml` runs the two services: ```yaml docker-compose.yml theme={null} services: prometheus: image: prom/prometheus:latest volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml ports: - "9090:9090" grafana: image: grafana/grafana:latest volumes: - ./grafana-datasource.yml:/etc/grafana/provisioning/datasources/together.yml ports: - "3000:3000" depends_on: - prometheus ``` `prometheus.yml` scrapes the metrics endpoint once a minute. Fill in your API key and organization ID: ```yaml prometheus.yml theme={null} global: scrape_interval: 60s scrape_timeout: 55s scrape_configs: - job_name: together-endpoint-metrics scheme: https authorization: credentials: your_together_api_key metrics_path: /organizations/your_org_id/metrics static_configs: - targets: ["o11y-de2-metrics.cloud.together.ai"] ``` `grafana-datasource.yml` pre-configures Grafana with Prometheus as its data source, so the dashboard import can bind to it directly: ```yaml grafana-datasource.yml theme={null} apiVersion: 1 datasources: - name: Prometheus type: prometheus access: proxy url: http://prometheus:9090 isDefault: true jsonData: timeInterval: 60s ``` The `timeInterval` value must match the `scrape_interval` in `prometheus.yml`. Grafana uses it to size rate windows, and without it every rate and percentile panel on the dashboard stays empty because Grafana assumes the default 15-second scrape interval. Start the stack: ```bash theme={null} docker compose up -d ``` Open the Prometheus targets page at [http://localhost:9090/targets](http://localhost:9090/targets) and confirm the `together-endpoint-metrics` target reports **UP**. The target stays in an unknown state until the first scrape completes, usually within a minute. > [!WARNING] > > The scrape config contains your API key in plain text. Keep the directory out of version control, or move the key into a file referenced by `credentials_file` instead of `credentials`. ## Step 4: Import the dashboard Together AI publishes the dashboard in the [together-cookbook](https://github.com/togethercomputer/together-cookbook/tree/main/dedicated-endpoints/Grafana_Dedicated_Endpoints) repository. It requires Grafana 10.2 or later and works with any Prometheus data source, including the one you started in Step 3. 1. Download the dashboard JSON: ```bash theme={null} curl -O https://raw.githubusercontent.com/togethercomputer/together-cookbook/main/dedicated-endpoints/Grafana_Dedicated_Endpoints/together-dedicated-endpoints-dashboard.json ``` 2. Open Grafana at [http://localhost:3000](http://localhost:3000) and sign in. The default credentials are `admin` / `admin`. 3. Go to **Dashboards**, select **New**, then **Import dashboard**. 4. Upload `together-dedicated-endpoints-dashboard.json`, select the **Prometheus** data source when prompted, and select **Import**. The dashboard loads with the **Endpoint** and **Deployment** variables at the top set to **All**. Rate and percentile panels need at least two scrapes, so expect the dashboard to fill in over the first few minutes. See [Read the dashboard](/docs/dedicated-endpoints/monitoring#read-the-dashboard) for what each row shows. ## Step 5: Alert on errors Add an alert rule that fires when more than 5% of requests return a 5xx error for five minutes straight. Grafana alert rules can't use dashboard variables like `$endpoint`, so the rule restates the **Error ratio (5xx, edge)** panel's query without them. 1. Add a contact point, because a new Grafana instance has none that can deliver alerts. Go to **Alerting** > **Notification configuration**, select **New contact point**, and set it up for the channel you want alerts sent to, such as Slack, PagerDuty, or a webhook. 2. Go to **Alerting** > **Alert rules** and select **New alert rule**. 3. Name the rule, select the **Prometheus** data source, switch the query editor to **Code**, and enter: ```text theme={null} (sum(rate(edge_inference_requests_total{status_code=~"5.."}[5m])) or vector(0)) / sum(rate(edge_inference_requests_total[5m])) ``` 4. Set the alert condition to **Is above** `0.05`. 5. Create a folder with **New folder** and an evaluation group with **New evaluation group** (keep the default `1m` interval), then set **Pending period** to `5m`. 6. Under **Configure notifications**, select your contact point, then select **Save**. The rule covers every endpoint in your organization. To alert on one endpoint, add `endpoint_id="ep_abc123"` to both selectors in the query. > [!TIP] > > Congrats! Your dedicated endpoint metrics now flow into your own Grafana, with an alert on errors. ## Clean up Stop the traffic loop with `Ctrl+C`, then shut down Prometheus and Grafana from the directory that holds `docker-compose.yml`: ```bash theme={null} docker compose down ``` If you deployed `grafana-demo` in Step 1, delete it to stop billing. Pass the endpoint ID from the deploy output: ```bash theme={null} tg endpoints rm ep_abc123 --force ``` ## Use Grafana Cloud The same dashboard works in Grafana Cloud or any other Grafana instance you run. Point a Prometheus-compatible collector, such as Grafana Alloy or a Prometheus instance with `remote_write`, at the metrics endpoint with the same scheme, path, and bearer credentials as the `prometheus.yml` from Step 3, then import the dashboard JSON against the data source that collector writes to. ## Troubleshooting * **The Prometheus target shows a timeout or context deadline error:** Organizations with many endpoints can take longer than the default timeout to scrape. Raise `scrape_interval` and `scrape_timeout` together, for example to `120s` and `115s`. * **The scrape returns 401:** The API key must belong to the organization in the scrape path. Run `tg whoami --api-key "$TOGETHER_API_KEY"` to see the key's organization. Without `--api-key`, a logged-in CLI reports the organization of your `tg login` session instead. * **Panels are empty:** Confirm the endpoint is serving requests, the Prometheus target is **UP**, and the dashboard time range covers the last few minutes. Rate panels stay empty until two scrapes have completed. * **Time-to-first-token panels are empty but others populate:** The edge TTFT panel only counts streaming requests. Send requests with `"stream": true`. * **The Router TTFT panel is empty:** This series depends on a newer router build. The panel fills in as the rollout completes, and the worker TTFT panel covers the same question in the meantime. ## Next steps > [card] [Metrics and dashboards](/docs/dedicated-endpoints/monitoring) > > Find the hosted Grafana dashboard and the full metric and label tables. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Act on what the dashboard shows by tuning replica scaling. # Manage endpoints and deployments Source: https://docs.together.ai/docs/dedicated-endpoints/manage Create, update, and delete resources for dedicated model inference. This page covers the lifecycle operations for dedicated model inference (DMI): creating endpoints and deployments, scaling, stopping, and deleting resources. The CLI's `tg endpoints deploy` command bundles several API/SDK operations into one step for convenience: it creates the endpoint (when you pass a new endpoint name), attaches a deployment to it, and routes 100% of traffic to that deployment. The sections below show the individual operations underneath it. To create your first deployment end-to-end, [follow the quickstart](/docs/dedicated-endpoints/quickstart). You can run every operation on this page from the Together CLI and SDK or from the [web console](https://api.together.ai/endpoints). Each section below shows both: the CLI or SDK command, and the equivalent steps in the console. ## Create an endpoint When you deploy a model to a new endpoint, Together creates the endpoint, attaches the deployment, and routes all traffic to it. (To create an endpoint resource with no deployments, use the [SDK or API](/reference/dmi/endpoints-create).) Before you deploy, choose a [supported model](/docs/dedicated-endpoints/models) and a [deployment profile](/docs/dedicated-endpoints/configs). > [tab] CLI > > Pass a model and a new endpoint name to `tg endpoints deploy`. It creates the endpoint, attaches a deployment on the model's default hardware, and routes 100% of traffic to it: > > ```bash CLI theme={null} > tg endpoints deploy google/gemma-4-E4B-it \ > --endpoint my-endpoint > ``` > > Add `--config ` when the model has more than one deployment profile, and `--min-replicas` / `--max-replicas` to set the [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds). > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > **1. Open the create form** > > On the **Endpoints** page, select **New endpoint**. > > **2. Name the endpoint and deployment** > > Enter an **Endpoint name** and a **Deployment name**. > > **3. Choose the model and deployment profile** > > Select the **Model**. For a project or organization model, choose a **Revision**, then pick a **Deployment profiles** card and a **Region**. Each [deployment profile](/docs/dedicated-endpoints/concepts#deployment-profile) bundles the model's hardware, quantization, and speculative decoding when the config enables it. For project and organization models, the console offers every certified config with known hardware. Supported catalog models still require a profile-certified or org-runtime-certified config. > > **4. Set autoscaling** > > Set **Min replicas** and **Max replicas** (both default to `1`). > > **5. Create the endpoint** > > Select **Create endpoint**. Together creates the endpoint and its first deployment and routes all traffic to it. The endpoint serves as a logical grouping of deployments, and the entry point for [routing traffic to your models](/docs/dedicated-endpoints/route-traffic). ## Create a deployment Add more deployments to an endpoint to run several models or hardware configs behind it, for [traffic splitting](/docs/dedicated-endpoints/split-traffic), [A/B tests](/docs/dedicated-endpoints/ab-tests), or [shadow experiments](/docs/dedicated-endpoints/shadow-experiments). It works like [creating an endpoint](#create-an-endpoint), except you target an existing endpoint and give the deployment a traffic weight so it takes a share of the [traffic split](/docs/dedicated-endpoints/route-traffic). > [tab] CLI > > Pass an existing endpoint ID (or a new endpoint name) to `tg endpoints deploy --endpoint` to add a deployment. The model is the positional argument, and the config is `--config`: > > ```bash CLI theme={null} > tg endpoints deploy ml_CbJNwQC2ZqCU2iFT3mrCh \ > --endpoint ep_abc123 \ > --deployment-name my-deployment \ > --config cr_CbzGdmn14t3HYrXXitmKa \ > --min-replicas 1 --max-replicas 2 > ``` > > When a model has more than one [deployment profile](/docs/dedicated-endpoints/concepts#deployment-profile), `deploy` returns an error that lists the available profiles, for example: > > ```text theme={null} > Model has multiple deployment profiles. Re-run with --config : > cr_CbzGdmn14t3HYrXXitmKa NVIDIA-H100 x1 BF16 TP1 > cr_CciJqTB35QmpMupbQNPPW NVIDIA-H100 x1 FP8 TP1 > ``` > > Re-run with `--config ` to choose one. When a model has a single profile, the CLI selects it automatically. List a model's profiles anytime with `tg models configs `. > > The CLI defaults `--min-replicas` and `--max-replicas` to `1`, so a bare `deploy` creates a single-replica deployment. If you pass only `--min-replicas`, the max matches it. `--min-replicas 0` alone creates the deployment stopped. > > For the full flag list, including placement, the autoscaling windows, and the scaling percentile, see the [CLI reference](/reference/cli/endpoints#deploy). > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open the endpoint and select **New deployment**. The dialog has the same fields as the create form ([Create an endpoint](#create-an-endpoint)), plus a **Traffic weight**: leave it at `0` to add the deployment without serving live traffic (for example, as an [A/B](/docs/dedicated-endpoints/ab-tests) variant). Fill in the fields and select **Create deployment**. While a [rollout](/docs/dedicated-endpoints/rollouts) is active (including pending or paused), **Traffic weight** is disabled so the rollout keeps ownership of the split. > > ![The New deployment dialog in the Together AI console, with fields for deployment name, model, deployment profiles, region, autoscaling replica bounds, and traffic weight.](https://mintcdn.com/togetherai-52386018/wiTeh4I8I-you2HE/images/dedicated-endpoints/manage-new-deployment.png?fit=max\&auto=format\&n=wiTeh4I8I-you2HE\&q=85\&s=f6f1b16977261c785d59dcb5b38cf15c) After you've created a deployment, you'll need to [route traffic](/docs/dedicated-endpoints/route-traffic) to it before it can serve requests. ### Choose where a deployment runs Placement controls which regions a deployment runs in. You can't change placement on an existing deployment, so set it when you deploy. You have two options: * **Attach a placement profile:** Pass `--placement ` with a placement profile ID. A *placement profile* is a reusable, Together-managed list of preferred regions that you attach instead of repeating the same region list on every deploy. * **Set placement inline:** Pass `--placement.regions` with a comma-separated list of regions, and `--placement.constraint` (`required` or `preferred`) to set how strictly Together enforces the list. Placement profiles are read-only. To list the profiles available to your project, with their IDs and preferred regions, use the [placement profiles API](/reference/dmi/placement-profiles-list). Each inline region is either an exact region name, such as `us-east-1`, or a prefix pattern of the form `-*` or `--*`, such as `us-*` or `us-east-*`. A pattern covers every region under it, including regions added later. The regions you can pass depend on the clusters available to your project, so a profile's preferred regions are a useful reference for valid region names. When you list two or more regions or use a pattern, the scheduler tries to spread replicas across the matching regions to improve availability. With the `required` constraint, if a pattern matches no available cluster, the deployment stays unscheduled. For example, this deployment runs only in regions that match `us-*`. Quote patterns so your shell doesn't expand the `*`: ```bash CLI theme={null} tg endpoints deploy zai-org/GLM-5.2 \ --endpoint us-only \ --placement.regions "us-*" \ --placement.constraint required ``` ## Poll deployment status > [tab] CLI > > To check a deployment's status, run `tg endpoints get` on its endpoint name or ID. The output lists up to the 10 newest deployments' `state` and ready/desired replica counts, so re-run it to watch a specific deployment come up: > > ```bash CLI theme={null} > # Show the endpoint with each deployment's state and replica counts > tg endpoints get my-endpoint > tg endpoints get ep_abc123 > ``` > > For the full set of status fields (scheduled replicas, status message), run `get` on the deployment itself with `--json` and read `status`: > > ```bash CLI theme={null} > tg endpoints get dep_abc123 --json > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint, then open the deployment from the endpoint's **Overview** tab to watch its status live. The **Status** card shows the current state (for example, Ready), the ready and scheduled replica counts, the region, **Estimated cost** (the hourly hardware rate times ready replicas), and a status message. The **Replicas** chart plots desired versus ready replicas over time. > > ![A deployment detail page in the Together AI console, showing the Model, Hardware and placement, Status, and Deployment configuration cards, a replica-count chart, and the deployment's logs. The Status card lists ready and scheduled replicas, region, estimated cost, and a status message.](https://mintcdn.com/togetherai-52386018/JlrVHiKFh6zHSJXu/images/dedicated-endpoints/manage-deployment-detail.png?fit=max\&auto=format\&n=JlrVHiKFh6zHSJXu\&q=85\&s=6b5981b68772cd91234ffe6cdf2887e0) The status object exposes these fields: | Field | Description | | - | - | | `desiredReplicas` | Target replica count from autoscaling. | | `status.scheduledReplicas` | Replicas the scheduler has placed on clusters. May trail `desiredReplicas` while capacity is still being found, and exceed `status.readyReplicas` while placed replicas start. | | `status.readyReplicas` | Replicas actively serving traffic. | | `status.message` | Human-readable explanation of the current stage or cause. Replica progress lives in the counts above, not in this string. | | `status.state` | [See below](#deployment-states). | ### Deployment states A deployment reports its lifecycle in `status.state`. The API returns the fully-qualified enum (for example `DEPLOYMENT_STATE_READY`). This page uses the short name for readability. | State | Description | | - | - | | **`PROVISIONING`** | The scheduler is placing replicas on clusters. `status.message` is `Scheduling replicas`. | | **`SCALING`** | Replicas are starting or draining to reach the desired count. `status.message` is `Starting replicas` or `Scaling down`. | | **`READY`** | All replicas are healthy and serving. `status.message` is `All replicas ready`. A deployment must also be in the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic) to receive requests. | | **`DEGRADED`** | The deployment is below the requested capacity or blocked by a transient issue. `status.message` explains the cause. It usually resolves on its own. | | **`STOPPING`** | A transient teardown state. Replicas are draining after a stop was requested. It settles to `STOPPED` once cleanup completes, or to `FAILED` if teardown ends with a failure. | | **`STOPPED`** | Scaled to zero replicas. The deployment isn't billing and isn't serving. | | **`FAILED`** | Terminal state. The `status.message` field explains why. | A deployment that never reaches `READY` within six hours after starting will be marked as `FAILED`. ## Scale a deployment Deployment scale is controlled by the deployment's [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds), and optionally autoscaled using [scaling metrics](/docs/dedicated-endpoints/scaling#scaling-metrics). Set the initial bounds when you create the deployment, then change them on a running deployment. > [tab] CLI > > ```bash CLI theme={null} > tg endpoints update dep_abc123 --min-replicas 2 --max-replicas 4 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > On the deployment's detail page, select **Edit** on the **Deployment configuration** card. Change **Min replicas** and **Max replicas** (and, optionally, the **Scaling metric** or **Traffic weight**), then select **Save changes**. The console applies the change in place, without restarting the deployment or creating a new one. While a [rollout](/docs/dedicated-endpoints/rollouts) is active (including pending or paused), **Traffic weight** is disabled. Complete or cancel the rollout before editing weights manually. > > ![The Edit configuration dialog in the Together AI console, with inputs for min and max replicas, scale-up and scale-down windows, traffic weight, and a scaling-metric target.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/manage-edit-deployment-config.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=a04b7b2229b730fb589f848e4475ddc4) ## Stop a deployment A deployment runs until you stop it. Stopping scales it to zero replicas and releases its hardware, but retains the deployment so you can [restart it](#restart-a-deployment) later. To stop a deployment automatically when it goes unused, set an [inactivity timeout](/docs/dedicated-endpoints/scaling#automatic-idle-shutdown) instead. > [tab] CLI > > Pass both `--min-replicas 0` and `--max-replicas 0`. The CLI rejects a stop request that sets only one bound to zero: > > ```bash CLI theme={null} > tg endpoints update dep_abc123 --min-replicas 0 --max-replicas 0 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > On the deployment's detail page, select **Stop deployment**, then select **Stop deployment** again in the confirmation dialog. If the deployment is receiving traffic, stopping it cuts off live requests, so the dialog keeps the button disabled until you enter `I understand`. > > To stop every active deployment on an endpoint, open the endpoint and select **Stop all deployments**. Select **Stop deployments** in the confirmation dialog. If any of those deployments is receiving traffic, the dialog asks you to enter `I understand` first. > > While the endpoint has an active [rollout](/docs/dedicated-endpoints/rollouts), the console disables **Stop deployment** on all of its deployments and **Stop all deployments** on the endpoint. Complete or cancel the rollout first. The replicas keep serving until they finish draining, then the deployment moves to `DEPLOYMENT_STATE_STOPPED` and billing stops. ## Restart a deployment A stopped deployment doesn't restart on its own. Only deployments in `DEPLOYMENT_STATE_STOPPED` can be restarted. A deployment in `FAILED` is terminal and can't be brought back this way. [Deploy a new deployment](#create-a-deployment) instead. To restart a stopped deployment, raise both bounds to `1` or more. > [tab] CLI > > ```bash CLI theme={null} > tg endpoints update dep_abc123 --min-replicas 1 --max-replicas 2 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > On the deployment's detail page, select **Start**, then confirm the **Min replicas** and **Max replicas** to bring it back with. ## List resources > [tab] CLI > > List and get endpoints with the CLI: > > ```bash CLI theme={null} > # All endpoints in the project > tg endpoints ls > > # One endpoint by name or ID (includes up to the 10 newest deployments' state and replica counts) > tg endpoints get my-endpoint > tg endpoints get ep_abc123 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > The **Endpoints** page lists every endpoint in the current project with its status, model, GPU, and ready/desired replica counts, plus a **Traffic** column with the estimated percentage of the endpoint's traffic each deployment currently receives. Single-deployment endpoints collapse into one row. Endpoints with more than one deployment expand to show each deployment. > > ![The Endpoints list in the Together AI console, with columns for name, status, model, GPU, replicas, traffic, and created date. A single-deployment endpoint fills one row, and an endpoint with two deployments is expanded to show each one.](https://mintcdn.com/togetherai-52386018/JlrVHiKFh6zHSJXu/images/dedicated-endpoints/manage-endpoints-list.png?fit=max\&auto=format\&n=JlrVHiKFh6zHSJXu\&q=85\&s=d84e06e2b1e76c6559c6eb9f1e2b2349) > > Select an endpoint to open its detail page. The **Overview** tab opens with a status card for the endpoint's serving state (live, starting, or offline), lists its deployments with the same **Traffic** column, and shows the endpoint's details and a ready-to-run code sample. When the endpoint is live and serving traffic, the status card shows the traffic split and an **Edit traffic weights** action. > > ![An endpoint detail page in the Together AI console, showing the Overview, Rollouts, Traffic Tests, Analytics, and Logs tabs, a live status card with the traffic split, a deployments table with a Traffic column, a code sample, and the endpoint's details.](https://mintcdn.com/togetherai-52386018/JlrVHiKFh6zHSJXu/images/dedicated-endpoints/manage-endpoint-detail.png?fit=max\&auto=format\&n=JlrVHiKFh6zHSJXu\&q=85\&s=7aa6c9e72d77ba9f8a124d45eaa5915f) Endpoint get and list responses embed lightweight deployment summaries in each endpoint's `deployments` array. The array includes at most the 10 newest deployments per endpoint (ordered by `createdAt`, descending). To list every deployment on an endpoint, use the [SDK or API](/reference/dmi/deployments-list). Same-project get, update, and list responses also include `activeRolloutId` when a [rollout](/docs/dedicated-endpoints/rollouts) is in flight (including paused). The field is omitted when there is no active rollout, on cross-project reads, and in organization or public catalog lists. ### List flags `tg endpoints ls` accepts these flags: | Flag | Description | | - | - | | `--limit` | Maximum number of endpoints to return. | | `--after` | Pagination cursor to start from. | | `--org` | List org-scoped endpoints instead of project-scoped ones. | | `--public` | List public endpoints. | List responses are paginated: when more results are available, the response includes `next_cursor`, which you pass as `--after` on the next request. ## Delete resources Deletion is permanent. A deployment must be stopped before it can be deleted. Follow this order: 1. [Scale the deployment to zero](#stop-a-deployment) and wait for `DEPLOYMENT_STATE_STOPPED`. 2. Delete the deployment. If you use the SDK or API (not the CLI), set the deployment's [traffic split](/docs/dedicated-endpoints/route-traffic) weight to 0 on the endpoint first. 3. Delete the endpoint once it has no deployments. > [tab] CLI > > The CLI's `rm` command is a smart-delete: it resolves the resource by its ID prefix, so the same command deletes an endpoint (`ep_`), a deployment (`dep_`), an A/B experiment (`abx_`), a shadow experiment (`exp_`), or a rollout (`rol_`). When you run `tg endpoints rm dep_...`, the CLI automatically detaches the deployment from the traffic split and from any experiments it belongs to: > > ```bash CLI theme={null} > # Delete the deployment (must be stopped first; auto-detaches from the traffic split) > tg endpoints rm dep_abc123 > > # Delete the endpoint once it has no deployments > tg endpoints rm ep_abc123 > ``` > > To delete an endpoint that still has deployments, pass `--force` to `rm`. If the endpoint has other deployments you want to keep, [rebalance the remaining weights](/docs/dedicated-endpoints/route-traffic) instead of clearing the split. > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > First [stop](#stop-a-deployment) every deployment under the endpoint. Then open the endpoint, select **Endpoint actions**, and select **Delete endpoint**. The console keeps **Delete endpoint** disabled until every deployment is stopped or deleted, so there's no console equivalent of the CLI's `rm --force` on a running endpoint. > > ![The Endpoint actions menu open in the Together AI console, with a Delete endpoint item that is disabled while a deployment is still running.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/manage-endpoint-actions.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=c8b5f88a7189762a4bda2d919d8e3195) ## Troubleshooting * **`unknown field "..."` (HTTP 400) on a management API request:** The JSON body or query string includes a key the API does not define. Remove the named field (including retired keys such as `inactive_timeout`) and retry. Known fields accept both camelCase and snake\_case spellings. * **`endpoint_not_configured` (HTTP 400) though the deployment is `READY`:** Confirm the deployment is in the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic) with a non-zero weight. * **Deployment `DEGRADED` with `Cannot place replicas: insufficient GPU capacity`:** Hardware for the config is constrained, so the scheduler couldn't place all replicas yet. Compare `status.scheduledReplicas` to `desiredReplicas`. The scheduler keeps retrying and the deployment starts once capacity frees up. To improve the chance of placement, request fewer replicas or choose a config with a smaller hardware footprint. * **Deployment `DEGRADED` with `Startup stalled` or `Not ready`:** A placed replica is still booting or hit a startup failure. Read the detail after the colon in `status.message`. The deployment stays `DEGRADED` rather than `FAILED` once any replica has been successfully started. * **Deployment `FAILED` with `Timed out waiting for readiness`:** No replica could be provisioned within six hours of the current run's start. Read the stall cause at the end of `status.message`. [Deploy a new deployment](#create-a-deployment) to try again with a fresh readiness budget. * **Restart fails with `the deployment is in a terminal FAILED state and cannot be restarted; create a new deployment` (HTTP 400):** A `FAILED` deployment can't be brought back by raising replica bounds. [Deploy a new deployment](#create-a-deployment) on the endpoint instead. * **Restart fails with `the deployment must be stopped before it can be restarted` (HTTP 400):** Wait for the deployment to reach `DEPLOYMENT_STATE_STOPPED` after you [stop it](#stop-a-deployment), or confirm both replica bounds are `0`, before raising them again. * **Deployment `FAILED` for another reason:** Read `status.message`. Common causes include deterministic placement rejection (`Cannot place replicas: …`), manifest generation failure, or remediation exhaustion. * **Model not supported:** Not every model can be deployed. See the [model catalog](/docs/dedicated-endpoints/models). A fine-tuned model deploys only if its base model is supported. * **Deploy fails with `the model has no revisions to deploy`:** The model record exists but has no uploaded weights yet. Finish [uploading the model](/docs/dedicated-endpoints/custom-models#upload-the-model) and wait for the upload to succeed before you deploy it. * **Deploy fails with a revision validation error:** When you pin a specific model or speculator revision, that revision must have passed validation first. Check `validationStatus` on the revision ([custom models](/docs/dedicated-endpoints/custom-models#check-revision-validation), [adapters](/docs/dedicated-endpoints/adapter#check-revision-validation)). Deploy the latest validated revision, or wait for the pinned revision to finish validating. * **Deploy or update fails with `GPU quota exceeded` (HTTP 429):** The request would put your project or organization over its per-GPU-type quota. The error message names the GPU type and the would-be total against the limit (for example, `this deployment would put your project at 116 of 100 H100 GPUs`). Lower the requested replica count, stop unused deployments on that GPU type, or [contact support](https://portal.usepylon.com/together-ai/forms/support-request) to raise the limit. When the platform itself is out of capacity for a GPU type (`GPU quota exceeded for H100`), retry later or contact support to request capacity. * **Deployment delete fails with `the deployment stands in an endpoint's traffic split and cannot be deleted; remove it from the traffic split (it may be standing at weight 0), then delete` (HTTP 400):** The deployment is still a member of the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic), including after a completed [rollout](/docs/dedicated-endpoints/rollouts) that left the drained source at weight `0`. Remove it from the split before deleting. The CLI's `tg endpoints rm dep_...` detaches it automatically. * **Deployment delete fails with `the deployment is an A/B experiment member; remove it from the experiment first` (HTTP 400):** The deployment is still a control or variant in an [A/B test](/docs/dedicated-endpoints/ab-tests). Remove it from the test (or delete the test) before deleting the deployment. The CLI's `tg endpoints rm dep_...` detaches it automatically. * **Stop or delete is disabled on a deployment in the console:** The deployment is the source or target of an active [rollout](/docs/dedicated-endpoints/rollouts). Complete or cancel the rollout first. ## Next steps > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Autoscale a deployment on the right metric. > [card] [Route traffic](/docs/dedicated-endpoints/route-traffic) > > Split traffic across deployments behind one endpoint. > [card] [Observability](/docs/dedicated-endpoints/monitoring) > > Monitor metrics and scrape the Prometheus-compatible endpoint. > [card] [Pricing](/docs/dedicated-endpoints/pricing) > > Understand per-minute and reserved pricing. # Migrate from v1 Source: https://docs.together.ai/docs/dedicated-endpoints/migrate-from-v1 Move a dedicated endpoint from the v1 API to the v2 dedicated model inference resource model. This guide helps you move endpoints from the v1 dedicated endpoints API to dedicated model inference (v2). It explains what stays the same, what changed, and how to recreate a v1 endpoint under the [v2 resource model](/docs/dedicated-endpoints/concepts). > [!WARNING] > > You can no longer create a v1 endpoint or restart a stopped or paused one. To create a new endpoint or bring a stopped v1 endpoint back online, [deploy the model on v2](#migrate-an-endpoint). > > Creating or restarting a v1 endpoint fails with `endpoints_v1_create_access_disabled` (HTTP 403) in the API (`POST /v1/endpoints`), SDK versions before 3.0 (`client.endpoints.create(...)`), and the Together AI console. Together CLI 2.x (`tg endpoints create`) gets the same 403 but reports it as a permissions error. For these errors and related symptoms, see [Troubleshooting](#troubleshooting). Endpoints already running on v1 keep serving and stay supported until further notice, so you can migrate them on your own schedule. Migrating also unlocks [v2-only capabilities](#v2-capabilities) such as traffic splitting, A/B tests, shadow experiments, metric-based autoscaling, and monitoring dashboards. ## What stays the same The inference API hasn't changed. You still send requests to `POST /v1/chat/completions` (and the other inference endpoints) with your endpoint name in the `model` field. Dedicated model inference is served at `https://api-inference.together.ai`: ```bash theme={null} curl -s -X POST https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-project-slug/my-endpoint", "messages": [{"role": "user", "content": "Hello!"}] }' ``` The same applies to [billing](/docs/dedicated-endpoints/pricing): dedicated model inference still bills per minute per running replica by hardware. The main thing you'll need to change in your application is the `model` string. When you recreate an endpoint in v2, it gets a new endpoint string (`/`), so update your inference calls to use the new name. ## What's changed v1 modeled a dedicated endpoint as a single model running on a hardware type. v2 splits that into a small [resource model](/docs/dedicated-endpoints/concepts) so one endpoint can host more than one model version and shift traffic between them: * **Endpoint:** A stable inference URL. It no longer carries the model or hardware itself. * **Deployment:** Binds a model and a config to an endpoint with an [autoscaling policy](/docs/dedicated-endpoints/scaling). A deployment is what runs replicas and serves traffic. One endpoint can host several deployments at once. * **Config:** Describes how a model runs, including the hardware selectors and optimization profile. In v1 you passed a hardware ID and decoding flags. In v2 you select a [published config](/docs/dedicated-endpoints/configs) instead. * **Traffic split:** Routes requests across an endpoint's deployments by weight. Even if it's `READY`, a deployment receives no traffic until you [route traffic](/docs/dedicated-endpoints/route-traffic) to it. ## Feature mapping | v1 | v2 | Notes | | - | - | - | | One model per endpoint. | Endpoint plus one or more deployments. | The endpoint is now only a stable URL. The deployment runs the model. | | `--hardware ` | A published config (`cr_...`). | Hardware is chosen through a config's selectors, not a hardware ID flag. See [Choose a config](/docs/dedicated-endpoints/configs). | | `--min-replicas` / `--max-replicas` on the endpoint | `--min-replicas` / `--max-replicas` on the deployment. | Autoscaling is a property of the deployment. On a running deployment `min-replicas` is at least `1`. | | `--inactive-timeout ` on the endpoint | `--inactive-timeout ` on the deployment. | Off unless you set it (v1 defaulted to 60). Accepts `30` to `1440` minutes. See [Automatic idle shutdown](/docs/dedicated-endpoints/scaling#automatic-idle-shutdown). | | `--no-speculative-decoding` and other decoding flags. | Config optimization profile. | Decoding optimizations are properties of the [config you select](/docs/dedicated-endpoints/configs#decoding-optimizations), not per-endpoint flags. | | `--availability-zone` | No direct equivalent yet. | Contact support if you have a specific zone requirement. | | Custom model upload. | Fine-tuned model upload. | Uploads are restricted to fine-tuned variants of the supported models. See [Upload a fine-tuned model](/docs/dedicated-endpoints/custom-models). | | Low-rank adapter (LoRA) deployment. | Adapter upload, then a deployment per adapter. | Upload the adapter and deploy it like any other model. See [Upload a LoRA adapter](/docs/dedicated-endpoints/adapter). | | `tg endpoints adapters add` (several adapters on one endpoint). | Adapters attached to a deployment of their base model. | Available for adapters from post-training on [supported base models](/docs/post-training/multi-lora-deployment#supported-models). Deploy other adapters one per deployment. | ## Command mapping In Together CLI 2.x and SDK versions before 3.0, the `tg endpoints` commands and `client.endpoints` methods call the v1 API. In v2, the same operations are available from the `tg endpoints` and `tg models` commands of Together CLI 3.0 and from the `/v2` management API at `https://api.together.ai`. A few operations, such as editing a traffic split and listing deployments, are available from the SDK and API, not the CLI. The following table maps each v1 command to its v2 equivalent: | v1 operation (CLI 2.x) | v2 equivalent (CLI 3.0) | | - | - | | `tg endpoints hardware --model ` | `tg models configs ` (configs encode the hardware). | | `tg endpoints create --model --hardware ` | `tg endpoints deploy --endpoint [--config ]` (creates the endpoint, deployment, and traffic split in one step). | | `tg endpoints update --min-replicas --max-replicas ` | `tg endpoints update --min-replicas --max-replicas ` (pass the deployment ID, and the CLI resolves the endpoint). | | `tg endpoints stop ` | `tg endpoints update --min-replicas 0 --max-replicas 0` (scales the deployment to `0/0`). | | `tg endpoints start ` | `tg endpoints update --min-replicas 1 --max-replicas ` (raises both bounds to `1` or more). | | `tg endpoints list` / `retrieve ` | `tg endpoints ls` and `tg endpoints get `. List deployments from the SDK or API. | | `tg endpoints delete ` | Stop the deployment, then smart-delete with `tg endpoints rm ` and `tg endpoints rm `. See [Delete resources](/docs/dedicated-endpoints/manage#delete-resources). | For the individual CLI commands and SDK methods behind these operations, see [Manage deployments](/docs/dedicated-endpoints/manage). ## Migrate an endpoint To move a v1 endpoint to v2, recreate it under the v2 resource model. Your v1 endpoint keeps serving while you stand up the v2 one, so you can cut over with no downtime. While both endpoints run during the cutover, you pay for the GPUs of both, so retire the v1 endpoint as soon as traffic is on v2. 1. **Find the model and a config:** Look up the model your v1 endpoint runs in the list of [supported models](/docs/dedicated-endpoints/models), then list the [configs](/docs/dedicated-endpoints/configs) published for it. Save the model ID (`ml_...`) and the ID of the config you choose (`cr_...`). 2. **Deploy the model:** With Together CLI 3.0, run `tg endpoints deploy --endpoint --config `, adding `--min-replicas` and `--max-replicas` to match your v1 endpoint's replica bounds. This creates the endpoint, deployment, and traffic split, and returns while the deployment provisions in the background. Save the endpoint string (`your-project-slug/`). 3. **Cut over:** Update your application's `model` field to the new endpoint string and [send a test request](/docs/dedicated-endpoints/requests). 4. **Retire the v1 endpoint:** Once traffic is on v2, [stop the v1 endpoint](#stop-a-v1-endpoint) to end its billing. The [quickstart](/docs/dedicated-endpoints/quickstart) walks through deploying and calling a v2 endpoint end to end. ## Manage remaining v1 endpoints The [3.0 SDKs and CLI](/docs/sdk-v3-migration-guide) removed the v1 methods and commands, so manage your remaining v1 endpoints with the v1 REST API at `https://api.together.ai/v1/endpoints` until you migrate them. ### List v1 endpoints List your dedicated v1 endpoints to find the ID of each one: ```bash cURL theme={null} curl -s "https://api.together.ai/v1/endpoints?type=dedicated&mine=true" \ -H "Authorization: Bearer $TOGETHER_API_KEY" ``` Each endpoint in `data` has an `id` (`endpoint-...`), a `name` that v1 inference requests pass as `model`, and a `state`, which is `STARTED` while the endpoint is running. To stop or delete an endpoint, pass its `id` as ``. ### Stop a v1 endpoint > [!WARNING] > > You can't restart a stopped v1 endpoint. To serve its model again, you need to redeploy the model on v2. To stop a v1 endpoint and end its billing, set its `state` to `STOPPED`: ```bash cURL theme={null} curl -s -X PATCH "https://api.together.ai/v1/endpoints/" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"state": "STOPPED"}' ``` ### Delete a v1 endpoint Deleting a v1 endpoint is permanent. A stopped endpoint doesn't bill, so delete one only when you no longer need its record: ```bash cURL theme={null} curl -s -X DELETE "https://api.together.ai/v1/endpoints/" \ -H "Authorization: Bearer $TOGETHER_API_KEY" ``` A successful delete returns HTTP 204 with an empty body. ## Migrate fine-tuned models Uploaded models carry over, but you must re-upload them into the v2 model catalog and reference them by model ID in a deployment: * **Fine-tuned models:** [Re-upload each model](/docs/dedicated-endpoints/custom-models). * **LoRA adapters:** [Re-upload each adapter](/docs/dedicated-endpoints/adapter) and deploy it on its own deployment. Serving several adapters on one deployment is available only for adapters from [post-training](/docs/post-training/multi-lora-deployment). Note the eligibility change: in v1 you could upload arbitrary models, but a v2 upload must be a fine-tuned variant of a base model architecture that Together AI already serves. ## Troubleshooting Most migration errors have one cause: v1 create and restart are retired. This isn't a permissions problem. Your models, fine-tuned checkpoints, hardware, and API key still work, so there's nothing to enable or restore. To fix these errors, [deploy the model on v2](#migrate-an-endpoint). | Error or symptom | What to do | | - | - | | `endpoints_v1_create_access_disabled` (HTTP 403) when creating an endpoint through the API or an SDK version before 3.0. | Create the endpoint on v2 instead, from the [console](https://api.together.ai/endpoints/configure), the [SDK or API](/reference/dmi/endpoints-create), or `tg endpoints deploy` in CLI 3.0. | | `You don't have permission to access this resource` from `tg endpoints create`, or `Unknown command "deploy"` from `tg endpoints deploy`. | Your Together CLI is older than `3.0.0`. CLI 2.x creates endpoints through the v1 API and reports the API's HTTP 403 as a permissions error. Upgrade the CLI with the command after this table, check that `tg --version` reports `3.0.0` or later, then deploy with `tg endpoints deploy`. | | A stopped or paused v1 endpoint won't start again. | Stopped v1 endpoints can't be restarted. Redeploy the same model as a new v2 endpoint. Fine-tuned models [don't need retraining](#migrate-fine-tuned-models). | | Creating a v1 endpoint still fails after you change replica bounds, autoscaling, or start settings. | Those settings don't affect the v1 create restriction. Deploy the model on v2. | | The SDK still calls the v1 endpoints API. | Upgrade to `together>=3.0.0` ([release notes](https://github.com/togethercomputer/together-py/releases/tag/v3.0.0)). In 3.0, `client.endpoints` and `client.models` call the v2 API, and the v1 methods are removed. For the v2 methods, see the [v2 endpoint reference](/reference/dmi/endpoints-create). | | `tg endpoints create`, `hardware`, `start`, or `stop` is missing in CLI 3.0. | CLI 3.0 removes these v1 commands. Use the [v2 commands](/reference/cli/endpoints) instead, such as `tg endpoints deploy`. To stop a v1 endpoint that's still running, use the [v1 REST API](#manage-remaining-v1-endpoints). | | You can't find a `/v2/endpoints` route in the docs or SDK. | The v2 management API is served under `https://api.together.ai`. See the [endpoint reference](/reference/dmi/endpoints-create) and [CLI reference](/reference/cli/endpoints). | To get the v2 commands, install or upgrade the CLI: ```bash theme={null} uv tool install "together[cli]" --upgrade ``` See the [models](/reference/cli/models) and [endpoints](/reference/cli/endpoints) CLI reference for the full command set. ## v2 capabilities Migrating your endpoint to v2 gives you access to several new capabilities: * [Split traffic across deployments](/docs/dedicated-endpoints/split-traffic): Host several deployments behind one endpoint URL and route requests between them by weight. * [Run A/B tests](/docs/dedicated-endpoints/ab-tests): Compare a candidate deployment against a baseline on live traffic before you promote it. * [Run a shadow experiment](/docs/dedicated-endpoints/shadow-experiments): Test a new deployment in production without affecting live traffic. * [Run a rollout](/docs/dedicated-endpoints/rollouts): Migrate live traffic from one deployment to another in steps, with automatic pauses when [live metrics](/docs/dedicated-endpoints/rollout-metric-gates) regress. * [Autoscale on a metric](/docs/dedicated-endpoints/scaling): Scale each deployment on the metric that fits your workload, and stop it when you don't need it to release the hardware. * [Monitor endpoints](/docs/dedicated-endpoints/monitoring): Track latency, throughput, and utilization in built-in dashboards, and trace lifecycle changes through the events feed. ## Timeline and support Existing v1 endpoints keep running until further notice, so you can migrate on your own schedule. Create all new endpoints and redeploy v1 endpoints that have stopped on v2. ## Next steps > [card] [Concepts](/docs/dedicated-endpoints/concepts) > > Learn the project, model, config, endpoint, and deployment model. > [card] [Quickstart](/docs/dedicated-endpoints/quickstart) > > Recreate an endpoint end to end with the CLI or SDK. > [card] [Choose a deployment profile](/docs/dedicated-endpoints/configs) > > Find the config that replaces your v1 hardware ID. > [card] [Manage deployments](/docs/dedicated-endpoints/manage) > > Create, inspect, scale, stop, and delete endpoints and deployments. # Supported models Source: https://docs.together.ai/docs/dedicated-endpoints/models View the supported models you can deploy or fine-tune for dedicated model inference. This page lists the supported models hosted by Together AI for dedicated model inference. You can also [upload a model you fine-tuned](/docs/dedicated-endpoints/custom-models).> [!TIP] > > If you're not sure which model to use, check out our list of [recommended models](/docs/recommended-models) by use case.## ModelsThe **Deployable hardware** column shows the [instance type](/docs/dedicated-endpoints/concepts#instance-type) of each model's smallest published [deployment profile](/docs/dedicated-endpoints/concepts#deployment-profile). A model may offer other profiles on different hardware. See [Pricing](/docs/dedicated-endpoints/pricing#supported-hardware) for the per-hour cost of each instance type. \ \ \ \ \
TypeOrganizationModel nameAPI model nameDeployable hardware
## List supported models programmaticallyThe table above is generated from Together's model catalog. To fetch the same catalog from the command line, list the platform-supported models with `tg models public`. Filter by product surface (`--product`), input modality (`--modality`), or a search term (`--search`):```bash CLI theme={null} # All models available for dedicated inference tg models public --product DEDICATED # Narrow by modality or search term tg models public --modality TEXT --search qwen ```Add `--json` to see the full record for each model, including the `deploymentProfiles` array. Each profile is a certified model-and-config pair Together publishes for that model, so it gives you a vetted `model` and `config` that you can pass straight into [creating a deployment](/docs/dedicated-endpoints/manage#create-a-deployment).The response looks like this:```json theme={null} { "data": [ { "id": "arch_abc123", "name": "zai-org/GLM-5.2", "displayName": "GLM 5.2", "displayType": "chat", "deploymentProfiles": [ { "profileId": "cfg_a", "certifiedConfigRevisionId": "cr_certified", "certifiedModelRevisionId": "rv_snap", "modelName": "zai-org/GLM-5.2-FP8", "config": "projects/proj_cfg/configs/cr_certified", "model": "projects/proj_weights/models/ml_weight/revisions/rv_snap", "parallelism": "TP8", "gpuType": "H100", "gpuCount": 8 } ] } ], "object": "list" } ```Each architecture includes these identity fields:| Field | Description | | - | - | | `id` | Architecture UID (`arch_...`). Pass to `retrieve_supported` to fetch a single entry. The catalog also accepts the architecture slug. | | `name` | Catalog-controlled Hugging Face model ID (for example `zai-org/GLM-5.2`). | | `displayName` | Catalog-controlled human-readable display name (for example `GLM 5.2`). |Each architecture also includes `displayType`, the model's category. Possible values are `chat`, `language`, `code`, `image`, `embedding`, `rerank`, `moderation`, `audio`, `video`, and `transcribe`.Each deployment profile includes these fields:| Field | Description | | - | - | | `modelName` | Name of the deploy model this profile references (`/`). This is the model name you pass when you deploy, and it identifies which precision weight the profile uses (for example `zai-org/GLM-5.2-FP8`). | | `config` | Resource name of the certified config revision: `projects/{project_id}/configs/{config_revision_id}`. `{project_id}` is the config's owning project, which is often a platform project rather than your project. Empty when the profile has no config pinned or its owning project is unresolved. | | `model` | Resource name of the deployable weight model for this profile (the quantization-specific build, not the architecture's base model): `projects/{project_id}/models/{model_id}[/revisions/{revision_id}]`. This field also exposes the deploy model ID, which the bare `certifiedModelRevisionId` alone does not. Empty when the profile has no model pinned or its owning project is unresolved. | | `parallelism` | The catalog's free-form parallelism spec (for example `TP8`, `TP4`, `EP`, or `PD`). Not every value is a tensor-parallel degree. |The bare `certifiedConfigRevisionId` and `certifiedModelRevisionId` fields remain populated alongside the resource names. Copy `config` and `model` from a profile directly into the `config` and `model` fields when you [create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment).To list the profiles published for a specific model instead, see [Choose a deployment profile](/docs/dedicated-endpoints/configs). # Metrics and dashboards Source: https://docs.together.ai/docs/dedicated-endpoints/monitoring Monitor endpoint and deployment metrics using the Together AI console, Grafana, or the Prometheus-compatible metrics endpoint. Dedicated model inference records latency, throughput, and utilization metrics for every endpoint and deployment. These are the same series that drive [autoscaling](/docs/dedicated-endpoints/scaling#scaling-metrics). ## Analytics dashboard The Together AI console shows per-endpoint charts for requests, tokens per second, input tokens, output tokens, latency, and time to first token, built on the metric series below. [Endpoints](https://api.together.ai/endpoints) Open an endpoint and select the **Analytics** tab. Switch between **Usage** and **Errors**, view the endpoint **Total** or break it down **By deployment**, and adjust the time range. Use the dashboard to monitor an endpoint at a glance and to compare deployments during an [A/B test](/docs/dedicated-endpoints/ab-tests). ![The Analytics tab for an endpoint in the Together AI console, with charts for requests, tokens per second, input tokens, and output tokens, plus Usage and Errors toggles, a Total and By deployment breakdown, and a time-range selector.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/monitoring-analytics.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=506df76b0031f8d2663c75dd8b88a06d) The charts populate once the endpoint starts serving requests. ## Grafana dashboard Together AI automatically creates and hosts a Grafana instance for each project with an active deployment. The prebuilt dashboard charts the [available metrics](#available-metrics) for every endpoint in the project. Unlike the **Analytics** tab, the dashboard breaks latency down by layer of the request path and shows queueing overhead and key-value (KV) cache utilization. To open the dashboard, select **Open Grafana** at the top of the [**Endpoints**](https://api.together.ai/endpoints) page to see every endpoint in the project, or at the top of an endpoint's page to see only that endpoint. Grafana opens in a new tab, already signed in. The button appears once the instance is ready. Anyone who can view the project can open Grafana. Together AI deletes the instance 30 days after the project's last deployment stops. ### Read the dashboard Use the **Endpoint** and **Deployment** variables at the top to focus on one endpoint, or on one deployment during an [A/B test](/docs/dedicated-endpoints/ab-tests) or [traffic split](/docs/dedicated-endpoints/split-traffic). The rows follow the request path from the client inward, matching the [metric groups](#available-metrics) of the metrics endpoint: * **Golden signals (edge):** Request rate stacked by status code, the 5xx error ratio, and in-flight requests, all measured at the front-door proxy. This row is the client's view of the endpoint, so check it first during an incident. * **Latency, client-observed (edge):** Request duration and time to first token as p50, p90, and p99. Edge latencies are in milliseconds. The time-to-first-token panel counts only streaming requests. * **Latency, server-side (router and worker):** At the router, request duration and the routing and queue overhead before the worker. At the worker, generation duration, time to first token, and time per output token. Router and worker latencies are in seconds, not milliseconds. A gap between edge latency and worker latency points at network or queueing overhead rather than model speed. * **Throughput and tokens:** Request rate by layer (edge, router, and worker), token throughput by token type, and tokens per request. When the three layers' request rates disagree, the comparison shows where requests drop off. * **Engine and cache (worker):** KV cache utilization per deployment and the prefix cache hit rate. Sustained high KV cache utilization is a signal to [scale up or out](/docs/dedicated-endpoints/scaling). A low hit rate means little prefix reuse across requests. Every rate, ratio, and percentile on the dashboard is a PromQL query that Grafana runs over raw counters and histogram buckets. ### Customize the dashboard The hosted Grafana signs everyone in as a viewer, so you can't edit the dashboard, save a copy, or create new dashboards. To customize the dashboard, import it into [your own Grafana](/docs/dedicated-endpoints/grafana). ## Events Each endpoint has an audit feed of events, newest first. It merges endpoint-scoped events with the deployment-scoped events for every deployment under the endpoint, so scale-ups, traffic shifts, readiness changes, and pauses across every deployment all surface here. Use it to trace what happened during an autoscaling event or a traffic-split change. In the console, open an endpoint and select the **Logs** tab to browse the feed, with columns for time, type, source, level, and message. ![The Logs tab for an endpoint in the Together AI console, an event feed with Time, Type, Source, Level, and Message columns showing the deployment's lifecycle events.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/monitoring-logs.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=3cd2f6a9e0f9249d5a2f4b5258d90441) To read the feed from the terminal, list events with the CLI. Pass the endpoint ID or name: ```bash Shell theme={null} tg endpoints events ep_abc123 ``` Optional flags narrow the feed: * `--types` restricts to specific event-type strings, comma-separated (for example `deployment.scaled,condition.set`). * `--min-level` sets the minimum severity: `debug`, `info`, `warn`, or `error`. * `--since` and `--until` bound a time range. * `--subject-id` filters to a single subject, such as a rollout ID. * `--deployment-ids` scopes to specific deployments, comma-separated. * `--limit` and `--after` paginate (max `10000`, default `50`). When more events remain, the CLI prints the `--after` command for the next page. Add `--json` for the raw event objects, including fields the table view omits. See the [endpoints CLI reference](/reference/cli/endpoints#events) for the full flag list. > [!NOTE] > > Endpoint mutation events such as `endpoint.updated` record when a change happened, but they don't include a field-level diff. Keep configuration history in your deployment system if you need to reconstruct exactly what changed. ### Deployment events To follow a single deployment instead of the whole endpoint, pass its ID to the `--deployment-ids` filter on the same events feed: ```bash Shell theme={null} tg endpoints events ep_abc123 --deployment-ids dep_abc123 ``` Filtering by deployment ID excludes endpoint-scoped events such as `endpoint.updated`, so the output covers only the listed deployments' lifecycles. ## Prometheus-compatible metrics endpoint > [!NOTE] > > The metrics endpoint is in beta. The host and path below are subject to change, and access may need to be enabled for your organization. Confirm availability with your Together AI contact before you build against it. Scrape real-time, per-organization performance metrics for your dedicated endpoints in standard Prometheus format. The endpoint works with any Prometheus-compatible scraper, including Prometheus, Grafana Agent, the Datadog OpenMetrics integration, and Vector. ### Authentication and URL Metrics are served per organization at: ```text theme={null} GET https://o11y-de2-metrics.cloud.together.ai/organizations/{org_id}/metrics ``` Authenticate with your API key as a bearer token. The endpoint is org-scoped by design, so it returns only your organization's data: ```bash Shell theme={null} curl -H "Authorization: Bearer $TOGETHER_API_KEY" \ "https://o11y-de2-metrics.cloud.together.ai/organizations/$ORG_ID/metrics" ``` ### Prometheus scrape config Point a Prometheus-compatible scraper at the endpoint: ```yaml theme={null} scrape_configs: - job_name: together-endpoint-metrics scheme: https authorization: credentials: metrics_path: /organizations//metrics static_configs: - targets: ["o11y-de2-metrics.cloud.together.ai"] ``` To chart the scraped series, follow [Run your own Grafana](/docs/dedicated-endpoints/grafana). It runs Prometheus and Grafana with Docker Compose and imports the [example dashboard](https://github.com/togethercomputer/together-cookbook/tree/main/dedicated-endpoints/Grafana_Dedicated_Endpoints), which has the same panels as your project's [Grafana dashboard](#grafana-dashboard). ### Available metrics Metrics are grouped by the stage of the request path they measure: the edge (front-door proxy), the router, and the worker (model server). Latency metrics are histograms, exposed as `_bucket`, `_sum`, and `_count` series. Counters end in `_total`. Gauges are point-in-time values. #### Edge (front-door proxy) | Metric | Type | Unit | Notes | | - | - | - | - | | `edge_inference_requests_total` | Counter | requests | Broken down by `status_code`. | | `edge_inference_request_duration_ms` | Histogram | milliseconds | End-to-end request duration at the edge. | | `edge_inference_ttft_ms` | Histogram | milliseconds | Time to first token. Most meaningful with `is_streaming="true"`. | | `edge_inference_inflight_requests` | Gauge | requests | Concurrent in-flight requests at the edge. | #### Router | Metric | Type | Unit | Notes | | - | - | - | - | | `router_inference_requests_total` | Counter | requests | Broken down by `status_code`. | | `router_inference_request_duration_seconds` | Histogram | seconds | Request duration at the router. | | `router_inference_ttft_seconds` | Histogram | seconds | Time to first token. | | `router_pre_worker_duration_seconds` | Histogram | seconds | Routing and queue overhead before the worker. | | `router_inference_inflight_requests` | Gauge | requests | Concurrent in-flight requests at the router. | | `router_token_count` | Counter | tokens | Broken down by `token_type`, and by `requester_organization_id`. | | `router_tokens_per_request` | Histogram | tokens | Broken down by `token_type`. | #### Worker (model server) | Metric | Type | Unit | Notes | | - | - | - | - | | `worker_inference_request_total` | Counter | requests | Broken down by `status_code`. | | `worker_ttft_seconds` | Histogram | seconds | Time to first token. | | `worker_generation_duration_seconds` | Histogram | seconds | Total generation duration. | | `worker_tpot_seconds` | Histogram | seconds | Time per output token (inter-token latency). | | `worker_token_total` | Counter | tokens | Broken down by `token_type`. | | `worker_tokens_per_request` | Histogram | tokens | Broken down by `token_type`. | | `worker_engine_kv_cache_utilization` | Gauge | ratio (0-1) | Fraction of the engine's KV-cache capacity in use. | | `worker_engine_cache_hit_rate` | Gauge | ratio (0-1) | Hit rate of the engine's KV cache. Higher values mean more prefix reuse across requests. | ### Labels Series carry labels that identify the resource and slice the data. Not every label appears on every metric. | Label | Description | | - | - | | `owner_organization_id` | Organization that owns the endpoint. | | `owner_project_id` | Project that owns the endpoint. | | `endpoint_id` / `endpoint_name` | The endpoint. | | `deployment_id` / `deployment_name` | The deployment. | | `deployment_service_id` | Internal service identifier for the deployment. | | `model` (edge) / `model_id` (worker) | The served model. | | `deployment_region` (edge) | Region the deployment runs in. | | `edge_region` (edge) | Region of the edge proxy that served the request. | | `replica_id` | The specific replica. | | `status_code` | HTTP status code of the request. | | `is_streaming` | Whether the request was streamed (`"true"` or `"false"`). | | `token_type` | Token category (for example input or output). | | `path` | Request path. | | `requester_organization_id` | Organization that made the request. | ## Next steps > [card] [Run your own Grafana](/docs/dedicated-endpoints/grafana) > > Scrape the metrics endpoint into your own Prometheus and Grafana, then alert on errors. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Pick a metric to autoscale a deployment on. > [card] [Route traffic](/docs/dedicated-endpoints/route-traffic) > > See how the endpoint routes requests across deployments. > [card] [Gate rollouts with metrics](/docs/dedicated-endpoints/rollout-metric-gates) > > Pause a rollout automatically when a new deployment regresses on live metrics. # Overview Source: https://docs.together.ai/docs/dedicated-endpoints/overview Deploy a model for inference on dedicated GPUs. > [!TIP] > > Using a coding agent? Install the [together-ai](https://github.com/togethercomputer/skills/tree/main/skills/together-ai) skill to let your agent deploy and manage dedicated endpoints automatically. See [agent skills](/docs/agent-skills) for details. Dedicated model inference (DMI) lets you serve a model on reserved hardware, providing several advantages over [serverless models](/docs/serverless/overview): * **Better performance:** Dedicated GPUs provide higher throughput, lower latency, and more predictable performance. * **No hard rate limits:** You're only limited by the capacity of your selected hardware, plus the bounds of your autoscaling configuration. * **Fine-tuned models:** Deploy a model you fine-tuned from a supported base model. * **Cost-efficient at scale:** DMI bills per-GPU-minute, which is cheaper at high utilization than serverless models (which bill per-token). Dedicated model inference uses the same [inference APIs](/docs/inference/overview#shared-inference-api) as serverless models, so you can prototype on serverless, then deploy on DMI without changing your application code. > [!TIP] > > If you're running a stock model in production and want a defined SLA without managing hardware, contact sales for [provisioned throughput](/docs/inference/provisioned-throughput). You can deploy an endpoint from the console, through the API, or with the [Together CLI](/reference/cli/endpoints): ```bash theme={null} # deploy a model to a new endpoint tg endpoints deploy google/gemma-4-E4B-it --endpoint my-endpoint # check the status until it's READY tg endpoints get # delete the endpoint when you're done tg endpoints rm --force ``` The [quickstart](/docs/dedicated-endpoints/quickstart) breaks down this flow and shows how to run inference against the endpoint. ## Get started > [card] [Quickstart](/docs/dedicated-endpoints/quickstart) > > Deploy and call your first endpoint in a few minutes. > [card] [Concepts](/docs/dedicated-endpoints/concepts) > > The DMI resource model and development workflow. > [card] [Manage deployments](/docs/dedicated-endpoints/manage) > > Create, scale, stop, and delete your deployments. > [card] [Supported models](/docs/dedicated-endpoints/models) > > Browse the list of Together-hosted models you can deploy. > [card] [Upload a fine-tuned model](/docs/dedicated-endpoints/custom-models) > > Deploy a model you fine-tuned from a supported base model. > [card] [Upload a LoRA adapter](/docs/dedicated-endpoints/adapter) > > Import a custom low-rank adapter (LoRA) from Hugging Face or S3 and serve it. > [card] [Multi-LoRA deployment](/docs/post-training/multi-lora-deployment) > > Attach post-training adapters to one deployment and choose one per request. > [card] [Migrate from v1](/docs/dedicated-endpoints/migrate-from-v1) > > Migrate a dedicated endpoint to the new DMI resource model. ## Project scope The `tg endpoints` and `tg models` commands, the management API, and the SDKs' `client.endpoints` and `client.models` methods operate within a [Together AI project](/docs/projects). The CLI reads the project from the `TOGETHER_PROJECT_ID` environment variable, or you can pass `--project` on any command. If neither is set, it uses the project you selected with `tg login` or `tg switch`, or the project associated with your API key. In the SDKs, pass `project_id` to `Together()` in Python or `projectID` to `new Together()` in TypeScript, or set `TOGETHER_PROJECT_ID`. Otherwise, read the project ID from `client.whoami()` before project-scoped API calls. For a project API key, the response's `type` is `project_api_key` and the ID is in `project.id`. ```bash theme={null} export TOGETHER_PROJECT_ID=your_project_id ``` ## Development workflow To create a deployment, run the `tg endpoints deploy` command, passing the model and endpoint name. This creates an endpoint, attaches a deployment, and routes all traffic to it: ```bash theme={null} tg endpoints deploy google/gemma-4-E4B-it \ --endpoint my-endpoint ``` The command prints the new endpoint's **endpoint string** (`/`): pass it as the `model` parameter on inference requests. Once the deployment is ready, send inference requests to the endpoint using the same [inference API](/docs/inference/overview#shared-inference-api) as serverless models. Pass the endpoint string as the `model` parameter: ```python Python {6} theme={null} from together import Together client = Together(base_url="https://api-inference.together.ai") response = client.chat.completions.create( model="your-project-slug/my-endpoint", messages=[{"role": "user", "content": "What is 2+2?"}], max_tokens=512, ) print(response.choices[0].message.content) ``` ```typescript TypeScript {8} theme={null} import Together from 'together-ai'; const client = new Together({ baseURL: 'https://api-inference.together.ai', }); const response = await client.chat.completions.create({ model: 'your-project-slug/my-endpoint', messages: [{ role: 'user', content: 'What is 2+2?' }], max_tokens: 512, }); console.log(response.choices[0].message.content); ``` ```bash cURL {5} theme={null} curl -s -X POST https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-project-slug/my-endpoint", "messages": [{"role": "user", "content": "What is 2+2?"}], "max_tokens": 512 }' ``` `deploy` bundles the endpoint, deployment, and traffic-routing steps for you. You can also [run those steps individually](/docs/dedicated-endpoints/manage), or drive them from the Python and TypeScript SDKs. For a step-by-step walkthrough, [follow the quickstart](/docs/dedicated-endpoints/quickstart). For more details on the DMI resource model, see [Concepts](/docs/dedicated-endpoints/concepts). ## Key features * **Deploy any supported model:** Run a [Together-hosted model](/docs/dedicated-endpoints/models), a [model you fine-tuned on Together](/docs/fine-tuning/overview), or [a fine-tuned model you upload](/docs/dedicated-endpoints/custom-models). * **Autoscale on demand:** [Scale your deployments with replicas](/docs/dedicated-endpoints/scaling) to meet demand, and stop them when you don't need them to reduce costs. * **Split traffic across deployments:** Host multiple deployments behind one endpoint URL and [route requests](/docs/dedicated-endpoints/split-traffic) between them by weight. * **Compare deployments on live traffic:** Run an [A/B test](/docs/dedicated-endpoints/ab-tests) with control and variant splits to measure a candidate against a baseline before you promote it. * **Migrate deployments with rollouts:** Shift live traffic from one deployment to another in [controlled, metric-gated steps](/docs/dedicated-endpoints/rollouts) without changing the endpoint URL. * **Monitor endpoints:** Track latency, throughput, and utilization in [built-in dashboards](/docs/dedicated-endpoints/monitoring), and trace lifecycle changes through the events feed. ## Pricing Dedicated model inference [bills per minute by hardware](/docs/dedicated-endpoints/pricing) while a deployment runs, regardless of model or request volume. Each running replica bills independently and stops billing as soon as it scales down. # Pricing Source: https://docs.together.ai/docs/dedicated-endpoints/pricing Billing and pricing details for dedicated model inference. Dedicated model inference (DMI) bills based on the hardware your deployments run on, regardless of model or request volume: * **Billed by the minute:** A deployment bills for as long as it runs, not per token or per request. The model you serve affects cost only through the hardware it needs (a larger model requires more or bigger GPUs), not through how many tokens or requests you push through it. * **Per replica:** Each running replica bills independently. A deployment running three replicas bills three times the single-replica rate. * **Only ready replicas:** A replica bills only while it's ready and able to serve traffic. Time spent provisioning or [cold-starting](/docs/dedicated-endpoints/concepts#cold-starts) isn't billed, and neither is a replica that isn't ready, such as while a deployment is [`DEGRADED`](/docs/dedicated-endpoints/manage#deployment-states). * **Stops when scaled down:** A replica stops billing as soon as it scales down. A deployment scaled to zero replicas, or stopped, costs nothing. Because cost tracks running replicas, you keep your cost down by [running only as many replicas as you need](/docs/dedicated-endpoints/scaling) for your workload, and by stopping a deployment or setting its [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds) to zero when you don't need it. You can also set an [inactivity timeout](/docs/dedicated-endpoints/scaling#automatic-idle-shutdown) so a deployment that serves no requests stops on its own. ## Supported hardware The following table lists the available hardware types. Where a single-GPU per-hour price is listed, multi-GPU configs cost proportionally more (a four-GPU config costs four times the single-GPU rate). For hardware without a listed price, [contact sales](https://www.together.ai/contact-sales) for a quote. | GPU | Hardware ID | Cost/hour | | - | - | - | | H100 80GB | `1xnvidia-h100-80gb` | \$5.49 | | H200 141GB | `1xnvidia-h200-140gb` | [Contact sales](https://www.together.ai/contact-sales) | | B200 180GB | `1xnvidia-b200-180gb` | \$8.99 | | GB300 280GB | `1xnvidia-gb300-280gb` | [Contact sales](https://www.together.ai/contact-sales) | | B300 280GB | `1xnvidia-b300-280gb` | [Contact sales](https://www.together.ai/contact-sales) | Hardware and GPU count are set by the [config](/docs/dedicated-endpoints/configs) you select when you create a deployment. ## How scaling affects cost Billing is proportional to the number of ready replicas across all deployments in your project, which you can track as `status.readyReplicas` when you [poll deployment status](/docs/dedicated-endpoints/manage#poll-deployment-status). For a given deployment, you control how much it costs with its [replica bounds](/docs/dedicated-endpoints/scaling#replica-bounds), and by stopping it when you don't need it: * **`minReplicas`:** This sets the floor for a deployment's cost. These replicas will run and bill continuously, so set it to the lowest count that meets your latency target. * **`maxReplicas`:** This sets the ceiling for a deployment's cost. The deployment never bills for more than this many replicas, so set it to a high enough count to handle your peak traffic. * **Stop when idle:** [Stop a deployment](/docs/dedicated-endpoints/manage#stop-a-deployment) or set both replica bounds to zero when you don't need it. It bills nothing while stopped, and you restart it (requiring a [cold start](/docs/dedicated-endpoints/concepts#cold-starts)) by raising the replica bounds. See [Configure autoscaling](/docs/dedicated-endpoints/scaling) for more details. ## On-demand vs. reserved Dedicated model inference offers two pricing options: * **On-demand:** Pay the per-minute rate for as long as your replicas run, with no commitment. Capacity scales up and down within your replica bounds. Best for variable traffic and prototyping. * **Reserved:** Commit to capacity for a set term at a lower effective rate, with guaranteed hardware availability. Best for steady, predictable production traffic. To set up reserved capacity, [contact us](https://www.together.ai/forms/monthly-reserved). ## DMI vs. serverless [Serverless models](/docs/serverless/overview) bill per token, while dedicated model inference bills per-minute for each running replica, regardless of how many tokens you push through. When comparing the two, consider how busy a replica would be for your workload: 1. Work out your DMI cost from the per-minute rate: A single H100 replica at \$5.49/hour costs about \$132/day, or roughly \$3,950 over a 30-day month, if running continuously. 2. Estimate your serverless cost at the same volume: Monthly tokens multiplied by the model's serverless per-token price. **DMI is usually cheaper** when a replica would stay busy most of the day. The fixed per-minute cost is spread across high throughput, and you also get reserved capacity and predictable latency. **Serverless is usually cheaper** when traffic is low or bursty enough such that a dedicated replica would be sitting idle most of the time. You pay only for the tokens you use, so you lose nothing during an idle window. Stopping a deployment when it's idle narrows the gap, but won't help if your deployment receives steady low-volume traffic around the clock. ## Next steps > [card] [Manage deployments](/docs/dedicated-endpoints/manage) > > Create and manage deployments to serve your model. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Control cost with replica bounds. # Quickstart Source: https://docs.together.ai/docs/dedicated-endpoints/quickstart Deploy a model on dedicated hardware in a few minutes. Dedicated model inference (DMI) serves a model on GPUs reserved for you, instead of the shared capacity behind [serverless models](/docs/serverless/overview). Use it when you need more predictable latency, throughput past serverless rate limits, or a place to serve a model you fine-tuned. In this quickstart, you'll deploy `google/gemma-4-E4B-it` to an endpoint, send it a request, and tear it down when you're done. ## Requirements Before you begin, make sure you have: * [Created an account](https://api.together.ai/settings/projects/~first/api-keys) and generated an API key in the project you'll deploy to. Run `tg whoami` after you log in to see the CLI's project. * [Set your API key as an environment variable](/docs/api-keys-authentication#set-as-an-environment-variable) in your terminal. * Installed the Together CLI and logged in: ```bash theme={null} # Install or upgrade uv tool install "together[cli]" --upgrade # Log in with your browser tg login ``` > [!NOTE] > > The commands on this page require Together CLI version `3.0.0` or later. Check your version with `tg --version`. > [!NOTE] > > In CI, agents, or other environments where the CLI cannot prompt for confirmation, select a project before deploying. Run `tg whoami` to find your project ID, then set `TOGETHER_PROJECT_ID` or pass `--project ` to the command. ## Step 1: Deploy a model Deploy `google/gemma-4-E4B-it`, one of the [supported models](/docs/dedicated-endpoints/models) Together hosts. The deployment provisions in the background: for a model this size, first-time provisioning usually takes about 5 to 10 minutes while the weights download and hardware is allocated, and larger models take longer. > [tab] CLI > > The `endpoints deploy` command creates an endpoint, attaches a deployment on the model's default hardware, and routes all traffic to it: > > ```bash theme={null} > tg endpoints deploy google/gemma-4-E4B-it \ > --endpoint quickstart-endpoint > ``` > > The command returns as soon as the resources are created and prints the endpoint's details: > > ```bash theme={null} > √ Model deployed to endpoint your-project-slug/quickstart-endpoint. > > ╭─ Endpoint Details for quickstart-endpoint ───────────────────────────────────╮ > │ Endpoint string your-project-slug/quickstart-endpoint │ > │ Endpoint ID ep_abc123 │ > │ Created at 07/13/2026, 06:52 PM │ > │ Updated at 07/13/2026, 06:52 PM │ > │ Visibility Private │ > │ Web URL https://api.together.ai/endpoints/ep_abc123 │ > ╰──────────────────────────────────────────────────────────────────────────────╯ > > Deployments > ╭──────────────────────────────────────┬───────────────────┬───────────────────╮ > │ Deployment │ Model │ │ > ├──────────────────────────────────────┼───────────────────┼───────────────────┤ > │ Name: │ google/gemma-4… │ Status: │ > │ google-gemma-4-E4B-it-BF16-abc123… │ │ Provisioning │ > │ ID: dep_abc123 │ │ Replicas: 0 / 1 │ > ╰──────────────────────────────────────┴───────────────────┴───────────────────╯ > ``` > > Note the **endpoint string** (`your-project-slug/quickstart-endpoint`): pass it as the `model` parameter when you send requests. > > Check the deployment's status with the deployment ID from the output, and wait for `DEPLOYMENT_STATE_READY`: > > ```bash theme={null} > tg endpoints get dep_abc123 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > **1. Open the create form** > > On the **Endpoints** page, select **New endpoint**. > > **2. Name the endpoint and deployment** > > In **Endpoint name**, enter `quickstart-endpoint`. In **Deployment name**, enter `quickstart-deployment`. The console requires a deployment name, unlike the CLI, which generates one for you. > > **3. Choose the model** > > Under **Model**, select `google/gemma-4-E4B-it`. > > **4. Keep the defaults** > > Leave the default **Deployment profiles** card and **Region**, and keep **Min replicas** and **Max replicas** at `1`. > > **5. Create the endpoint** > > Select **Create endpoint**. You land on the endpoint's page, where the deployment starts in **Provisioning** and moves to **Ready** once it's live. > > Copy the **endpoint string** shown on the endpoint's page (in the form `your-project-slug/quickstart-endpoint`): this is what you pass as the `model` parameter when you send requests. > > ![The Create endpoint form in the Together AI console, configured with the model Gemma 4 E4B IT, a selected Deployment profiles card (hardware and quantization), Any region, and min and max replicas both set to 1. The Summary panel shows an estimated hourly cost and a Create endpoint button.](https://mintcdn.com/togetherai-52386018/wiTeh4I8I-you2HE/images/dedicated-endpoints/quickstart-create-endpoint.png?fit=max\&auto=format\&n=wiTeh4I8I-you2HE\&q=85\&s=476d366f0957264069419937bda07338) ## Step 2: Send a request Point the SDK's base URL at `https://api-inference.together.ai`, pass the endpoint string as the `model` parameter, and use the same request shape as a [serverless model](/docs/inference/overview#shared-inference-api): ```python Python theme={null} from together import Together client = Together(base_url="https://api-inference.together.ai") response = client.chat.completions.create( model="your-project-slug/quickstart-endpoint", messages=[{"role": "user", "content": "What is 2+2?"}], max_tokens=512, ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together({ baseURL: 'https://api-inference.together.ai', }); const response = await client.chat.completions.create({ model: 'your-project-slug/quickstart-endpoint', messages: [{ role: 'user', content: 'What is 2+2?' }], max_tokens: 512, }); console.log(response.choices[0].message.content); ``` ```bash cURL theme={null} curl -s -X POST https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-project-slug/quickstart-endpoint", "messages": [{"role": "user", "content": "What is 2+2?"}], "max_tokens": 512 }' | jq . ``` You should see output similar to this: ```json theme={null} { "id": "8d43d9055fa845b2b1ad11b946191a7e", "object": "chat.completion", "created": 1782839730, "model": "your-project-slug/quickstart-endpoint", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "2 + 2 = 4." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 74, "completion_tokens": 13, "total_tokens": 87 } } ``` > [!TIP] > > Congrats! You deployed and called your first dedicated model on Together AI. ## Step 3: Clean up resources Dedicated model inference bills per minute per running replica, so tear down what you deployed once you're done. > [tab] CLI > > Pass the endpoint ID (`ep_abc123`) from the deploy output to `rm` with `--force` to delete the endpoint and its deployment in one step: > > ```bash theme={null} > tg endpoints rm ep_abc123 --force > ``` > > To stop charges without deleting anything (for example, to redeploy later), [scale the deployment](/docs/dedicated-endpoints/manage#stop-a-deployment) to zero instead, then re-run the status command above to confirm it reaches `DEPLOYMENT_STATE_STOPPED`. > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > On the endpoint's page, open the deployment and select **Stop** to scale it to zero, which stops the per-minute charges. To bring it back later, select **Start**. > > To remove the endpoint entirely, delete it once the deployment is stopped: open **Endpoint actions** and select **Delete endpoint**, then confirm. The console keeps **Delete endpoint** disabled until every deployment under the endpoint is stopped or deleted. ## Next steps > [card] [Concepts](/docs/dedicated-endpoints/concepts) > > Understand the resource model and development workflow. > [card] [Manage deployments](/docs/dedicated-endpoints/manage) > > Create, scale, stop, and delete endpoints and deployments. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Autoscale a deployment on the metric that fits your workload. > [card] [Upload a model](/docs/dedicated-endpoints/custom-models) > > Deploy a model you fine-tuned from a supported base model. # Send requests Source: https://docs.together.ai/docs/dedicated-endpoints/requests After deploying a model, send requests using the shared inference API. After [deploying a model](/docs/dedicated-endpoints/manage#create-a-deployment) and [routing traffic](/docs/dedicated-endpoints/route-traffic) to it, you can send requests to the endpoint using the same [inference APIs](/docs/inference/overview) as serverless models. Features available on the underlying model work the same way on DMI, including: * [Function calling](/docs/inference/function-calling/overview) for tool use. * [Structured outputs](/docs/inference/chat/structured-outputs) for JSON-shaped responses. * [Streaming](/docs/inference/chat/overview) responses. Dedicated model inference is served at `https://api-inference.together.ai`. There's no CLI for inference, so send requests with curl or the SDK, pointing the SDK's base URL at `https://api-inference.together.ai`. OpenAI-compatible clients use `https://api-inference.together.ai/v1`. Pass the endpoint string as the `model` parameter, and use the same request shape you'd use against a serverless model. The endpoint string has the form `your-project-slug/endpoint-name`: ```python Python theme={null} from together import Together client = Together(base_url="https://api-inference.together.ai") response = client.chat.completions.create( model="your-project-slug/endpoint-name", messages=[{"role": "user", "content": "What is 2+2?"}], max_tokens=512, ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from 'together-ai'; const client = new Together({ baseURL: 'https://api-inference.together.ai', }); const response = await client.chat.completions.create({ model: 'your-project-slug/endpoint-name', messages: [{ role: 'user', content: 'What is 2+2?' }], max_tokens: 512, }); console.log(response.choices[0].message.content); ``` ```bash cURL theme={null} curl -s -X POST https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-project-slug/endpoint-name", "messages": [{"role": "user", "content": "What is 2+2?"}], "max_tokens": 512 }' | jq . ``` To [call a low-rank adapter (LoRA)](/docs/post-training/multi-lora-deployment#send-requests-to-an-adapter) attached to the deployment, append a colon and the adapter's model ID to the endpoint string, for example `your-project-slug/endpoint-name:ml_abc123`. ## Prompt caching Prompt caching stores the result of previously processed prompt prefixes so the model can reuse them instead of recomputing. It reduces redundant compute for repeated prefixes, such as a system prompt that's shared across many requests. Prompt caching is enabled by default for dedicated model inference. No configuration is required. See [Prompt caching](/docs/inference/chat/prompt-caching) for detailed information on how prefix matching works, how to structure prompts for cache hits, and how to group related requests with `prompt_cache_key`. ## Decoding optimizations Decoding optimizations such as speculative decoding are set by the [config](/docs/dedicated-endpoints/configs#decoding-optimizations) your deployment runs on. To change them, deploy a different config. ## Next steps > [card] [Create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment) > > Set the traffic split that drives routing. > [card] [Route traffic](/docs/dedicated-endpoints/route-traffic) > > See how the endpoint resolves each request to a deployment. # Gate rollouts with metrics Source: https://docs.together.ai/docs/dedicated-endpoints/rollout-metric-gates Pause a canary rollout automatically when the new deployment regresses. When you create a [canary rollout](/docs/dedicated-endpoints/rollouts), you can configure a metric gate to pause the rollout automatically when the target deployment regresses, for example when it serves traffic more slowly than the source or has a higher error rate. A metric gate monitors live metrics as the rollout shifts traffic. After each step, the rollout holds the traffic split during the *soak window*, a waiting period (set by `--interval` in the CLI, or **Step interval** in the console) during which traffic stays at the current split level so the metric can settle and accumulate samples. At the end of the window, the gate evaluates its rules against the target deployment and either advances the rollout or pauses it for review. > [!WARNING] > > **Metric gates require traffic on the endpoint:** The gate compares live traffic on the target against the source. If the endpoint is serving traffic but the target accumulates no samples, the gate reports the metric as unavailable and the rollout pauses for review. A fully idle endpoint (no traffic on either deployment) skips the gate entirely and the rollout proceeds ungated. ## Configure a metric gate Metric gates are canary-only. Blue-green and rolling strategies have no soak window, so a gate is rejected at create time. > [tab] CLI > > Configure a gate by passing `--metric*` flags to the `rollout dep_target456 --canary` command. Pass a [supported metric](#supported-metrics) plus either a threshold check or a regression check. For `router_latency`, set `--metric-stat` to `avg` or a percentile. For `router_error_rate` and `inflight_requests`, omit `--metric-stat` (the platform records it as `AVG`). > > ```bash theme={null} > # Threshold check: p95 router latency must stay under 30 seconds (in milliseconds) > tg endpoints rollout dep_target456 --canary \ > --metric router_latency --metric-stat p95 \ > --metric-threshold 30000 --metric-operator lt \ > --metric-window 300s > > # Regression check: p95 router latency at most 50% worse than the source > tg endpoints rollout dep_target456 --canary \ > --metric router_latency --metric-stat p95 \ > --metric-max-regression 50 --metric-direction higher-is-worse \ > --metric-window 300s > > # Ratio gate: omit --metric-stat (stored as AVG). Threshold is a 0-1 ratio (0.02 = 2%). > tg endpoints rollout dep_target456 --canary \ > --metric router_error_rate \ > --metric-threshold 0.02 --metric-operator lt \ > --metric-window 300s > ``` > > `--metric-stat` picks the aggregation the gate applies over the lookback window: a percentile (`p50`, `p90`, `p95`, or `p99`) or `avg`, the mean over the window. It is required for `router_latency` and optional for the other metrics, which only aggregate one way. > > See the [CLI reference](/reference/cli/endpoints#rollout) for the full flag list. > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint's **Rollouts** tab, select **New rollout**, and pick **Canary**. Under **Metric gates**, select **Add metric gate**, then set: > > 1. **Metric:** One of the [supported metrics](#supported-metrics): **Router latency**, **Router error rate**, or **Inflight requests**. > 2. **Aggregation:** For **Router latency**, pick Average or Percentile (when you pick Percentile, also set **Percentile** to p50, p90, p95, or p99). For **Router error rate** and **Inflight requests**, Average is the only aggregation. > 3. **Check:** **Threshold** (set **Operator** and **Threshold**) or **Regression vs. source** (set **Direction** and **Max regression (%)**). > 4. **Window (s):** Optional [lookback window](#choose-a-lookback-window) in seconds. Leave it blank to use the default. > > Select **Add metric gate** again to attach more rules. ## Threshold vs. regression checks Each gate uses one of the following checks to evaluate the target at the end of each soak window: * **Threshold check:** Compares the target against a fixed SLO, set with `--metric-threshold` and `--metric-operator` (`gt`, `gte`, `lt`, or `lte`). For example, "p95 router latency must stay under 30 seconds". * **Regression check:** Compares the target against the source, set with `--metric-max-regression` (a percent) and `--metric-direction` (`higher-is-worse` or `lower-is-worse`). It fails when the target is worse than the source by more than the allowed amount. For example, "the new deployment must not be more than 50% slower than the old one". ## Supported metrics The following metrics are supported (creating a rollout with any other metric name is rejected with a `400` error). All of them are measured at the router. | `--metric` | Type | What it measures | `--metric-stat` | | - | - | - | - | | `router_latency` | Histogram | Router per-attempt request duration, in milliseconds. Bimodal (the median attempt is often a fast reject), so gate on `p95` or higher rather than the mean. | Required: `avg` or a percentile | | `router_error_rate` | Ratio | Router 5xx responses divided by all inference responses. This is a ratio, so set the threshold as a 0-1 value, for example 0.02 for 2%. | Optional (stored as `AVG`) | | `inflight_requests` | Gauge | Concurrent requests, i.e. requests the router has sent to the deployment's replicas that haven't yet finished, averaged over the [lookback window](#choose-a-lookback-window). This is measured per ready replica, so make sure not to size your threshold against the fleet-wide total. | Optional (stored as `AVG`) | For regression checks, higher values are worse for all three metrics. ## Choose a lookback window `--metric-window` (CLI) or **Window (s)** (console) sets the lookback period over which the gate samples the metric. The minimum is `60s`. When omitted, it defaults to `300s` (five minutes). Use at least `300s` for `router_latency` percentile gates. A short window such as `60s` falls inside the metric pipeline's ingestion lag (about 90 seconds) and will likely hold too few samples for a trustworthy percentile, causing the rollout to pause unnecessarily. You don't need to size the step interval to fit the window: at create time, the platform grows each step's soak window to at least the metric window plus the ingestion lag, so the metric always has time to settle and accumulate samples before the target is evaluated. ## Gate on more than one rule The CLI configures a single-rule gate. To gate on several rules at once, add multiple gates in the console's **New rollout** dialog, or [create the rollout through the API](/reference/dmi/rollouts-create) and then [start it manually](/reference/dmi/rollouts-start). A step advances only when every rule passes. If any rule regresses or its metric is unavailable, the rollout pauses instead. You can attach both a threshold check and a regression check on the same metric. When you [retrieve the rollout](/docs/dedicated-endpoints/rollouts#monitor-progress), each configured rule appears as its own row in `status.steps[].metrics`, with its criteria and its own verdict. ## How gate results appear on retrieve Each metric row in `status.steps[].metrics` or `status.condition.metrics` is a `MetricResult` object containing the rule's name, check form, criteria, optional observed values, and a verdict (`PASS`, `BREACHED`, or `UNAVAILABLE`). * **Measured rows:** `targetValue` is set whenever the gate recorded an observation, including a legitimate `0`. `sourceValue` is set only on regression-check rows, because threshold checks never consult the source. * **Unmeasured rules:** When the gate couldn't measure a rule (for example, no traffic reached the target), the rule still appears as a row with verdict `UNAVAILABLE` and its criteria, but no `sourceValue` or `targetValue`. * **Completed rollouts:** A `COMPLETED` rollout never marks a step as `FAILED`. Finished steps are `PASSED`, and steps a promote jumped over are `SKIPPED`. For the full per-step state set, see [Step status on retrieve](/docs/dedicated-endpoints/rollouts#step-status-on-retrieve). ## What to do when a metric gate fails If a metric gate fails (the target deployment doesn't meet the gate's threshold or regression criteria), the rollout pauses automatically. The traffic split that's in place when the gate fails is maintained while the rollout is paused. Review the gate verdicts for each completed step by [retrieving the rollout](/docs/dedicated-endpoints/rollouts#monitor-progress), or open the **Rollout details** drawer from the progress card or history table in the console. The pause reason (shown on the paused rollout and on its `rollout.system_paused` [event](/docs/dedicated-endpoints/monitoring#events)) starts with one of two prefixes: * **`metrics-regression:`** The gate confirmed the target is worse than the gate's criteria allow. The rest of the reason names the failing rule and the observed values. Investigate why the target regressed before acting. If the target itself is at fault, cancel the rollout, then [run it in reverse](/docs/dedicated-endpoints/rollouts#roll-back-to-the-source) to move traffic back to the source. If the cause was external (like a traffic surge), resume instead. * **`metrics-unavailable:`** The gate could not get a trustworthy reading, so it paused rather than advancing on incomplete data. Common causes are gaps in the metrics pipeline (the most common), too few samples in the [lookback window](#choose-a-lookback-window), and zero ready replicas on the target or source. Most of these are transient—the platform confirms the reading before pausing and [retries automatically](/docs/dedicated-endpoints/rollouts#troubleshooting). Resume the rollout manually if the pause persists. The paused step's metrics include an `UNAVAILABLE` row for each rule the gate could not measure. See [Troubleshooting rollouts](/docs/dedicated-endpoints/rollouts#troubleshooting) for more details on how to respond to each failure condition. ## Next steps > [card] [Start a rollout](/docs/dedicated-endpoints/rollouts) > > Create and run the canary rollout a gate protects. > [card] [Observability](/docs/dedicated-endpoints/monitoring) > > Watch the same metrics on your endpoint's dashboards. # Start a rollout Source: https://docs.together.ai/docs/dedicated-endpoints/rollouts Shift traffic to a new deployment on the same endpoint. A rollout moves traffic from one deployment to another under the same endpoint, without changing the endpoint URL. Traffic shifts to the new deployment (the *target*) while the old one (the *source*) drains. For example: ```bash theme={null} tg endpoints rollout dep_target456 \ --source dep_source123 \ --rolling ``` > [!NOTE] > > The CLI examples on this page use these placeholders, which you should replace with your own endpoint/deployment IDs: > > * Endpoint: `ep_abc123`. > * Source deployment: `dep_source123`. > * Target deployment: `dep_target456`. ## When to use rollouts Use a rollout instead of editing the [traffic split](/docs/dedicated-endpoints/route-traffic) by hand when you're migrating a deployment on live traffic. Rollouts are especially useful when you want to: * **Ship a new model version or engine config:** Canary rollouts shift traffic gradually from the old deployment to the new one, allowing you to monitor the new deployment's performance before fully committing to it. * **Validate a change under production traffic:** Use [metric gates](/docs/dedicated-endpoints/rollout-metric-gates) to pause the rollout automatically when the new deployment is worse than the original. * **Recover from a bad release:** Canceling freezes traffic where it is, allowing you to walk the change back safely with a [reverse rollout](#roll-back-to-the-source). * **Keep a record of the migration:** Each rollout records its steps, state changes, and pause/cancel reasoning in the endpoint's [rollout history](#monitor-progress). For a one-off comparison between two deployments, use an [A/B test](/docs/dedicated-endpoints/ab-tests) or a [shadow experiment](/docs/dedicated-endpoints/shadow-experiments) instead. ## Requirements A rollout needs two eligible deployments under the same endpoint: * **Source:** The deployment you're migrating away from. The source must: * Be in the `READY` [deployment state](/docs/dedicated-endpoints/manage#deployment-states), or in the `SCALING` state with at least one ready replica and a ready routing tier. * Have a positive weight in the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic). A rollout shifts only the source's share of the traffic. Any other deployments in the split keep serving their shares, and the target takes over the source's slot when the rollout completes. * Not be part of a [shadow experiment](/docs/dedicated-endpoints/shadow-experiments) or [A/B test](/docs/dedicated-endpoints/ab-tests). * **Target:** The deployment you're rolling out to. The target must: * Be in the `READY`, `STOPPED`, or `SCALING` [deployment state](/docs/dedicated-endpoints/manage#deployment-states). The rollout restarts a stopped target when it scales it up. * Not be receiving 100% of the traffic on the endpoint. * Not be part of a [shadow experiment](/docs/dedicated-endpoints/shadow-experiments) or [A/B test](/docs/dedicated-endpoints/ab-tests). * Belong to a project in good billing standing. Each deployment must be in one of its allowed states when you create the rollout and again when you start it. A deployment with a stop in progress doesn't qualify, whatever its state. If either deployment is still `SCALING` when the rollout starts, the first traffic shift waits until that deployment has enough ready replicas. If that doesn't happen within 30 minutes, the rollout pauses with [`UNDER_SERVED`](#troubleshooting). > [!TIP] > > Pass `--detach` when [starting the rollout](#start-a-rollout) to detach the target from its experiment automatically. `--detach` covers only the target, so detach a source from its experiment yourself before you start the rollout. Make sure enough hardware is available for the [rollout strategy](#choose-a-rollout-strategy) and final target size you choose. To check, [retrieve the per-region `headroom` value](/docs/dedicated-endpoints/configs#instance-types-and-capacity) for the target's instance type. ## Choose a rollout strategy The rollout strategy you choose determines how traffic moves from the source deployment to the target. Pick exactly one strategy per rollout: ![Comparison of the canary, blue-green, and rolling rollout strategies. Canary ramps traffic to the new deployment in gated steps (10 to 50 to 100 percent); blue-green cuts over in a single gated step (0 to 100 percent); rolling swaps replicas one in, one out while keeping total capacity constant. Orange represents traffic on the new deployment.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/rollout-strategies.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=805030ba9d7e8d8ff02e8db5a608c176) During a rollout, the source and target deployments will run at the same time while traffic shifts, so you'll be [billed for both](/docs/dedicated-endpoints/pricing). The amount of extra capacity the overlap requires depends on the strategy (see **Extra capacity** in the table below). | | **Canary** | **Blue-green** | **Rolling** | | - | - | - | - | | **Traffic pattern** | Shifts traffic to the target in steps: by default 5%, then 25%, 50%, and 100%. After each step, the rollout holds traffic steady for a soak period so the new deployment can prove itself, optionally checked by a [metric gate](/docs/dedicated-endpoints/rollout-metric-gates) that pauses the rollout if the new deployment is worse than the original. | Moves all traffic to the target in one step, as soon as the target is ready. **The fastest option.** | Swaps replicas one batch at a time: a new replica comes up, then an old one shuts down. **The slowest option.** | | **Extra capacity** | The target scales up and the source scales down as traffic moves, so the combined replica count stays close to the source's original size. | The target scales to full size before the cutover, so the endpoint briefly runs both deployments at full size (roughly double its usual replica count) until the source drains. **The most expensive option.** | Replicas swap from source to target one by one, keeping the combined count essentially constant. **The cheapest option.** | | **Completion** | Completes after the final step's soak passes. Pass [`--promote`](#promote-a-rollout) to finish early. | Completes once the cutover stabilizes. | Completes when every replica batch has been swapped. | | **Best for** | Gradual, [metric-gated](/docs/dedicated-endpoints/rollout-metric-gates) exposure. The safest option for production traffic. | One quick switch, when you can afford to run both deployments at full size while it happens. | Keeping your total GPU capacity constant during the swap. | ## Start a rollout > [tab] CLI > > To start a rollout, run the `rollout` command, passing the target deployment (ID or name) and a strategy flag. The command creates the rollout and starts shifting traffic from the source to the target. Before you run it, check the following: > > * **Source:** The deployment currently serving the traffic you're migrating. It must be referenced in the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic), which is automatic on a single-deployment endpoint. If the source isn't referenced in the traffic split, the rollout still starts but doesn't shift any traffic. > * **Target:** The new deployment you're rolling out to. It doesn't need to be `READY` yet. The rollout scales up a `STOPPED` or `SCALING` target and waits for its replicas before it shifts traffic. A `READY` target starts fastest. > * **Inactivity timeouts disabled:** Neither deployment can have an [inactivity timeout](/docs/dedicated-endpoints/scaling#automatic-idle-shutdown) enabled. A deployment that stops automatically when idle can't also carry a rollout, so create rejects the pair and names the offending deployment. Set the timeout to `0` on both, and turn it back on after the rollout completes. > * **Billing standing:** The target deployment's project must be in good billing standing to create the rollout, start it, and keep scaling the target up during the run. If billing lapses mid-run, the rollout pauses with `ENTITLEMENT_LAPSED` before the next target scale-up. Scale-downs and recovery actions, such as [canceling the rollout](#manage-a-running-rollout), aren't blocked. > > See the [CLI reference](/reference/cli/endpoints#rollout) for the full flag list. > > ### Canary > > Pass `--canary`. To customize the ladder, set the traffic percentages with `--steps` and the soak between steps with `--interval`: > > ```bash theme={null} > # Canary with the default ladder (5%, 25%, 50%, 100%) > tg endpoints rollout dep_target456 --canary > > # Canary with a custom ladder > tg endpoints rollout dep_target456 \ > --canary \ > --steps 25,50,75,100 \ > --interval 300s > ``` > > If the target is already serving some traffic (for example, after a [canceled rollout](#cancel-a-rollout)), your custom ladder must start above the share the target is already serving. When in doubt, omit `--steps` and the platform picks steps that fit the live traffic. > > You can also configure a canary rollout to evaluate live metrics after each step, pausing automatically instead of advancing when the target regresses. Attach a [metric gate](/docs/dedicated-endpoints/rollout-metric-gates) with the `--metric*` flags: > > ```bash theme={null} > # Pause the rollout if p95 router latency exceeds 30 seconds (in milliseconds) > tg endpoints rollout dep_target456 --canary \ > --metric router_latency --metric-stat p95 \ > --metric-threshold 30000 --metric-operator lt \ > --metric-window 300s > ``` > > ### Blue-green > > Pass `--blue-green`: > > ```bash theme={null} > tg endpoints rollout dep_target456 \ > --source dep_source123 \ > --blue-green > ``` > > ### Rolling > > Pass `--rolling`: > > ```bash theme={null} > tg endpoints rollout dep_target456 --rolling > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint and select the **Rollouts** tab, then select **New rollout**. If the endpoint has no eligible source and target pair, **New rollout** is disabled. The tab then names the role no deployment can fill and lists why each deployment can't fill it. > > In the dialog: > > 1. Select the **Source deployment** and the **Target deployment**. Each list shows only the deployments whose state and inactivity timeout let them fill that role. > > After you select both, the dialog warns you if anything about your setup would prevent the rollout from being created or started. > 2. Select a **Strategy**: **Canary**, **Blue-green**, or **Rolling**. The console defaults to canary. > 3. For a canary rollout, leave **Canary steps** on **auto** to let the platform pick the steps, or switch it to **custom** to set the traffic percentages and, optionally, the **Step interval (seconds)** yourself. Each step sets only a traffic percentage, and the rollout sizes the step's replicas itself. > 4. Optionally set **Final target replicas**. Leave it empty to use the platform's default, shown in the field's placeholder. > 5. For a canary rollout, optionally select **Add metric gate** to add a [metric gate](/docs/dedicated-endpoints/rollout-metric-gates), then set its [metric, aggregation, check, and window](/docs/dedicated-endpoints/rollout-metric-gates#configure-a-metric-gate). > 6. Leave **Start immediately** on and select **Start rollout** to begin shifting traffic right away, or turn it off and select **Create rollout** to create a pending rollout you start later. ## Monitor progress > [tab] CLI > > Retrieve the rollout with `get`, passing the rollout ID (`rol_...`) printed under **Active Rollout** when you started it. You can also pass the endpoint ID to print the endpoint summary, which includes the active rollout's ID, state, strategy, and progress. > > ```bash theme={null} > # Rollout detail: state, strategy, step progress, traffic percent > tg endpoints get rol_abc123 > > # Endpoint summary with the active rollout's state and progress > tg endpoints get ep_abc123 > ``` > > To follow traffic-split transitions event by event, list the endpoint's [events](/docs/dedicated-endpoints/monitoring#events) with `--subject-id` set to the rollout ID. Traffic-shift rows include `old_traffic_percent` and `new_traffic_percent`. > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > When a rollout is active, your endpoint's **Overview** and **Rollouts** tabs show a rollout progress card with the strategy, the source and target names, a progress bar with the current step and the percentage of traffic on the target, and the lifecycle controls for the current state. While the next traffic shift waits for replicas to become ready, the card shows whether it's waiting for source replicas, target replicas, or both. > > The **Rollouts** tab also has a history table that lists every rollout with its state and dates. To open the **Rollout details** drawer, select a row in the history table or the details control on the progress card. > > The drawer shows the rollout's timing, each step's progress and state, and the verdict for each metric gate: **Pass**, **Breached**, or **No data** when the gate couldn't take a reading. While the rollout is running, the drawer refreshes automatically. For the same information over the CLI or API, see [Step status on retrieve](#step-status-on-retrieve) and [How gate results appear on retrieve](/docs/dedicated-endpoints/rollout-metric-gates#how-gate-results-appear-on-retrieve). > > To follow traffic-split transitions event by event, open the endpoint's **Logs** tab. It shows the same events as the CLI and API, including traffic-shift percentages for canary steps. ### Step status on retrieve When you retrieve a rollout, `status.steps` lists one row per step with its `state`: | `state` | Meaning | | - | - | | `PASSED` | The step finished. `completed_at` is when it did. | | `RUNNING` | The step currently in progress. | | `PAUSED` | The step the rollout is paused on. Resuming continues from here. The pause cause is on the rollout (`pause_info` or `status.condition`), not on the step. | | `CANCELED` | The step the rollout was canceled on. `completed_at` is set once the cancellation finishes. | | `SKIPPED` | The rollout never completed the step. Either a promotion jumped over it or a cancellation ended the rollout before it could run. | | `FAILED` | The step failed. `failure_reason` carries the cause when one was recorded. | | `PENDING` | Not reached yet. | `started_at` is set only when the step actually ran. ## Manage a running rollout You can pause, resume, promote, and cancel a rollout using the CLI or console. An endpoint has at most one active rollout, so the CLI accepts any of these identifiers: the endpoint or deployment ID or name, or the rollout ID (`rol_...`). ### Pause and resume > [tab] CLI > > To manually pause a rollout, pass `--pause` (and optionally a reason). You can resume it later with `--resume`: > > ```bash theme={null} > # Pause > tg endpoints rollout ep_abc123 --pause --reason "holding for review" > > # Resume > tg endpoints rollout ep_abc123 --resume > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint's **Rollouts** tab and select **Pause** on the active rollout card. To continue a paused rollout (including one the platform paused), select **Resume**. > [!NOTE] > > The platform may pause a rollout automatically, which sets the [rollout state](#rollout-states) to `SYSTEM_PAUSED` (for example on a failed [metric gate](/docs/dedicated-endpoints/rollout-metric-gates) or when capacity runs out). See [Troubleshooting](#troubleshooting) for the pause causes and how to respond to each. ### Promote a rollout > [tab] CLI > > To promote a rollout, immediately shifting all traffic to the target, pass `--promote`: > > ```bash theme={null} > # Promote > tg endpoints rollout ep_abc123 --promote > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint's **Rollouts** tab and select **Promote** on the active rollout card to move all traffic to the target immediately. ### Cancel a rollout Canceling a rollout freezes the current [traffic split](/docs/dedicated-endpoints/route-traffic) wherever it is. Both deployments keep the weights that were serving at cancel time. A target that isn't serving traffic may be left at weight `0` or removed from the split. After the cancellation completes, both deployments keep serving at those frozen shares (rollout events describe this as traffic frozen at the current split). This leftover state, the *frozen pair*, keeps serving until you either [edit the traffic split](/docs/dedicated-endpoints/route-traffic) to put all traffic on one deployment or [run the rollout in reverse](#roll-back-to-the-source). > [!NOTE] > > Canceling before any traffic has shifted (a 0% split) leaves the target deployment running with no traffic. If you no longer need the target, scale it to zero or delete it once the cancellation is finished. > [tab] CLI > > To cancel a rollout, pass `--cancel` and optionally a reason: > > ```bash theme={null} > # Cancel > tg endpoints rollout ep_abc123 --cancel --reason "latency regression on target" > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint's **Rollouts** tab and select **Cancel** on the active rollout card. Enter a reason in the dialog, then select **Cancel rollout**. ## Roll back to the source There is no separate rollback operation. To move traffic back, [run another rollout](#start-a-rollout) with the roles reversed. ### After a completed rollout This works like any other rollout. The deployment now serving traffic becomes the source, and the old source is the target (any stopped deployment is an eligible target for the new rollout). ### After a canceled rollout If you canceled a rollout and the endpoint is still serving from the frozen pair, roll back by running a new rollout with the roles reversed. Any strategy works. The platform adapts the rollout to the frozen state: * **Replica counts:** `--final-target-replicas` defaults to the pair's combined replica count (the capacity serving all of the endpoint's traffic today), not only the source's count. * **Canary steps:** For a canary, the default ladder skips the steps the new target has already passed. For example, if the cancel froze the target at 40%, the rollout runs only the 50% and 100% steps. A custom ladder must start above the frozen share, the same rule as when [starting any canary](#canary). ## Delete a rollout You can delete a rollout that hasn't started yet or has finished (completed or canceled). Deleting the rollout record doesn't change the traffic split it left behind. To stop serving both deployments of a [frozen pair](#cancel-a-rollout), [edit the traffic split](/docs/dedicated-endpoints/route-traffic) so one deployment carries all of the traffic, then scale the other to zero if you no longer need it. > [tab] CLI > > Use `rm` to delete a rollout, passing the rollout ID (`rol_...`): > > ```bash theme={null} > tg endpoints rm rol_abc123 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > Open your endpoint's **Rollouts** tab and select **Delete** in the rollout's actions menu in the history table. ## Rollout states A rollout can pass through the following states: | State | Meaning | | - | - | | `PENDING` | Created but not yet started. | | `RUNNING` | Actively shifting traffic. | | `STABILIZING` | Holding at a step's traffic level before moving to the next. | | `PAUSING` | Pause accepted. The current step may still finish before the rollout is fully paused. | | `PAUSED` | Paused by the operator. The current split is held until you resume or cancel. | | `SYSTEM_PAUSED` | Paused by the platform. Recoverable pauses may auto-resume. See [Troubleshooting](#troubleshooting). | | `CANCELLING` | Cancel accepted. The current split keeps serving while the freeze is in progress. | | `CANCELED` | Terminal. The current split is frozen into the endpoint's standing traffic split at cancel time. | | `COMPLETED` | Terminal. All traffic has been shifted to the target. | ## Limitations While a rollout is in any non-terminal [state](#rollout-states) (including `PENDING` and paused rollouts), it locks the endpoint resources it depends on: * **Traffic split edits are blocked:** Editing the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic) returns a `409` until the rollout completes, is canceled, or is deleted. To check for an active rollout before editing, retrieve the endpoint: get, update, and list responses include the active rollout's ID as `activeRolloutId` (omitted when there is none). * **One active rollout per endpoint:** Creating a second rollout returns a `409`, and the error names the rollout that blocks it and its state. A `PENDING` rollout left behind by a failed start also occupies the slot. * **The source and target can't be stopped or deleted:** Deleting either deployment returns a `409`, and stopping one returns a `400`. The console disables **Stop** and **Delete** on both deployments, along with the endpoint's **Stop all deployments**. * **The source and target can't join experiments:** A deployment can only serve one traffic role at a time, so adding either deployment to a [shadow experiment](/docs/dedicated-endpoints/shadow-experiments) or [A/B test](/docs/dedicated-endpoints/ab-tests) is rejected while the rollout is active. * **Replica bounds stay editable, with one caveat:** Lowering the target's `--max-replicas` below what the current rollout step requires pauses the rollout with a [`POLICY_INFEASIBLE`](#troubleshooting) error. ## Troubleshooting When the platform pauses a rollout (`SYSTEM_PAUSED`), the rollout's `status.condition` carries a typed `category` and a human-readable `message`. > [!NOTE] > > Recoverable pauses often clear on their own. The platform retries the failed process every 15 minutes for up to three hours, then leaves the rollout paused for you to act on. Operator pauses (`PAUSED`) never auto-resume. | Category | Meaning | Typical action | | - | - | - | | `METRIC_REGRESSION` | A [metric gate](/docs/dedicated-endpoints/rollout-metric-gates) detected the target is worse than the source. | Investigate why the target regressed before acting. A bad release calls for a cancel and a [reverse rollout](#roll-back-to-the-source), but an external cause (like a traffic surge) may only need a resume. | | `METRICS_UNAVAILABLE` | The gate could not collect enough samples. The most common cause is an outage in the platform's metrics pipeline. | Wait for the metrics pipeline to recover. The platform may auto-retry. Resume manually if the pause persists. | | `TARGET_NOT_READY` | The target deployment did not become ready in time. | Investigate the target deployment. The platform may auto-retry. Resume or cancel if the pause persists. | | `HEALTH_REGRESSION` | A health check failed during the soak window (the waiting period after each step). | Investigate the failed check before acting. Cancel and [run a rollout in reverse](#roll-back-to-the-source) if the target is at fault, or resume if the cause was external. | | `CAPACITY_EXHAUSTED` | The Together AI GPU fleet does not have enough capacity for the requested replicas. | Wait for capacity. The platform may auto-retry. Resume if the pause persists. | | `ROUTING_ERROR` | The routing tier stopped serving during the soak window. | Wait for the routing tier to recover. The platform may auto-retry. Resume if the pause persists. | | `POLICY_INFEASIBLE` | The target's max replicas is below what the current step needs. This usually follows a mid-run edit to the target's max replicas. | Raise the [max replicas](/docs/dedicated-endpoints/scaling#replica-bounds) bound, then resume. A rollout can't be edited after creation, so to lower its final target replicas instead, cancel and recreate it. | | `UNDER_SERVED` | A deployment doesn't have enough ready replicas for the current traffic split, or didn't reach the replicas the next step needs within 30 minutes. | Restore capacity or reduce the split. The platform may auto-retry. Resume if the pause persists. | | `ENTITLEMENT_LAPSED` | The target project's billing standing failed the entitlement check before a target scale-up. | Resolve the billing issue. The platform may auto-retry. Resume or cancel if the pause persists. | | `INTERNAL` | An unexpected platform error. | Contact support with the rollout ID and `message`. | Other common issues and their fixes: * **New replicas are slow to take on traffic:** Each step brings up new replicas, each of which requires a [cold start](/docs/dedicated-endpoints/concepts#cold-starts). For canary rollouts, set the [`--interval`](/reference/cli/endpoints#rollout) long enough for the replica to warm up before the gate starts sampling. * **Create or start returns `409`:** The error message names the rollout or deployment that blocks it. If it names a rollout, the endpoint already has an active one, so finish or cancel it before you create another. If it names a deployment, that deployment either has a stop in progress or is in a state that doesn't allow a rollout. Wait for it to reach one of the states listed in [Requirements](#requirements). A source that finishes stopping stays ineligible until you restart it. * **Preview warns with `START_WILL_REJECT`:** The rollout can be created, but starting it would fail while the deployments keep their current traffic shape (for example, the target already serves the pair's whole share). Follow the fix in the warning message, then start the rollout again. * **Create returns `400`, or preview warns with `FIRST_STEP_AT_SEED`, for a custom canary ladder:** The ladder's first step is at or below the share of traffic the target already serves. Create rejects a first step below that share. Preview warns when the first step exactly equals it. In that case, creating may work, but starting can still fail. Raise the first step above the target's share, or omit `--steps` (leave **Canary steps** on **auto** in the console) so the platform picks steps that fit. * **Create returns `400` for a metric gate:** The gate's threshold or regression budget could never pass, or could never fail, so the gate would be meaningless. Fix the operator and value so a realistic reading can pass and a bad one can fail. See [Supported metrics](/docs/dedicated-endpoints/rollout-metric-gates#supported-metrics) for each metric's unit. * **Preview shows a landing max above the target's current max replicas:** The rollout raises the target's max replicas to cover the larger of the two deployments (or `--final-target-replicas`, if higher), so the target can hold the endpoint's whole traffic. The raised bound stays after the rollout ends, so lower it afterward if you don't want to keep it. * **Target scales down after the rollout completes:** `--final-target-replicas` sets how many replicas the target runs at cutover, not a standing floor. After the rollout completes, the target's autoscaling policy takes over and scales it from the cutover count to what your traffic needs, so a rollout created at peak load doesn't keep its peak replica count. The target scales no lower than its own [min replicas](/docs/dedicated-endpoints/scaling#replica-bounds), or the source's min replicas if the target started stopped. Preview reports this floor as the landing minimum. * **Preview warns with `LANDING_MIN_ABOVE_CUTOVER`:** The target started stopped, so it inherits the source's min replicas, and your `--final-target-replicas` is below that min. After the rollout completes, the autoscaler scales the target up from the cutover count to the source's min. To land at the cutover count instead, lower the source's min replicas before you start the rollout. * **Updating the traffic split returns `409`:** The rollout controls the endpoint's traffic split in every non-terminal state (including pending or paused). Complete, cancel, or delete the rollout before editing traffic weights. In the console, **Traffic weight** is also disabled on **New deployment** and **Edit** while a rollout is active. * **Stop or delete is disabled on a deployment in the console:** The deployment is the source or target of an active rollout. Complete or cancel the rollout first. **Stop all deployments** on the endpoint is also disabled while any rollout is active. * **Create returns a `400` that names a shadow experiment target:** The source or target is registered as a [shadow experiment](/docs/dedicated-endpoints/shadow-experiments) target. Pass `--detach` to detach a shadow or A/B target automatically. A shadow source must be removed by hand. * **`rollout` reports `Created rollout ... but failed to start it`:** Creation succeeded but the start call failed, so a `PENDING` rollout now occupies the endpoint's single active-rollout slot. Run the cleanup command the CLI prints (`tg endpoints rm rol_...`), fix the underlying cause, then create the rollout again. * **An error says the project `is not in good standing`:** The target deployment's project failed the billing check, which runs when you create a rollout, when you start it, and before each step scales up the target. A failure before a scale-up pauses the rollout with `ENTITLEMENT_LAPSED`. Resolve the billing issue on the project, then retry or resume. * **An error says only `internal error` or `Failed Precondition`:** Some platform failures surface as a generic message with no further detail. Contact support with the rollout ID and the time of the failure. ## Next steps > [card] [Gate rollouts with metrics](/docs/dedicated-endpoints/rollout-metric-gates) > > Pause a canary automatically when the target regresses on live metrics. > [card] [Create a deployment](/docs/dedicated-endpoints/manage#create-a-deployment) > > Create the source and target deployments a rollout shifts between. # Overview Source: https://docs.together.ai/docs/dedicated-endpoints/route-traffic Route traffic to a deployment, and explore strategies that change how traffic moves over time. After you create a deployment, you still need to route traffic to it before it can receive requests (even if it's marked `READY`). ## Basic routing The simplest routing method is to assign each deployment a weight in the endpoint's traffic split. Each deployment's share of traffic is proportional to its capacity (its weight times its number of ready replicas), so traffic follows both the weights you assign and how each deployment is scaled. When the CLI's `deploy` creates a deployment, it routes 100% of traffic to it automatically. To change an existing split, set a deployment's weight with `endpoints update --traffic-weight`. Pass the deployment ID (`dep_...`), and the CLI resolves its parent endpoint and preserves the weights of the other deployments. For a single deployment, any non-zero weight routes all traffic to it: ```bash Shell theme={null} tg endpoints update dep_abc123 --traffic-weight 1 ``` Each weight must be non-negative and finite. ## Remove a deployment from the traffic split To stop routing traffic to a deployment without rebalancing the rest of the split, set its weight to `0`. Setting a deployment's weight to `0` will remove it from the split entirely, while preserving the weights of the other deployments. The deployment keeps running, so you can scale it up or bring it back into rotation later by setting a non-zero weight again. > [tab] CLI > > For example, to remove `dep_def456` while leaving the other deployments untouched: > > ```bash Shell theme={null} > tg endpoints update dep_def456 --traffic-weight 0 > ``` > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > On the endpoint's **Overview** tab, select **Edit traffic weights**, set the deployment's weight to `0`, and select **Save changes**. You can also open the deployment, select **Edit** on the **Deployment configuration** card, set **Traffic weight** to `0`, and select **Save changes**. While a [rollout](/docs/dedicated-endpoints/rollouts) is active, those controls are unavailable until you complete or cancel the rollout. ## Routing strategies To run several deployments behind one endpoint, or to change how traffic moves between them over time, use one of these strategies: > [card] [Split traffic](/docs/dedicated-endpoints/split-traffic) > > Run multiple deployments on one endpoint and divide requests between them by weight. > [card] [Rollouts](/docs/dedicated-endpoints/rollouts) > > Shift traffic from one deployment to another in controlled, gated steps. > [card] [A/B tests](/docs/dedicated-endpoints/ab-tests) > > Hold a fixed control/variant split and compare candidates on live traffic. > [card] [Shadow experiments](/docs/dedicated-endpoints/shadow-experiments) > > Mirror a sampled fraction of traffic to a target without affecting responses. ## How routing works The endpoint directs each request to a single deployment through a series of sampling decisions: 1. **Traffic split:** Among the deployments in the endpoint's traffic split, the endpoint samples a candidate in proportion to its capacity (weight times ready replicas). 2. **A/B test:** If the candidate is the control of an [A/B test](/docs/dedicated-endpoints/ab-tests), the endpoint re-samples from among the control and its variants by the percentages you set for the test. 3. **Route:** The endpoint sends the request to a cluster within the final deployment. ```mermaid theme={null} flowchart TB Req["Request"] --> S1["Traffic split
sample by capacity"] S1 --> Q1{"Candidate is an
A/B control?"} Q1 -->|" YES "| S2["A/B test
re-sample by percent"] Q1 -->|" NO "| S4 S2 --> S4["Route to a cluster
in the final deployment"] classDef client fill:#b65a7c,stroke:#76374d,stroke-width:1.5px,color:#ffffff; classDef endpoint fill:#fc4c02,stroke:#b83702,stroke-width:1.5px,color:#ffffff; classDef deployment fill:#7f6caa,stroke:#50426e,stroke-width:1.5px,color:#ffffff; classDef decision fill:#cbd5e1,stroke:#64748b,stroke-width:1.5px,color:#132133; class Req client; class S1,S2 endpoint; class S4 deployment; class Q1 decision; ``` [Shadow experiments](/docs/dedicated-endpoints/shadow-experiments) sit outside this path, copying a sampled fraction of traffic to a target for observation without changing which deployment serves the response. ## Stickiness Routing is deterministic per request, not randomly drawn each time. The endpoint derives a **sampling key** from each request and always routes requests with the same key to the same deployment. Across many distinct keys, traffic still splits according to each deployment's capacity, but any single key stays pinned to one deployment while the traffic split is stable. **This is how the endpoint keeps prompt caches warm**. When the follow-up requests in a conversation land on the same replica that served the earlier ones, the cached prompt prefix is reused, lowering latency and cost. Purely random routing would scatter those requests across deployments, discarding the cache. The endpoint picks the sampling key from the request in this order: 1. The request's `prompt_cache_key` field, if set. 2. Otherwise, the `user` field, if set. 3. Otherwise, a key derived from the request content. To control stickiness yourself, set `prompt_cache_key` on requests that share a prompt prefix (for example, every turn of one conversation) so they route together. > [!NOTE] > > Stickiness is maintained as long as the traffic split is stable. When the routing changes (you edit weights or add/remove a deployment), some keys are reassigned to a different deployment. # Configure autoscaling Source: https://docs.together.ai/docs/dedicated-endpoints/scaling Autoscale a deployment between replica bounds, pick the right scaling metric, and stop idle deployments automatically. Configure your deployment to scale automatically by setting limits on how many replicas it can run. You set the minimum and maximum replica count, and the platform autoscales between those bounds based on a metric that you choose. ## Replica bounds A *replica* is one instance of your model running on its own hardware. Adding more replicas raises the aggregate requests per second that a deployment can serve, and also adds redundancy in case a single replica fails. Two parameters control the number of replicas that a deployment can run: * **`minReplicas`:** The floor. The deployment never scales below this. On a running deployment, it must be at least `1`. * **`maxReplicas`:** The ceiling. Caps how far the deployment scales up, which determines the deployment's maximum cost. You can set both at [creation time](/docs/dedicated-endpoints/manage#create-a-deployment) with the CLI's `tg endpoints deploy --min-replicas`/`--max-replicas`. To update the bounds on a running deployment, pass the deployment ID (`dep_...`) to `tg endpoints update`. The CLI resolves its parent endpoint automatically: ```bash CLI theme={null} tg endpoints update dep_abc123 \ --min-replicas 1 \ --max-replicas 4 ``` Setting `minReplicas` equal to `maxReplicas` fixes the size of the deployment and disables autoscaling. Setting both to `0` stops the deployment. A `minReplicas` of `0` paired with a positive `maxReplicas` is rejected. An active [rollout](/docs/dedicated-endpoints/rollouts) also holds a replica floor for each deployment for its current step. If you lower `maxReplicas` below what the rollout's current step requires, the rollout pauses until you restore a compatible replica bound. ## Enable autoscaling To enable autoscaling, set `minReplicas` to less than `maxReplicas`. With a range set but no metric specified, the platform applies a default scaling metric (concurrent in-flight requests per replica), so you can enable autoscaling without first choosing a metric or target. To scale on a specific metric, pass `--scaling-metric` and `--scaling-target` together. A deployment scales on a single metric, so you set exactly one. Choose the metric when you first deploy: ```bash CLI theme={null} tg endpoints deploy zai-org/GLM-5.2 \ --endpoint my-glm-endpoint \ --min-replicas 1 \ --max-replicas 4 \ --scaling-metric gpu_utilization \ --scaling-target 70 ``` You can also set or change the metric later on a running deployment. Pass the deployment ID (`dep_...`). With the Python SDK, use snake\_case field names and set the metric target `type` explicitly: ```bash CLI theme={null} tg endpoints update dep_abc123 \ --min-replicas 1 \ --max-replicas 4 \ --scaling-metric gpu_utilization \ --scaling-target 70 ``` ```python Python theme={null} from together import Together client = Together() identity = client.whoami() if identity.type != "project_api_key": raise RuntimeError("TOGETHER_API_KEY must be a project API key") project_id = identity.project.id deployment = client.endpoints.deployments.update( "dep_abc123", project_id=project_id, endpoint_id="ep_abc123", autoscaling={ "min_replicas": 1, "max_replicas": 4, "scaling_metrics": [ { "name": "gpu_utilization", "target": 70, "type": "METRIC_TARGET_TYPE_UTILIZATION", } ], }, ) ``` The SDK converts the snake\_case fields above to the API's camelCase fields. You can pass the same `autoscaling` object to `client.endpoints.deployments.create`. For create requests, `model` and `config` must be fully qualified resource names, such as `projects/{project_id}/models/{model_id}` and `projects/{project_id}/configs/{config_id}`. See the [create deployment](/reference/dmi/deployments-create) and [update deployment](/reference/dmi/deployments-update) API references. ## Scaling metrics `--scaling-metric` accepts one of nine metrics, and `--scaling-target` sets the threshold the platform holds it near. The unit of the target depends on the metric: | Metric (`--scaling-metric`) | What `--scaling-target` sets | | - | - | | `inflight_requests` | Concurrent in-flight requests per replica. The default metric. The target is `8` when no metric is specified. Works for LLM engines and TTS handlers. | | `active_sessions` | Concurrent open client WebSocket sessions per replica on a TTS deployment. Accepts `AVERAGE_VALUE` only. | | `gpu_utilization` | GPU compute utilization, as a percentage (`0`–`100`). | | `token_utilization` | KV-cache utilization, as a percentage (`0`–`100`). | | `cache_hit_rate` | Prompt-cache hit rate, as a percentage (`0`–`100`). | | `throughput_per_replica` | Tokens generated per second, per replica. | | `ttft` | Time to first token, in milliseconds. | | `decoding_speed` | Time per output token, in milliseconds. | | `e2e_latency` | End-to-end request latency, in milliseconds. | The target is interpreted in one of three ways, depending on the metric: * **Utilization** (`gpu_utilization`, `token_utilization`, `cache_hit_rate`): an average percentage across all replicas, from `0` to `100`. `gpu_utilization` with `--scaling-target 70` holds GPU utilization near 70%. * **Average value** (`inflight_requests`, `active_sessions`, `throughput_per_replica`): an average value across all replicas. `inflight_requests` with `--scaling-target 16` aims for about 16 concurrent requests per replica. `active_sessions` with `--scaling-target 4` aims for about four open WebSocket sessions per replica. * **Absolute value** (`ttft`, `decoding_speed`, `e2e_latency`): a value across the whole deployment, measured at a percentile. `e2e_latency` with `--scaling-target 2000` targets a p95 of 2000 ms (2 seconds). [See below](#how-latency-is-calculated) for details. > [!WARNING] > > The per-token metrics `throughput_per_replica`, `ttft`, and `decoding_speed` are recorded only for streaming responses. When scaling on one of these metrics, make sure to send [streaming requests](/docs/inference/chat/overview#stream-responses) (`"stream": true`), or the deployment won't scale correctly. (`e2e_latency` is the exception: it's measured for both streaming and non-streaming traffic.) ### Choose a metric The nine metrics fall into three families. Which one fits depends on what you want to protect the deployment against. * **Concurrency-driven (`inflight_requests`, `active_sessions`) is the safe default:** In-flight count is a *leading* indicator: it rises when demand outpaces service, but before latency visibly degrades. It needs no streaming and no percentile choice, and it maps directly onto how inference engines batch requests. A target of `8` says "hold each replica at about eight concurrent requests." Raise it for short-prompt chat workloads that batch well, and lower it for long-context traffic (like coding agents) that spends longer in prefill. For TTS WebSocket traffic, prefer `active_sessions` (sessions per replica). HTTP TTS traffic can keep using `inflight_requests`. * **SLO-driven (`ttft`, `e2e_latency`, `decoding_speed`) scale on the promise you make to users:** If your contract is "first token in under a second," scaling on `ttft` targets exactly that. Latency is a *trailing* signal: by the time p95 breaches the target, users can already notice it, so pair a latency metric with honest headroom in `minReplicas` rather than letting the deployment scale from a cold floor. * **Efficiency-driven (`gpu_utilization`, `token_utilization`, `throughput_per_replica`, `cache_hit_rate`) put cost first:** They keep replicas busy and add capacity only when the fleet is genuinely saturated. Understand what "utilized" means for your workload before you rely on them: a GPU can be busy without the workload being latency-healthy, and a utilization target near `100` leaves no headroom for arrival bursts. When you scale on one of these, watch your p95 latency in [monitoring](/docs/dedicated-endpoints/monitoring). Use this as a quick reference when picking a metric: | Metric (`name`) | Good to use when | | - | - | | `inflight_requests` | Default choice. Robust, leading, and engine-agnostic (including HTTP TTS). | | `active_sessions` | TTS deployments with concurrent WebSocket sessions. | | `ttft` | You have a latency SLO on responsiveness (first-token time). | | `e2e_latency` | You have an SLO on total request-completion time. | | `gpu_utilization` | Cost-first workloads that tolerate some latency variance. | | `token_utilization` | Batch or throughput workloads running near engine limits. | | `throughput_per_replica` | Sustained-generation pipelines. | | `decoding_speed` | Guarding per-request generation speed for each user. | | `cache_hit_rate` | Specialist: cache-heavy serving patterns. | When the metric rises above the target, the platform raises `desiredReplicas` and new replicas [cold-start](/docs/dedicated-endpoints/concepts#cold-starts). When load falls, it scales back down after a [stabilization window](#scaling-rate-and-timing). Track progress by polling the deployment: `desiredReplicas` reflects the decision immediately, `status.scheduledReplicas` shows how many replicas the scheduler has placed, and `status.readyReplicas` catches up once cold start finishes. > [!NOTE] > > When you test autoscaling, measure the change in `desiredReplicas` as scaling-decision latency and the change in `status.readyReplicas` as usable-capacity latency. Sustain the test load through the expected cold-start period. A short spike can raise `desiredReplicas` and then subside before a new replica becomes ready, so it demonstrates a scaling decision but not completed scale-up. ### How latency is calculated To calculate the overall latency of a deployment, the platform looks at a percentile of the request latency over each measurement window and scales replicas to keep the metric near your target. The default is the 95th percentile (`p95`), meaning that 95% of requests should come in at or below your target, allowing only the slowest 5% of requests to run longer. To track a different point in the distribution, add `--scaling-percentile` with `p50`, `p90`, `p95`, or `p99`: ```bash CLI theme={null} tg endpoints update dep_abc123 \ --scaling-metric e2e_latency \ --scaling-target 2000 \ --scaling-percentile p90 ``` `--scaling-percentile` applies only to the latency metrics (`ttft`, `decoding_speed`, and `e2e_latency`). The platform ignores it for other metrics. ## Scaling rate and timing After the platform computes how many replicas a deployment needs from your metric and target, two layers shape how quickly the replica count can change. **Stabilization windows** control how long the metric must stay above or below your target before the platform acts. Pass `--scale-up-window` and `--scale-down-window` on [`deploy`](/reference/cli/endpoints#deploy) or [`update`](/reference/cli/endpoints#update) to override them. When omitted, scale-up has no stabilization delay (`0` seconds), and scale-down waits five minutes before removing replicas. **Rate limits** cap how many replicas can be added or removed per evaluation. The platform applies fleet defaults that you cannot override through the public API: | Direction | Rate limit | Period | | - | - | - | | Scale up | The smaller of a 100% increase or 4 replicas | 15 seconds | | Scale down | The smaller of a 25% decrease or 1 replica | 60 seconds | The platform evaluates scaling roughly every 60 seconds. Each evaluation applies the stabilization windows first, then clamps the replica delta to these rate limits, then clamps the result to your [replica bounds](#replica-bounds). A deployment at zero replicas stays at zero until you raise its floor above zero. ## Automatic idle shutdown To avoid paying for a deployment that sits idle, set an inactivity timeout. If the deployment serves no inference requests for that many minutes, the platform stops it: both [replica bounds](#replica-bounds) drop to `0`, the hardware is released, and billing stops, exactly as if you had [stopped the deployment](/docs/dedicated-endpoints/manage#stop-a-deployment) yourself. Idle shutdown is off unless you set it. Enable it when you deploy, or on a running deployment: ```bash CLI theme={null} # At deploy time tg endpoints deploy zai-org/GLM-5.2 \ --endpoint my-glm-endpoint \ --min-replicas 1 \ --max-replicas 4 \ --inactive-timeout 60 # On a running deployment tg endpoints update dep_abc123 --inactive-timeout 60 ``` The timeout must be between `30` and `1440` minutes (24 hours). To turn idle shutdown off, set it to `0`. In the management API, the field is `inactiveTimeout` on the deployment (`inactive_timeout` in the Python SDK). How the idle clock runs: * **The clock starts when the deployment first becomes ready:** A deployment that never serves a request shuts down after its timeout elapses from the moment it first reaches `READY`, not from creation. * **Every inference request resets it:** The deployment stays up as long as requests keep arriving. * **Changing the timeout also resets it:** When you update the value, the new period counts from the moment of the update. Enabling or lowering the timeout on an already idle deployment grants a full fresh window rather than shutting it down immediately. After an idle shutdown the deployment sits in `DEPLOYMENT_STATE_STOPPED` and doesn't restart on its own. To bring it back, raise both replica bounds to `1` or more. The timeout stays set, so the deployment shuts down again after another idle period. > [!NOTE] > > A deployment with an inactivity timeout enabled can't take part in a [rollout](/docs/dedicated-endpoints/rollouts), as either the source or the target. Set the timeout to `0` before creating the rollout, and turn it back on after the rollout completes. ## Release hardware A deployment runs until you stop it or an [idle shutdown](#automatic-idle-shutdown) stops it. To release the hardware yourself, [stop the deployment](/docs/dedicated-endpoints/manage#stop-a-deployment) or lower its [replica bounds](#replica-bounds) to zero (set both `minReplicas` and `maxReplicas` to `0`). A stopped deployment doesn't restart on its own. To bring it back, raise both bounds to `1` or more. ## Next steps > [card] [Observability](/docs/dedicated-endpoints/monitoring) > > Query the metrics that drive autoscaling decisions. > [card] [Pricing](/docs/dedicated-endpoints/pricing#how-scaling-affects-cost) > > See how replica count maps to cost. # Run a shadow experiment Source: https://docs.together.ai/docs/dedicated-endpoints/shadow-experiments Mirror a sampled fraction of endpoint traffic to a target deployment without affecting the client response. A shadow experiment copies a fraction of live traffic on an endpoint to one or more target deployments for observation, without changing what your application gets back. ![Request mirroring. A client sends a request to the endpoint, which acts as a sampler. Every request goes to the live deployment, which serves every user and returns the response to the client. A sampled copy is sent to the shadow deployment as fire-and-forget: it is measured, then discarded, and never reaches the client.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/shadow-request-mirroring.gif?s=94c193612985051927a12dc878eb0ed1) Use a shadow experiment to warm up a new deployment under real load, stress-test configuration changes, or gather latency data for a candidate before routing live requests to it. Unlike an [A/B test](/docs/dedicated-endpoints/ab-tests), a shadow experiment never affects the client-visible response. ## How it works A shadow experiment has two parts: * **Source:** The endpoint where mirrored traffic comes from and how much of it gets sampled. The source samples traffic at the API gateway using one of four [sampling strategies](#sampling-strategies). * **Targets:** The deployments that receive the mirrored traffic. Each target names a deployment under the same endpoint that isn't serving live traffic (traffic-split weight `0` or unset) and isn't the source or target of an active rollout. A deployment holds one traffic role at a time, so both directions are rejected with `400` `failed_precondition` (you also can't create a rollout onto a current shadow target). A weight-`0` staging deployment is allowed as a warm-up state. Size each target for the mirrored volume you expect. When a request is sampled, a copy is sent to every target in the experiment. In an experiment with two targets that sample at 10% each, each target receives 10% of endpoint traffic. Adding a target multiplies the mirrored volume rather than dividing it. For a single target, copies are spread across its replicas through normal load balancing. All mirroring stops when you delete the experiment. ### Hosting multiple experiments on an endpoint An endpoint can host several experiments at once. Each experiment samples the endpoint's traffic independently, with its own [sampling strategy](#sampling-strategies) and rate, so a single request can be mirrored by more than one experiment. Mirrored volumes add up across experiments, so watch the total load on your targets. Use the structure that matches your use case: * **More targets in one experiment:** Compare how candidates perform for the same sampled requests. Each sampling decision applies to every target, so each target receives the same traffic. Use this for apples-to-apples comparisons, such as comparing fp8, fp4, and baseline builds on the same prompts. * **Multiple experiments on the endpoint:** Compare how candidates perform under different rules. Use this method when candidates require different sampling rates (a large candidate can absorb 50% vs. a small one that can only take 10%), different strategies (sticky key-based sampling vs. random uniform), or different owners and lifetimes (a long-lived 1% safety net vs. a short-lived high-rate test). ### Sampling strategies The source can be configured with one of four sampling strategies: ![The four sampling strategies. uniform samples a fixed fraction of all requests at random (rate 0.1). key\_based samples all requests from a fraction of distinct key values, so one user is either always or never mirrored (key: user\_id). adaptive\_uniform auto-adjusts the uniform rate to hold mirrored traffic at or below a target QPS as production arrivals rise and fall. adaptive\_key\_based combines sticky key sampling with the same target-QPS throttle.](https://mintcdn.com/togetherai-52386018/tYKDywxdUBR_nCcU/images/dedicated-endpoints/shadow-sampling-strategies.png?fit=max\&auto=format\&n=tYKDywxdUBR_nCcU\&q=85\&s=3e0fce498d1cfc900f94a20392470601) | Strategy | Description | | - | - | | `uniform` | Samples a fixed fraction of all requests at random. Set the `--rate` flag to a value between `0.0` and `1.0` to use this strategy. | | `key_based` | Samples a fixed fraction of distinct key values. The same key always gets the same decision (sticky). Set the `--rate` and `--key` flags to use this strategy. | | `adaptive_uniform` | Auto-adjusts the uniform rate to approach a target request rate (QPS). Set the `--target-qps` flag, and optionally `--window` (the sliding window for QPS observation, defaults to 60 seconds). | | `adaptive_key_based` | Auto-adjusts a per-key rate to approach a target request rate (QPS). Set the `--target-qps` and `--key` flags, and optionally `--window`. | The `key` for key-based strategies names a top-level field in the request body (for example `body.user` or `body.prompt_cache_key`), not a nested path. Requests with no value in that field are sampled at random. Setting `--rate` to `0` mirrors nothing, which is a way to [pause an experiment](#pause-retune-or-stop-an-experiment) without deleting it. For the adaptive strategies, `target_qps` is an approximate throttle, not a precise cap on total mirrored volume. The volume your targets actually receive may run higher than the value you set, and it grows as your endpoint scales up under load. Treat `target_qps` as a way to keep mirroring loosely bounded rather than pinned to an exact rate. Set it conservatively, [check the volume your targets actually receive](#observe-results), and adjust. If you need a predictable, exact fraction of traffic, use a `uniform` strategy instead. ## Requirements Before you start a shadow experiment, you need a running endpoint under load and a candidate deployment to shadow to. The candidate must not serve live traffic on the endpoint (traffic-split weight `0` or unset), must not be the source or target of an active rollout, and must not be a member of an [A/B test](/docs/dedicated-endpoints/ab-tests). It receives only mirrored traffic. The CLI's `shadow` command provisions a new shadow deployment from a model ID and wires up the experiment in one command, so you only need the endpoint and a model. The SDK mirrors to a deployment you've already created. The examples below use these example IDs, which you should replace with your own: * Endpoint: `ep_abc123`. * Model to shadow-deploy: `ml_CbJNwQC2ZqCU2iFT3mrCh`. * Target deployment (already created, for the SDK path): `dep_target456`. ## Create a shadow experiment Create an experiment that samples 10% of gateway traffic uniformly and mirrors it to one target. > [tab] CLI > > The CLI's `shadow` command creates a new shadow deployment from a model, then starts mirroring sampled traffic to it (the SDK mirrors to an existing target deployment instead, with the sampling strategy in the `source.endpoint` block): > > ```bash theme={null} > tg endpoints shadow ml_CbJNwQC2ZqCU2iFT3mrCh \ > --endpoint ep_abc123 \ > --rate 0.1 \ > --name candidate-v2 > ``` > > Note the experiment ID (`exp_...`) from the response. You use it to inspect, update, or delete the experiment. > > > [!NOTE] > > > > `name` is immutable after creation and must be unique within the endpoint. `description` can't be set on create. Set it by [updating the experiment](/reference/dmi/shadow-experiments-update). > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > The console mirrors to a shadow deployment you've already created, so first [add the candidate to the endpoint](/docs/dedicated-endpoints/manage#create-a-deployment) at traffic weight `0`. The console blocks the form until the endpoint has at least two deployments, with at least one that is not currently receiving live traffic. > > **1. Open the shadow test form** > > On the endpoint, select the **Traffic Tests** tab, then **New shadow test**. > > **2. Name the test** > > Enter a **Name** and an optional **Description**. Sampling mirrors the endpoint's live traffic. > > **3. Choose the shadow deployment** > > Select the weight-`0` candidate as the **Shadow deployment**. The picker lists only deployments that are not currently receiving live traffic. > > **4. Set the sampling strategy** > > Choose a **Sampling strategy** (Uniform, Key-based, Adaptive, or Adaptive + key) and set the **Sample rate**. > > **5. Create the test** > > Select **Create shadow test**. > > ![The New shadow test dialog in the Together AI console, with name and description fields, a Shadow deployment picker, a sampling-strategy selector offering Uniform, Key-based, Adaptive, and Adaptive plus key, and a sample-rate input.](https://mintcdn.com/togetherai-52386018/pe3m0UN_u6jcX2cr/images/dedicated-endpoints/shadow-test-create-dialog.png?fit=max\&auto=format\&n=pe3m0UN_u6jcX2cr\&q=85\&s=af7c14e445522c08a75e1574ae5752d1) After creating the experiment, [send requests](/docs/dedicated-endpoints/requests) to the endpoint as you normally would, using the endpoint string as the `model` field. The request path doesn't change, but a sampled fraction of requests is mirrored to each target in the background. ### Sampling strategy examples Use `key_based` sampling to make mirroring decisions sticky on a request field (for example `body.user`), so all requests from the same user are either always mirrored or never: ```bash theme={null} tg endpoints shadow ml_CbJNwQC2ZqCU2iFT3mrCh \ --endpoint ep_abc123 \ --rate 0.05 \ --key body.user \ --name candidate-v2 ``` Use `adaptive_uniform` to throttle mirroring toward a target request rate (QPS) rather than a fixed fraction. The sampler adjusts the rate automatically: ```bash theme={null} tg endpoints shadow ml_CbJNwQC2ZqCU2iFT3mrCh \ --endpoint ep_abc123 \ --target-qps 5.0 \ --name candidate-v2 ``` ### Response fields | Field | Description | | - | - | | `id` | Unique experiment identifier. | | `project_id` | The project the experiment belongs to. | | `endpoint_id` | The endpoint whose traffic is sampled. | | `name` | Human-readable name, unique within the endpoint. | | `source` | Sampling configuration for the endpoint's traffic. | | `targets` | Target deployments, populated inline on Get. | | `created_by` | Identifier of the principal that created the experiment. | | `created_at` | Timestamp when the experiment was created. | | `updated_at` | Timestamp when the experiment was last updated. | | `etag` | Opaque version tag for optimistic concurrency. Pass it back in update and delete requests. A stale value is rejected. | | `state` | Output only. Derived serving state: `ACTIVE` when the experiment has at least one target, `INACTIVE` when it has none. Recomputed on every read. Not stored and not settable (rejected if listed in `update_mask`). | ## Observe results Once the experiment is `ACTIVE`, keep calling the endpoint as you normally would. A sampled fraction of your requests is mirrored to each target in the background, and the response you get back is always the baseline's. > [!NOTE] > > A new or updated experiment takes effect within about 30 to 60 seconds. Deleting an experiment stops mirroring within roughly the same window. Because targets never return their responses to your caller, evaluate them the same way you would evaluate any deployment: * Compare each target's own latency, throughput, and error rate against the baseline. * If you log outputs, compare each target's outputs against the baseline's for the mirrored requests. * Confirm each target is receiving the expected mirrored volume. As a rough check, target volume should equal the sampled requests times the number of targets: about (endpoint traffic times `rate`) for a uniform strategy, or roughly tracking your configured `target_qps` (which can run higher and rises as the endpoint scales) for an adaptive one. ## Pause, retune, or stop an experiment * **Pause without deleting:** [Update](/reference/dmi/shadow-experiments-update) the experiment's `source` to set the sampling `rate` to `0`. The experiment stays `ACTIVE` but samples nothing. * **Retune sampling:** Update the experiment's `source`, for example to raise `uniform.rate` or switch strategy. Fetch the experiment first to get its current `etag` and pass it back on the update. A stale value returns `409 ABORTED`. * **Fan out to more targets:** [Add a target](/reference/dmi/shadow-experiment-targets-create) to the experiment. One sampling decision fans out to every target, so adding a target roughly multiplies mirrored volume. * **Stop mirroring:** [Delete the experiment](#delete-an-experiment) (which cascade-deletes its targets), or remove all its targets so the experiment goes `INACTIVE`. * **Promote a validated candidate:** Start a [rollout](/docs/dedicated-endpoints/rollouts) to shift live traffic to the shadow deployment. Pass `--detach` and the CLI's `rollout` command removes the deployment from the experiment (deleting the experiment if it has no targets left) before shifting traffic. Mirrored requests are never sampled and mirrored again. The system prevents shadow loops automatically. > [!TIP] > > Before deleting a deployment that an experiment targets, remove it from the experiment first (or delete the experiment). That keeps the experiment's configuration consistent and avoids leaving a target that points at a deployment that no longer exists. ### Delete an experiment Deletion cascade-deletes all targets, and mirroring stops shortly after. The CLI's smart-delete `rm` accepts the experiment ID: ```bash theme={null} tg endpoints rm exp_abc123 ``` In the console, stop a shadow test from its actions menu on the endpoint's **Traffic Tests** tab. ## Troubleshooting * **A target receives no mirrored traffic:** The experiment may be `INACTIVE` (no targets), the sampling `rate` may be `0`, or the change may not have propagated yet. Confirm the experiment is `ACTIVE` with at least one target and a non-zero rate, then re-check after the 30-to-60-second propagation window. Mirroring also needs live traffic on the endpoint: a sampled fraction of zero requests is zero. * **A target's shadow metrics show dropped copies (`build_error` or `5xx`):** Mirroring is fire-and-forget. If a target is still provisioning, scaled to zero, or unhealthy, copies are still sent and then silently dropped, and the failures show up only in that target's shadow metrics. Your callers are never affected, and mirroring recovers on its own once the target is serving again. * **Mirrored volume is lower than expected:** With `key_based` sampling, whole keys are sampled sticky, so a few high-volume keys can pull the effective rate away from the nominal `rate`. With an adaptive strategy, the sampler throttles toward `target_qps` rather than a fixed fraction, and the actual volume can drift as the endpoint scales. Switch to `uniform` if you need a predictable fraction. * **An update or delete returns `409 ABORTED`:** The `etag` you passed is stale. Re-read the experiment (or target) to get the current `etag`, then retry. * **Create returns `400`:** The request shape is invalid. Check for a missing required field, a `rate` outside `[0.0, 1.0]`, more than 100 inline targets, or a `name` longer than 256 characters. * **Create or add target returns `400` with `the deployment is serving live traffic on this endpoint and cannot also be a shadow target; remove it from the traffic split first`:** The target deployment has a non-zero weight in the endpoint's [traffic split](/docs/dedicated-endpoints/route-traffic). Remove it from the split (set its weight to `0` or omit it) before adding it as a shadow target. * **Create or add target returns `400` with `the deployment is the source or target of an active rollout; wait for the rollout to finish (or cancel it) first`:** The candidate is already in an active rollout. Wait for the rollout to finish, or cancel it, before using the deployment as a shadow target. * **Create or add target returns `400` with `the deployment is an A/B experiment member; remove it from the experiment first`:** The candidate is a control or variant in an [A/B test](/docs/dedicated-endpoints/ab-tests). Remove it from the test (or delete the test) before adding it as a shadow target. * **Create or a lookup returns `404`:** The experiment, target, or parent endpoint doesn't exist in the project named in the path. The API returns the same `404` for a missing ID, a wrong-endpoint ID, and an ID that belongs to a different project, so you can't use it to probe for cross-tenant resources. ## Limits * Up to 100 inline targets when creating an experiment. Add more with the target methods after creation. * `name` (on both experiments and targets) is at most 256 characters. * `limit` on list calls defaults to 50, up to a maximum of 500. ## Next steps > [card] [A/B tests](/docs/dedicated-endpoints/ab-tests) > > Split live traffic and compare user-visible responses across deployments. > [card] [Rollouts](/docs/dedicated-endpoints/rollouts) > > Promote a validated candidate by shifting live traffic to it in controlled steps. > [card] [Observability](/docs/dedicated-endpoints/monitoring) > > Monitor per-deployment metrics during experimentation. > [card] [Manage deployments](/docs/dedicated-endpoints/manage) > > Create and manage the deployments used in shadow experiments. # Split traffic across deployments Source: https://docs.together.ai/docs/dedicated-endpoints/split-traffic Run multiple deployments on one endpoint and split requests between them by weight. Running more than one deployment on an endpoint lets you serve traffic across them for high availability, providing redundancy in case one of them fails. To split traffic between multiple deployments, list each with its relative weight. A weight sets a deployment's share of traffic relative to its capacity: the actual share a deployment receives is proportional to its weight times its number of ready replicas. > [tab] CLI > > Set each weight with `endpoints update --traffic-weight`, passing the deployment ID (`dep_...`). The CLI resolves its parent endpoint and preserves the other deployments' weights, so run it once per deployment: > > ```bash Shell theme={null} > tg endpoints update dep_abc123 --traffic-weight 70 > tg endpoints update dep_def456 --traffic-weight 30 > ``` > > > [!NOTE] > > > > When each deployment has the same number of ready replicas, the weights behave like a direct ratio. For example, with equal replica counts, the weights in the example above send roughly 70% of traffic to one deployment and 30% to the other. > [tab] Console > > [Endpoints](https://api.together.ai/endpoints) > > On a live endpoint's **Overview** tab, the status card shows the current traffic split. Select **Edit traffic weights** to set a weight for every deployment at once, then **Save changes**. At least one deployment must have a weight above 0. > > You can also set each deployment's **Traffic weight** in its **Deployment configuration** (open the deployment, select **Edit**, then **Save changes**), or set all weights together in the create form's **Traffic weights** card when you create an endpoint with more than one deployment. > > While a [rollout](/docs/dedicated-endpoints/rollouts) is active (including pending or paused), the **Overview** status card shows rollout progress instead of **Edit traffic weights**, and the **Traffic weight** field is disabled in each deployment's **Edit** dialog and in **New deployment**. Complete or cancel the rollout before editing weights manually. Weights are relative ratios, not percentages, so they don't have to sum to any particular number: a split of `7` and `3` is equivalent to a split of `70` and `30`. But weight sets *relative capacity*, not a fixed percentage. Each weight must be non-negative and finite. Two deployments with the same weight but different replica counts do not receive equal traffic. A deployment with weight `1` and two ready replicas draws the same traffic as one with weight `2` and a single ready replica. A deployment receives no traffic if it has a weight of `0`, is absent from the split, or has zero ready replicas. Scaling a deployment to zero replicas takes it out of rotation even when it keeps a non-zero weight. Requests to an endpoint with no routable deployment return HTTP `400` with the error code `endpoint_not_configured`. ## Shift traffic with replica counts Treat weights as a stable definition of each deployment's relative capacity, and shift traffic between deployments by changing their [replica counts](/docs/dedicated-endpoints/scaling#replica-bounds) rather than editing weights. Because a deployment's share tracks its ready replicas, scaling one deployment up (or another down) moves traffic without you having to recompute a set of weights. To migrate traffic from one deployment to another on live traffic, use a [rollout](/docs/dedicated-endpoints/rollouts) instead of shifting the split by hand: it moves traffic in controlled steps, can gate each step on live metrics, and drains the source when it completes. A deployment's weight is remembered when it scales to zero and reapplies automatically when it scales back up, so you don't need to re-add it to the split after a scale-down. ## Troubleshooting * **Update traffic split returns `409` with `cannot update traffic_split while rollout ... is active`:** A [rollout](/docs/dedicated-endpoints/rollouts) in any non-terminal state (including pending or paused) owns the endpoint's traffic split. Complete, cancel, or delete the rollout before editing weights. * **Update traffic split returns `400` with `the deployment is a shadow experiment target and cannot serve live traffic; remove the shadow target first`:** The deployment is registered as a target in an active [shadow experiment](/docs/dedicated-endpoints/shadow-experiments). Remove it from the experiment (or delete the experiment) before giving it a non-zero weight in the traffic split. ## Next steps > [card] [Route traffic](/docs/dedicated-endpoints/route-traffic) > > Understand how an endpoint resolves each request to a deployment. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Set the replica bounds that shift traffic between deployments. > [card] [Run an A/B test](/docs/dedicated-endpoints/ab-tests) > > Compare a candidate deployment against a baseline on live traffic. > [card] [Manage deployments](/docs/dedicated-endpoints/manage) > > Create, poll, scale, stop, and delete deployments. # DeepSeek V4 Pro quickstart Source: https://docs.together.ai/docs/deepseek-v4-quickstart Call DeepSeek V4 Pro on Together for hybrid reasoning, long-context, and tool-using workloads. DeepSeek V4 Pro is DeepSeek's frontier 1.6T-parameter Mixture-of-Experts model (49B active per token), with a hybrid attention architecture built for long-context, low-cost reasoning. On Together AI, it runs in NVFP4 with a 1M-token context window and supports streaming, function calling, structured outputs, and adjustable reasoning effort. The model ID is `deepseek-ai/DeepSeek-V4-Pro-0813`. Pricing is \$1.32 per 1M input tokens, \$3.96 per 1M output tokens, and \$0.13 per 1M cached input tokens. ## Quickstart Reasoning is on by default, so most calls work with no extra configuration. Stream the response, since reasoning output can be long. ```python Python theme={null} from together import Together client = Together() stream = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=[ { "role": "user", "content": "Prove that the square root of 2 is irrational.", } ], stream=True, ) for chunk in stream: if not chunk.choices: continue delta = chunk.choices[0].delta if hasattr(delta, "reasoning") and delta.reasoning: print(delta.reasoning, end="", flush=True) if hasattr(delta, "content") and delta.content: print(delta.content, end="", flush=True) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const stream = await together.chat.completions.stream({ model: "deepseek-ai/DeepSeek-V4-Pro-0813", messages: [ { role: "user", content: "Prove that the square root of 2 is irrational." }, ], }); for await (const chunk of stream) { const delta = chunk.choices[0]?.delta; if (delta?.reasoning) process.stdout.write(delta.reasoning); if (delta?.content) process.stdout.write(delta.content); } ``` ```bash cURL theme={null} curl -X POST "https://api.together.ai/v1/chat/completions" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-ai/DeepSeek-V4-Pro-0813", "messages": [ {"role": "user", "content": "Prove that the square root of 2 is irrational."} ], "stream": true }' ``` The response separates the chain of thought from the final answer: reasoning tokens arrive in the `reasoning` field on each delta, and the answer arrives in `content`. ## Reasoning effort DeepSeek V4 Pro accepts two effort levels through the `reasoning_effort` parameter: * `"high"`: The default thinking depth. Use for most complex problems. * `"max"`: Maximum reasoning effort. Use for the hardest math, planning, and multi-step coding agents. Set the context window to at least 384K tokens for Think Max mode, and set `max_tokens` generously, since `"max"` mode can produce very long chains of thought. Together normalizes other values automatically: `"low"` and `"medium"` map to `"high"`, and `"xhigh"` maps to `"max"`. ```python Python theme={null} from together import Together client = Together() stream = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=[ { "role": "user", "content": "Find all integer solutions to x^3 + y^3 = z^3 + 1 with |x|,|y|,|z| <= 100.", } ], reasoning_effort="max", temperature=1.0, top_p=1.0, max_tokens=384000, stream=True, ) for chunk in stream: if not chunk.choices: continue delta = chunk.choices[0].delta if hasattr(delta, "reasoning") and delta.reasoning: print(delta.reasoning, end="", flush=True) if hasattr(delta, "content") and delta.content: print(delta.content, end="", flush=True) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const stream = await together.chat.completions.stream({ model: "deepseek-ai/DeepSeek-V4-Pro-0813", messages: [ { role: "user", content: "Find all integer solutions to x^3 + y^3 = z^3 + 1 with |x|,|y|,|z| <= 100.", }, ], reasoning_effort: "max", temperature: 1.0, top_p: 1.0, max_tokens: 384000, }); for await (const chunk of stream) { const delta = chunk.choices[0]?.delta; if (delta?.reasoning) process.stdout.write(delta.reasoning); if (delta?.content) process.stdout.write(delta.content); } ``` For broader guidance on reasoning controls and prompting, see [Reasoning](/docs/inference/chat/reasoning). ## Long-context use DeepSeek V4 Pro accepts up to 1M input tokens on Together. The model's hybrid attention combines Compressed Sparse Attention (CSA) with Heavily Compressed Attention (HCA), which keeps the key-value (KV) cache and per-token FLOPs roughly an order of magnitude smaller than DeepSeek V3.2 at long contexts. Use the full context window with care. The model's ability to retrieve information is not uniform across the window, so refer to the needle-in-a-haystack results from [DeepSeek's paper](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/main/DeepSeek_V4.pdf) below. For critical tasks, treat the first 256K of context as more reliable than the next 256K, and so on. ![DeepSeek V4 Pro context length visualization](https://mintcdn.com/togetherai-52386018/clRQwip6lGxMeevX/images/niah_deepseekv4.png?fit=max\&auto=format\&n=clRQwip6lGxMeevX\&q=85\&s=d6e813c91e3234d0fac839c32f103cfe) A few tips for long inputs: * Put your instructions at the top of the prompt and your question at the bottom. * Set `max_tokens` explicitly. Long contexts plus `reasoning_effort="max"` can produce very long completions. ## Recommended sampling parameters DeepSeek recommends `temperature=1.0` and `top_p=1.0` for V4 Pro. Lower temperatures can collapse the reasoning trace and degrade answer quality, so prefer to control output length with `max_tokens` rather than turning down temperature. ## Reducing reasoning overhead V4 Pro is a thinking-by-default hybrid model on Together. For turns where reasoning overhead is not needed, disable reasoning with `reasoning={"enabled": False}`: ```python theme={null} response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=[ { "role": "user", "content": "Translate 'good morning' into French.", } ], reasoning={"enabled": False}, max_tokens=512, ) print(response.choices[0].message.content) ``` When you keep reasoning enabled, use `reasoning_effort="high"` (the default) and add a short instruction asking the model to keep its thinking concise. ## Multi-turn conversations In each turn of the conversation, the model outputs both a chain-of-thought (`reasoning_content`) and a final answer (`content`). The API itself is stateless, so to continue a conversation, you must resend the prior `messages` for every request. If the assistant's response included tool calls, pass both the previous answer and the CoT (`reasoning_content`) back in your next request to maintain the model's reasoning context. However, if there was **no tool call**, the prior CoT (`reasoning_content`) from previous turns is **not** included in the next turn's context. Only the usual conversation history carries forward. The diagram for multi-turn reasoning context illustrates this behavior: ![DeepSeek V4 Pro multi-turn conversation timeline example](https://mintcdn.com/togetherai-52386018/MqzdCJm37PZ2ceQI/images/deepseek_r1_multiround_example_en.jpeg?fit=max\&auto=format\&n=MqzdCJm37PZ2ceQI\&q=85\&s=abd629a7821d0cd9924997a9d20bab76) Code example: ```python theme={null} from together import Together client = Together() messages = [ { "role": "user", "content": "What is the highest mountain in the United States?", } ] response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=messages, reasoning_effort="high", ) assistant_message = response.choices[0].message messages.append( { "role": "assistant", "content": assistant_message.content, } ) messages.append({"role": "user", "content": "How tall is it?"}) response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=messages, reasoning_effort="high", ) print(response.choices[0].message.content) ``` ## Function calling and interleaved reasoning DeepSeek V4 Pro supports tool calling. Define tools in the standard OpenAI-compatible schema and pass them via `tools`. ```python Python theme={null} from together import Together client = Together() tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name.", }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], }, }, "required": ["location"], }, }, } ] response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=[ {"role": "user", "content": "What's the weather in Paris and Tokyo?"} ], tools=tools, ) print(response.choices[0].message.tool_calls) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const tools = [ { type: "function" as const, function: { name: "get_weather", description: "Get the current weather for a city.", parameters: { type: "object", properties: { location: { type: "string", description: "City name." }, unit: { type: "string", enum: ["celsius", "fahrenheit"] }, }, required: ["location"], }, }, }, ]; const response = await together.chat.completions.create({ model: "deepseek-ai/DeepSeek-V4-Pro-0813", messages: [{ role: "user", content: "What's the weather in Paris and Tokyo?" }], tools, }); console.log(response.choices[0].message.tool_calls); ``` For multi-turn function calling, pass the assistant message's reasoning trace back in every later request. This preserves the model's reasoning across tool calls and user turns. Include the assistant message's `content`, `reasoning_content`, and `tool_calls`, then append each tool result with the matching `tool_call_id`, as illustrated in the multi-turn function-calling diagram. ![Multi-turn function calling timeline example](https://mintcdn.com/togetherai-52386018/clRQwip6lGxMeevX/images/thinking_with_tools_en.jpg?fit=max\&auto=format\&n=clRQwip6lGxMeevX\&q=85\&s=4969aea7932afaf9433f6e2df94109e4) Code example: ```python theme={null} import os import json from together import Together from datetime import datetime tools = [ { "type": "function", "function": { "name": "get_date", "description": "Get the current date", "parameters": {"type": "object", "properties": {}}, }, }, { "type": "function", "function": { "name": "get_weather", "description": "Get weather of a location, the user should supply the location and date.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name", }, "date": { "type": "string", "description": "The date in format YYYY-mm-dd", }, }, "required": ["location", "date"], }, }, }, ] def get_date_mock(): return datetime.now().strftime("%Y-%m-%d") def get_weather_mock(location, date): return "Sunny 68~82°F" TOOL_CALL_MAP = { "get_date": get_date_mock, "get_weather": get_weather_mock, } def run_turn(client, turn, messages): sub_turn = 1 while True: response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V4-Pro-0813", messages=messages, tools=tools, reasoning_effort="high", ) choice = response.choices[0].message reasoning = getattr(choice, "reasoning", None) or getattr( choice, "reasoning_content", None ) content = choice.content tool_calls = choice.tool_calls print(f"Turn {turn}.{sub_turn}") print(f" reasoning = {reasoning}") print(f" content = {content}") print(f" tool_calls= {tool_calls}") assistant_msg = { "role": "assistant", "content": content or "", } if reasoning: assistant_msg["reasoning_content"] = reasoning if tool_calls: assistant_msg["tool_calls"] = [ { "id": tc.id, "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments, }, } for tc in tool_calls ] messages.append(assistant_msg) if not tool_calls: break for tool in tool_calls: tool_function = TOOL_CALL_MAP[tool.function.name] tool_result = tool_function(**json.loads(tool.function.arguments)) print(f" tool result for {tool.function.name}: {tool_result}") messages.append( { "role": "tool", "tool_call_id": tool.id, "content": tool_result, } ) sub_turn += 1 print() client = Together() messages = [ {"role": "user", "content": "How's the weather in San Francisco tomorrow?"} ] run_turn(client, 1, messages) messages.append( {"role": "user", "content": "How's the weather in New York tomorrow?"} ) run_turn(client, 2, messages) ``` ```text theme={null} Turn 1.1 reasoning = The user wants to know the weather in San Francisco tomorrow. I need to get the current date first, and then use that to determine tomorrow's date. Then I'll call the weather function. Let me start by getting the current date. content = tool_calls= [ToolChoice(id='call_02dbb9ade77b4e8890526e02', function=Function(arguments='{}', name='get_date'), index=0.0, type='function')] tool result for get_date: 2026-04-29 Turn 1.2 reasoning = Today is 2026-04-29, so tomorrow is 2026-04-30. Now let me get the weather for San Francisco on that date. content = tool_calls= [ToolChoice(id='call_af2f753610ab4281a4ebe8ed', function=Function(arguments='{"location": "San Francisco", "date": "2026-04-30"}', name='get_weather'), index=1.0, type='function')] tool result for get_weather: Sunny 68~82°F Turn 1.3 reasoning = I have the weather information for San Francisco tomorrow. Let me summarize it for the user. content = Tomorrow (April 30, 2026) in San Francisco is looking **sunny** with a temperature range of **68°F to 82°F** (about 20°C to 28°C). Should be a beautiful day — perfect for getting outside! ☀️ tool_calls= [] Turn 2.1 reasoning = The user wants the weather in New York tomorrow. I already know today is 2026-04-29, so tomorrow is 2026-04-30. Let me call the weather function directly. content = tool_calls= [ToolChoice(id='call_4c5c442c8f884f8bb09a2ad2', function=Function(arguments='{"location": "New York", "date": "2026-04-30"}', name='get_weather'), index=1.0, type='function')] tool result for get_weather: Sunny 68~82°F Turn 2.2 reasoning = The weather for New York tomorrow is the same as San Francisco in this case? That's what the tool returned. Let me present this to the user. content = Tomorrow (April 30, 2026) in New York is also looking **sunny** with a high of **82°F** and a low of **68°F**. Looks like both coasts are getting great weather tomorrow! 🌞 tool_calls= [] ``` # Jig CLI Source: https://docs.together.ai/docs/deployments-jig Build, push, and deploy containers to Together's managed GPU infrastructure. Jig is a lightweight CLI for building Docker images from a `pyproject.toml`, pushing them to Together's private container registry, and managing deployments. It's included with the [Together Python library](https://github.com/togethercomputer/together-python). > [!TIP] > > **See Jig in action:** Check out the end-to-end examples for [Image Generation with Flux2](/docs/dedicated-containers-image) and [Video Generation with Wan 2.1](/docs/dedicated-containers-video). ## The deploy workflow Jig combines several steps into a single `deploy` command: 1. **Init:** `tg beta jig init` scaffolds a `pyproject.toml` with sensible defaults. 2. **Build:** Generates a Dockerfile from your config and builds the image locally. 3. **Push:** Pushes the image to Together's registry at `registry.together.ai`. 4. **Deploy:** Creates or updates the deployment on Together's infrastructure. ```shell Shell theme={null} # One command does it all tg beta jig deploy # Or step by step tg beta jig build tg beta jig push tg beta jig deploy --image registry.together.ai/myproject/mymodel@sha256:abc123 ``` Once deployed, monitor your containers: ```shell Shell theme={null} tg beta jig status tg beta jig logs --follow ``` For the full list of commands and flags, see the [Jig CLI reference](/reference/cli/jig). > [!TIP] > > Jig builds images locally and pushes them to Together's registry. ML images can be 10GB+, so building on a machine with a fast network connection saves significant time compared to pushing from a laptop over wifi. ## Cache warmup The `--warmup` option lets you pre-generate inference engine compile caches (such as those created by `torch.compile` or TensorRT) at build time, rather than waiting for the first request in production. This can significantly reduce cold-start latency. ```shell Shell theme={null} tg beta jig deploy --warmup tg beta jig build --warmup # Build only, no deploy ``` ### How it works 1. **Build phase:** Jig builds the base image normally. 2. **Warmup phase:** Jig runs the container with GPU access, mounting your local workspace to `/app`. 3. **Cache capture:** The container runs your Sprocket's `warmup_inputs`, generating compile caches. 4. **Final image:** Jig builds a new image layer with the cache baked in. The cache location inside the container is controlled by `WARMUP_ENV_NAME` (default: `TORCHINDUCTOR_CACHE_DIR`) and `WARMUP_DEST` (default: `torch_cache`). Jig sets the environment variable to point to the cache directory during warmup and copies its contents into the final image. ### Sprocket integration Define `warmup_inputs` on your Sprocket class to specify what inputs to run during warmup: ```python app.py theme={null} import base64 import logging import os from io import BytesIO import sprocket import torch from diffusers import Flux2Pipeline class Flux2Sprocket(sprocket.Sprocket): # Define inputs to run during warmup - this pre-generates compile caches warmup_inputs = [ {"prompt": "a white cat"}, ] def setup(self) -> None: device = "cuda" if torch.cuda.is_available() else "cpu" logging.info(f"Loading Flux2 pipeline on {device}...") self.pipe = Flux2Pipeline.from_pretrained( "diffusers/FLUX.2-dev-bnb-4bit", torch_dtype=torch.bfloat16, ).to(device) logging.info("Pipeline loaded successfully!") def predict(self, args: dict) -> dict: prompt = args.get("prompt", "a cat") num_inference_steps = args.get("num_inference_steps", 28) guidance_scale = args.get("guidance_scale", 4.0) logging.info(f"Generating image for prompt: {prompt[:50]}...") image = self.pipe( prompt=prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, ).images[0] # Convert to base64 buffered = BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() return {"image": img_str, "format": "png", "encoding": "base64"} if __name__ == "__main__": queue_name = os.environ.get( "TOGETHER_DEPLOYMENT_NAME", "sprocket-flux2-dev" ) sprocket.run(Flux2Sprocket(), queue_name) ``` During a --warmup build, the `predict(...)` function is invoked once for each input specified in `warmup_inputs`. If `warmup_inputs` is empty or not defined, the warmup step invokes `predict({})` once as a fallback. Make sure all the compile paths would be exercised by the warmup inputs. In normal build (no `--warmup`), an empty `warmup_inputs` means no warmup runs at all. Since the local workspace is mounted to `/app`, model weights and example inputs can live in your project directory and be referenced directly. ### Requirements * A GPU on your build machine: warmup runs your model locally to generate caches. If you don't have a local GPU, [Together GPU clusters](/docs/gpu-clusters-overview) provide on-demand H100s with fast connectivity to Together's container registry. * `warmup_inputs` defined on your Sprocket with representative inputs. * Weights and example inputs accessible in local workspace. ## Secrets Secrets are encrypted environment variables injected into your container at runtime. Use them for API keys, tokens, and other sensitive values that shouldn't be baked into the image. > [!WARNING] > > A name cannot appear in both `[tool.jig.deploy.environment_variables]` and a secret. `jig deploy` fails and lists each colliding name if the same name is defined in both places. Remove the duplicate from your config or run `tg beta jig secrets unset --name `. ```shell Shell theme={null} tg beta jig secrets set --name HF_TOKEN --value hf_xxxxx --description "Hugging Face token" tg beta jig secrets list tg beta jig secrets unset HF_TOKEN ``` Secrets are available to your container as environment variables at runtime. Do not also define the same name under `[tool.jig.deploy.environment_variables]`. See the [Jig CLI reference](/reference/cli/jig#secrets) for all secrets commands. ## Volumes Volumes let you mount read-only data, like model weights, into your container without baking them into the image. This keeps images small and lets you update weights independently of code. Create a volume and upload files: ```shell Shell theme={null} tg beta jig volumes create --name my-weights --source ./model_weights/ ``` Then mount it in your `pyproject.toml`: ```toml theme={null} [[tool.jig.deploy.volume_mounts]] name = "my-weights" mount_path = "/models" ``` See the [Jig CLI reference](/reference/cli/jig#volumes) for all volume commands. # Queue API Source: https://docs.together.ai/docs/deployments-queue Submit, monitor, and manage asynchronous jobs for your dedicated container inference deployments. The Queue API provides asynchronous job processing for dedicated container inference. Submit jobs to a managed queue, and workers automatically claim and process them. This model supports long-running inference, batch workloads, and explicit priority control. > [!TIP] > > **New to dedicated container inference?** Start with the [Overview](/docs/dedicated-container-inference) to understand the platform, or jump to the [Quickstart](/docs/containers-quickstart) to deploy your first container. ## Core concepts ### Jobs A *job* is a single unit of work submitted to your deployment. Jobs can run for seconds or hours, making them ideal for: * Video generation. * Batch image processing. * Long-running inference tasks. * Any workload that doesn't fit the request-response pattern. ### Job lifecycle | Status | Description | | - | - | | `pending` | Job is queued, waiting for a worker to claim it | | `running` | Job has been claimed and is being processed | | `done` | Job completed successfully | | `failed` | Job failed with an error | | `canceled` | Job was canceled before processing started | ### Priority Jobs are processed in strict order of **priority first, then submission time**. Priority is an integer where higher values are processed first. ```python theme={null} # High priority job (processed first) client.beta.jig.queue.submit(model="my-model", payload={...}, priority=10) # Normal priority job client.beta.jig.queue.submit(model="my-model", payload={...}, priority=1) # Low priority job (processed last) client.beta.jig.queue.submit(model="my-model", payload={...}, priority=0) ``` > [!NOTE] > > By default, priority is **not** considered for autoscaling metrics: the autoscaler scales based on total queue depth regardless of priority. [Contact support](mailto:support@together.ai) for advanced scaling policies that account for priority tiers. ### Job state with `info` The `info` field provides persistent state that survives across the job lifecycle. You can: 1. **Set initial state** when submitting a job via the `info` parameter. 2. **Update state** during processing using `emit()` in your Sprocket worker. 3. **Preserve state** across retries: `info` accumulates rather than resets. This is useful for tracking progress, storing metadata, or passing context between retries. ```python Submit with initial info theme={null} job = client.beta.jig.queue.submit( model="my-model", payload={"prompt": "A cat playing piano"}, info={"user_id": "user_123", "tier": "premium"}, ) ``` ```python Update info during processing (in Sprocket) theme={null} from sprocket import emit def predict(self, args: dict) -> dict: emit({"progress": 0.5, "stage": "encoding"}) # ... more processing emit({"progress": 1.0, "stage": "complete"}) return {"output": result} ``` For full endpoint documentation (request parameters, response schemas, and error codes), see the reference page for each endpoint: [submit](/reference/queue-submit), [status](/reference/queue-status), [cancel](/reference/queue-cancel), [clear](/reference/queue-clear), [metrics](/reference/queue-metrics). ## Polling for job completion For jobs that take time to complete, poll the status endpoint until the job reaches a terminal state (`done`, `failed`, or `canceled`). ```python Python theme={null} import time from together import Together client = Together() # Submit job job = client.beta.jig.queue.submit( model="my-deployment", payload={"prompt": "Generate a video of a sunset"} ) print(f"Submitted job: {job.request_id}") # Poll for completion while True: status = client.beta.jig.queue.retrieve( request_id=job.request_id, model="my-deployment" ) if status.status == "done": print(f"Success! Result: {status.outputs}") break elif status.status == "failed": print(f"Failed: {status.error}") break elif status.status == "canceled": print("Job was canceled") break else: # Show progress if available if status.info and "progress" in status.info: print(f"Progress: {status.info['progress']:.0%}") time.sleep(2) # Poll every 2 seconds ``` ```shell Bash theme={null} #!/bin/bash REQUEST_ID="019ba379-92da-71e4-ac40-d98059fd67c7" MODEL="my-deployment" while true; do RESPONSE=$(curl -s "https://api.together.ai/v1/queue/status?request_id=$REQUEST_ID&model=$MODEL" \ -H "Authorization: Bearer $TOGETHER_API_KEY") STATUS=$(echo $RESPONSE | jq -r '.status') case $STATUS in "done") echo "Success!" echo $RESPONSE | jq '.outputs' break ;; "failed") echo "Failed:" echo $RESPONSE | jq '.error' break ;; "canceled") echo "Cancelled" break ;; *) echo "Status: $STATUS" sleep 2 ;; esac done ``` ## Clearing pending jobs To cancel every pending job for a model at once, for example to drain a backed-up queue, call `clear`. Only jobs still in the `pending` state are canceled. Running jobs are left untouched. The response reports how many jobs were canceled. ```python Python theme={null} from together import Together client = Together() result = client.beta.jig.queue.clear(model="my-deployment") print(f"Canceled {result.canceled_count} pending jobs") ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const result = await client.beta.jig.queue.clear({ model: "my-deployment" }); console.log(`Canceled ${result.canceled_count} pending jobs`); ``` *** ## Best practices ### Use priority for tiered service Implement different service tiers by assigning priority based on customer type: ```python theme={null} def submit_job(user, payload): priority = 10 if user.tier == "premium" else 1 return client.beta.jig.queue.submit( model="my-deployment", payload=payload, priority=priority, info={"user_id": user.id, "tier": user.tier}, ) ``` ### Track progress for long-running jobs For jobs that take more than a few seconds, emit progress updates so clients can show status: ```python theme={null} class VideoGenerator(Sprocket): def predict(self, args: dict) -> dict: total_frames = args.get("num_frames", 60) for i, frame in enumerate(self.generate_frames(args)): emit( { "progress": (i + 1) / total_frames, "current_frame": i + 1, "total_frames": total_frames, } ) return {"video": FileOutput("output.mp4")} ``` ### Handle all terminal states Always check for `done`, `failed`, and `canceled` when polling: ```python theme={null} terminal_states = {"done", "failed", "canceled"} while status.status not in terminal_states: time.sleep(2) status = client.beta.jig.queue.retrieve(...) ``` ### Store metadata in `info` Use `info` to store job metadata that you'll need when the job completes: ```python theme={null} job = client.beta.jig.queue.submit( model="my-deployment", payload={"prompt": "..."}, info={ "user_id": "user_123", "callback_url": "https://myapp.com/webhook", "requested_at": datetime.now().isoformat(), }, ) ``` *** ## Error codes | Code | Description | | - | - | | `400` | Invalid request (missing required fields, malformed payload) | | `401` | Unauthorized (invalid or missing API key) | | `404` | Job or deployment not found | | `409` | Cannot cancel job (already running or completed) | | `500` | Internal server error | *** ## Related resources * [Dedicated container inference overview](/docs/dedicated-container-inference): Architecture and concepts. * [Quickstart](/docs/containers-quickstart): Deploy your first container. * [Sprocket SDK](/docs/deployments-sprocket): Build queue-integrated workers. * [Jig CLI](/docs/deployments-jig): Deploy and manage containers. # Sprocket SDK Source: https://docs.together.ai/docs/deployments-sprocket Sprocket is a Python SDK for building inference workers that support both synchronous and asynchronous requests via Together's platform. Sprocket is a Python SDK for building inference workers that run on Together's managed GPU infrastructure. You implement two methods, `setup()` and `predict()`, and Sprocket handles the HTTP server, queue integration, file transfers, health checks, and graceful shutdown. > [!TIP] > > **See Sprocket in action:** Check out the end-to-end examples for [image generation with FLUX.2](/docs/dedicated-containers-image) and [video generation with Wan 2.1](/docs/dedicated-containers-video). Install Sprocket from Together's package index: ```shell theme={null} uv add sprocket --index https://pypi.together.ai/ ``` ## How Sprocket works * **Model definition:** Subclass `Sprocket`, implement `setup()` to load your model and `predict(args) -> dict` to handle each request. * **Startup:** Calls `setup()` once, optionally runs warmup inputs for cache generation, then starts accepting traffic. * **HTTP endpoints:** `/health` for readiness checks, `/metrics` for autoscaler, `/generate` for direct HTTP inference (route configurable via `predict_path`). * **Job processing:** In queue mode, pulls jobs from Together's managed queue, downloads input URLs, calls `predict()`, uploads output files, and reports job status. * **Graceful shutdown:** On SIGTERM, finishes the current job, calls `shutdown()` for cleanup, and exits. * **Distributed inference:** With `use_torchrun=True`, launches one process per GPU and coordinates inputs/outputs across ranks. ### Architecture ![](https://mintcdn.com/togetherai-52386018/a8zRq9mD9Va4o5jL/images/architechture_dep.png?fit=max\&auto=format\&n=a8zRq9mD9Va4o5jL\&q=85\&s=57b6562a6089d3724c822ef8aa73a4bc) ## File handling Sprocket automatically handles file transfers in both directions. **Input files:** Any HTTPS URL in the job payload is downloaded to a local `inputs/` directory before `predict()` is called. The URL in the payload is replaced with the local file path, so your code opens a local file. This works with Together's files API or any public URL. **Output files:** Return a `FileOutput("path")` in your output dict and Sprocket uploads it to Together storage after `predict()` returns. The `FileOutput` is replaced with the public URL in the final job result. **The full pipeline for each job is:** 1. Download input URLs → local files. 2. Call `predict(args)` with local paths. 3. Call `finalize()` on your `InputOutputProcessor` (if you've overridden it). 4. Upload any `FileOutput` values to Together storage. 5. Report job result. **Custom I/O:** If you need to process downloaded files before they reach `predict()` (e.g., decompressing), or upload outputs to your own storage instead of Together's, you can [subclass `InputOutputProcessor`](/reference/dci-reference-sprocket#custom-io-processing) and attach it to your Sprocket via the `processor` class attribute. > [!NOTE] > > When using `use_torchrun=True` for multi-GPU inference, all file I/O (downloading inputs, uploading outputs, `finalize()`) runs in the parent process, not in the GPU worker processes. This keeps networking separate from GPU compute. ## Multi-GPU / distributed inference For models that need multiple GPUs (tensor parallelism, context parallelism), pass `use_torchrun=True` to `sprocket.run()` and set `gpu_count` in your Jig config. The architecture is: * A **parent process** manages the HTTP server, queue polling, and file I/O. * `torchrun` launches **N child processes** (one per GPU), connected to the parent via a Unix socket. * For each job, the parent broadcasts inputs to all children, each child runs `predict()`, and the parent collects the output from whichever rank returns a non-None value (by convention, rank 0). Your Sprocket code looks the same as single-GPU, with two additions: initialize `torch.distributed` in `setup()`, and return `None` from non-rank-0 processes: ```python Python theme={null} import torch import torch.distributed as dist import sprocket class DistributedModel(sprocket.Sprocket): def setup(self): dist.init_process_group() torch.cuda.set_device(dist.get_rank()) self.model = load_and_parallelize_model() def predict(self, args): result = self.model.generate(args["prompt"]) if dist.get_rank() == 0: result.save("output.mp4") return {"url": sprocket.FileOutput("output.mp4")} return None if __name__ == "__main__": sprocket.run(DistributedModel(), "my-org/my-model", use_torchrun=True) ``` ```toml pyproject.toml theme={null} [tool.jig.deploy] gpu_type = "h100-80gb" gpu_count = 4 ``` ## Error handling Sprocket distinguishes between **per-job errors** and **fatal errors**. **Per-job errors:** If `predict()` raises an exception, the job is marked as `failed` with the error message, downloaded input files are cleaned up, and the worker moves on to the next job. The worker stays healthy: one bad input doesn't take down the whole deployment. **Fatal errors** trigger a full worker restart (SIGTERM). These occur when: * A prediction times out (torchrun mode only, when it exceeds `TERMINATION_GRACE_PERIOD_SECONDS`). * A torchrun child process crashes or disconnects. * The connection to Together's API is lost. In torchrun mode, the job claim has a 90-second timeout that's refreshed every 45 seconds. If a worker dies mid-job, the queue reclaims the job and assigns it to another worker. In single-GPU mode, claims are held until completion with no timeout. ## Graceful shutdown When a container receives SIGTERM (during scale-down or redeployment): 1. Sprocket stops accepting new jobs. 2. The current job runs to completion. 3. Your `shutdown()` method is called for cleanup. 4. The container exits. The total time allowed is controlled by `TERMINATION_GRACE_PERIOD_SECONDS` (default: 300s, configurable in `pyproject.toml`). Set this higher if your jobs are long-running (for example, video generation that takes several minutes per job). ## Running modes Sprocket supports two modes: **Queue mode** and **HTTP server mode**. * **Queue mode** is for workloads that need job durability and tracking: model generations, video rendering, or anything that takes more than a few hundred milliseconds. Jobs are persisted in the queue, survive worker restarts, and support priority ordering and progress reporting. * **HTTP server mode** (direct HTTP) is for synchronous workloads that don't need queueing: embedding inference, streaming voice models, or OpenAI-compatible endpoints where the result must be returned immediately. ### Queue mode ```shell Shell theme={null} python app.py --queue ``` * Continuously pulls jobs from Together's managed queue. * Automatic job status reporting. * Graceful shutdown support. * Integrated with autoscaling. ### HTTP server mode ```shell Shell theme={null} python app.py ``` * Serves inference requests directly over HTTP at `predict_path` (default `/generate`). * Returns results synchronously. Jobs are not persisted in a queue. * Receives the raw JSON request body in `predict()`, so your worker controls the request and response shapes. Set `predict_path` in `sprocket.run()` to serve a custom route. This is how you [serve an OpenAI-compatible API](/docs/dedicated-containers-openai) from a container: ```python Python theme={null} sprocket.run(MyModel(), predict_path="/v1/images/generations") ``` ## Progress reporting For long-running jobs like video generation, you can report progress updates that clients can poll for. Call `emit_info()` from inside `predict()` with a dict of progress data: ```python Python theme={null} from sprocket import Sprocket, emit_info class VideoGenerator(Sprocket): def predict(self, args): for i in range(100): frame = generate_frame(i) emit_info({"progress": (i + 1) / 100, "status": "generating"}) return {"video": FileOutput("output.mp4")} ``` Progress updates are batched and merged: frequent calls to `emit_info()` don't create excessive API traffic, and later values overwrite earlier ones for the same keys. The info dict must serialize to less than 4096 bytes of JSON. The runner also sends periodic heartbeats to maintain the job claim even if you don't call `emit_info()`. Clients poll the [job status endpoint](/reference/queue-status) and see emitted data in the `info` field: ```json theme={null} { "request_id": "req_abc123", "status": "running", "info": {"progress": 0.75, "status": "generating"} } ``` *** The [full API reference](/reference/dci-reference-sprocket) covers class signatures, parameters, environment variables, and complete examples. # Deprecations Source: https://docs.together.ai/docs/deprecations Together AI's model lifecycle policy, including upgrades, redirects, and deprecation schedules. Together AI regularly updates the platform with new open-source models. This page describes the model lifecycle policy and lists active redirects and scheduled deprecations. ## Model lifecycle policy Together AI follows a structured approach to introducing new models, upgrading existing models, and deprecating older versions, so you can rely on predictable behavior. ### Model upgrades (redirects) An **upgrade** is a model release that is materially the same model lineage with targeted improvements and no fundamental changes to how developers use or reason about it. A model qualifies as an upgrade when **one or more** of the following are true (and none of the "new model" criteria apply): * Same modality and task profile (e.g., instruct → instruct, reasoning → reasoning). * Same architecture family (e.g., DeepSeek-V3 → DeepSeek-V3-0324). * Post-training or fine-tuning improvements, bug fixes, safety tuning, or small data refresh. * Behavior is strongly compatible (prompting patterns and evals are similar). * Pricing change is none or small (≤10% increase). **Outcome:** The current endpoint redirects to the upgraded version after a **3-day notice**. The old version remains available via dedicated endpoints. ### New models (no redirect) A **new model** is a release with materially different capabilities, costs, or operating characteristics, so a silent redirect would be misleading. Any of the following triggers classification as a new model: * Modality shift (e.g., reasoning-only ↔ instruct/hybrid, text → multimodal). * Architecture shift (e.g., Qwen3 → Qwen3-Next, Llama 3 → Llama 4). * Large behavior shift (prompting patterns, output style, or verbosity materially different). * Experimental flag by provider (e.g., DeepSeek-V3-Exp). * Large price change (>10% increase or pricing structure change). * Benchmark deltas that meaningfully change task positioning. * Safety policy or system prompt changes that noticeably affect outputs. **Outcome:** No automatic redirect. Together AI announces the new model and deprecates the old one on a **2-week timeline** (both are available during this window). You must explicitly switch model IDs. ## Active model redirects The following models are redirected to newer versions. Requests to the original model ID are automatically routed to the upgraded version: | Original model | Redirects to | Notes | | :- | :- | :- | | `mistralai/Mistral-7B-Instruct-v0.3` | `mistralai/Ministral-3-14B-Instruct-2512` | Same lineage, upgraded version | | `Kimi-K2` | `Kimi-K2-0905` | Same architecture, improved post-training | | `DeepSeek-V3` | `DeepSeek-V3.1` | Same architecture, targeted improvements | | `DeepSeek-V3-0324` | `DeepSeek-V3.1` | Same architecture, targeted improvements | | `DeepSeek-R1` | `DeepSeek-R1-0528` | Same architecture, targeted improvements | > [!TIP] > > If you need to use the original model version, you can always deploy it as a [dedicated endpoint](/docs/dedicated-endpoints). ## Deprecation policy | Model type | Deprecation notice | Notes | | :- | :- | :- | | Preview model | \<24 hours of notice, after 30 days | Clearly marked in docs and playground with "Preview" tag | | Serverless endpoint | 2 or 3 weeks\* | | | On-demand dedicated endpoint | 2 or 3 weeks\* | | \*Depends on usage and whether a newer version of the model is available. * If you use a model scheduled for deprecation, you receive an email notification. * All changes appear on this page. * Each deprecated model has a specified removal date. * After the removal date, the model is no longer available via its serverless endpoint, but migration options are described below. ## Migration options When a model is deprecated on the serverless platform, you have three options: 1. **On-demand dedicated endpoint** (if supported): * Reserved solely for you. You choose the underlying hardware. * Charged on a price-per-minute basis. * Endpoints can be dynamically spun up and down. 2. **Monthly reserved dedicated endpoint:** * Reserved solely for you. * Charged on a month-by-month basis. * Can be requested via this [form](https://together.ai/monthly-reserved). 3. **Migrate to a newer serverless model:** * Switch to an updated model on the serverless platform. ## Migration steps 1. Review the deprecation table below to find your current model. 2. Check if on-demand dedicated endpoints are supported for your model. 3. Decide on your preferred migration option. If you choose a new serverless model, compare candidates on capability, latency, and cost for your workload. 4. Run a small A/B test comparing the replacement against your current model on representative traffic. Replacement models rarely behave identically, so validate quality, latency, and cost before committing. 5. Update your API calls, then shift traffic gradually (canary, then partial, then full cutover). Keep a fallback path during the rollout if possible. 6. Monitor error rates, latency, and cost during and after the migration. > [!NOTE] > > During a transition, a model can still appear in catalog listings while its route-level availability changes. If a listed model returns unavailable or disabled errors, treat the runtime API behavior and this page as the source of truth. ## Scheduled deprecations The following models are deprecated and will be removed from serverless inference on the date listed. Migrate to the recommended replacement or a [dedicated endpoint](/docs/dedicated-endpoints) before that date. | Removal date | Model | Recommended replacement | Supported by on-demand dedicated endpoints | | :- | :- | :- | :- | | 2026-11-06 | `MiniMaxAI/MiniMax-M3` | `MiniMaxAI/MiniMax-M3.1-Flash` | Yes | | 2026-11-06 | `thinkingmachines/Inkling` | `meta-models/Muse-Spark-Open-816B-A42B` | Yes | | 2026-11-04 | `Qwen/Qwen3.8-2.4T-A95B` | `Qwen/Qwen3.7-Max` | No | | 2026-09-14 | `openai/gpt-oss-20b` | `Qwen/Qwen3.5-9B` | Yes | | 2026-09-14 | `google/gemma-4-31B-it` | `zai-org/GLM-5.3-Flash` | Yes | | 2026-09-14 | `thinkingmachines/Inkling-Small` | `zai-org/GLM-5.3-Flash` | Yes | | 2026-09-14 | `intfloat/multilingual-e5-large-instruct` | | No | ## Deprecation history ### Inference The table below lists all models removed from serverless inference, most recent first. | Removal date | Model | Supported by on-demand dedicated endpoints | | :- | :- | :- | | 2026-10-22 | `meta-llama/Llama-3.3-70B-Instruct-Turbo` | Yes | | 2026-10-22 | `deepseek-ai/DeepSeek-V4-Flash-0731` | Yes | | 2026-09-15 | `openai/gpt-oss-20b` | Yes | | 2026-09-15 | `google/gemma-4-31B-it` | Yes | | 2026-09-15 | `thinkingmachines/Inkling-Small` | Yes | | 2026-09-15 | `intfloat/multilingual-e5-large-instruct` | No | | 2026-08-27 | `nvidia/Nemotron-3-ultra-550b-a55b` | No | | 2026-08-27 | `pearl-ai/gemma-4-31b-it` | No | | 2026-08-27 | `deepseek-ai/DeepSeek-V4-Pro` | Yes | | 2026-08-27 | `moonshotai/Kimi-K2.7-Code` | Yes | | 2026-08-25 | `meta-llama/Llama-Guard-4-12B` | No | | 2026-08-25 | `google/gemma-3n-E4B-it` | No | | 2026-08-21 | `deepcogito/cogito-v2-1-671b` | No | | 2026-08-19 | `black-forest-labs/FLUX.1-schnell` | No | | 2026-08-19 | `Qwen/Qwen2.5-7B` | No | | 2026-08-19 | `moonshotai/Kimi-K2.6` | Yes | | 2026-07-10 | `Qwen/Qwen3-235B-A22B-Instruct-2507-tput` | Yes | | 2026-07-10 | `meta-llama/Meta-Llama-3-8B-Instruct-Lite` | No | | 2026-07-10 | `zai-org/GLM-5.1` | Yes | | 2026-06-29 | `Qwen/Qwen3.5-397B-A17B` | Yes | | 2026-06-22 | `zai-org/GLM-5` | No | | 2026-06-11 | `mistralai/Voxtral-Mini-3B-2507` | No | | 2026-06-04 | `Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8` | Yes | | 2026-05-27 | `black-forest-labs/FLUX.1-krea-dev` | No | | 2026-05-21 | `moonshotai/Kimi-K2.5` | No | | 2026-05-14 | `deepseek-ai/DeepSeek-R1` | No | | 2026-05-14 | `deepseek-ai/DeepSeek-V3.1` | Yes | | 2026-05-14 | `Qwen/Qwen3-Coder-Next-FP8` | Yes | | 2026-04-16 | `Qwen/Qwen3-VL-8B-Instruct` | Yes | | 2026-04-16 | `Qwen/Qwen3-235B-A22B-Thinking-2507` | Yes | | 2026-04-16 | `mistralai/Mixtral-8x7B-Instruct-v0.1` | Yes | | 2026-04-03 | `ServiceNow-AI/Apriel-1.5-15b-Thinker` | No | | 2026-04-03 | `ServiceNow-AI/Apriel-1.6-15b-Thinker` | No | | 2026-04-02 | `zai-org/GLM-4.5-Air-FP8` | No | | 2026-04-02 | `zai-org/GLM-4.7` | No | | 2026-04-02 | `mistralai/Mistral-Small-24B-Instruct-2501` | No | | 2026-04-02 | `Qwen/Qwen3-Next-80B-A3B-Instruct` | Yes | | 2026-03-31 | `meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | Yes | | 2026-03-06 | `mixedbread-ai/Mxbai-Rerank-Large-V2` | No | | 2026-03-06 | `meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo` | Yes | | 2026-03-06 | `Qwen/Qwen3-235B-A22B-Thinking-2507` | Yes | | 2026-03-06 | `moonshotai/Kimi-K2-Thinking` | No | | 2026-03-06 | `moonshotai/Kimi-K2-Instruct-0905` | No | | 2026-03-06 | `meta-llama/Llama-3.2-3B-Instruct-Turbo` | No | | 2026-02-25 | `black-forest-labs/FLUX.1-dev` | No | | 2026-02-25 | `black-forest-labs/FLUX.1-dev-lora` | No | | 2026-02-25 | `black-forest-labs/FLUX.1-Kontext-dev` | No | | 2026-02-25 | `Qwen/Qwen3-VL-32B-Instruct` | No | | 2026-02-25 | `meta-llama/Llama-3.2-3B-Instruct-Turbo-Classifier` | No | | 2026-02-25 | `mistralai/Ministral-3-14B-Instruct` | No | | 2026-02-25 | `Qwen/Qwen3-Next-80B-A3B-Thinking` | No | | 2026-02-25 | `Alibaba-NLP/gte-modernbert-base` | No | | 2026-02-25 | `BAAI/bge-base-en-v1.5-vllm` | No | | 2026-02-25 | `meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo` | No | | 2026-02-25 | `meta-llama/Llama-Guard-3-11B-Vision-Turbo` | No | | 2026-02-25 | `meta-llama/LlamaGuard-2-8b` | No | | 2026-02-25 | `marin-community/Marin-8B-Instruct` | No | | 2026-02-25 | `nvidia/Nvidia-Nemotron-Nano-9B-v2` | No | | 2026-02-06 | `togethercomputer/m2-bert-80M-32k-retrieval` | No | | 2026-02-06 | `Salesforce/Llama-Rank-V1` | No | | 2026-02-06 | `togethercomputer/Refuel-Llm-V2` | No | | 2026-02-06 | `togethercomputer/Refuel-Llm-V2-Small` | No | | 2026-02-06 | `Qwen/Qwen3-235B-A22B-fp8-tput` | No | | 2026-02-06 | `qwen-qwen2-5-14b-instruct-lora` | No | | 2026-02-06 | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | Yes | | 2026-02-06 | `Qwen/Qwen2.5-72B-Instruct-Turbo` | No | | 2026-02-06 | `meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo` | No | | 2026-02-06 | `BAAI/bge-large-en-v1.5` | No | | 2026-02-03 | `deepseek-ai/DeepSeek-R1-0528-tput` | No | | 2026-01-05 | `Qwen/Qwen2.5-VL-72B-Instruct` | No | | 2025-12-23 | `deepseek-ai/DeepSeek-R1-Distill-Llama-70B` | No | | 2025-12-23 | `meta-llama/Meta-Llama-3-70B-Instruct-Turbo` | No | | 2025-12-23 | `black-forest-labs/FLUX.1-schnell-free` | No | | 2025-12-23 | `meta-llama/Meta-Llama-Guard-3-8B` | No | | 2025-11-19 | `deepcogito/cogito-v2-preview-deepseek-671b` | No | | 2025-07-25 | `arcee-ai/caller` | No | | 2025-07-25 | `arcee-ai/arcee-blitz` | No | | 2025-07-25 | `arcee-ai/virtuoso-medium-v2` | No | | 2025-11-17 | `arcee-ai/virtuoso-large` | No | | 2025-11-17 | `arcee-ai/maestro-reasoning` | No | | 2025-11-17 | `arcee_ai/arcee-spotlight` | No | | 2025-11-17 | `arcee-ai/coder-large` | No | | 2025-11-13 | `deepseek-ai/DeepSeek-R1-Distill-Qwen-14B` | No | | 2025-11-13 | `mistralai/Mistral-7B-Instruct-v0.1` | No | | 2025-11-13 | `Qwen/Qwen2.5-Coder-32B-Instruct` | No | | 2025-11-13 | `Qwen/QwQ-32B` | No | | 2025-11-13 | `deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free` | No | | 2025-11-13 | `meta-llama/Llama-3.3-70B-Instruct-Turbo-Free` | No | | 2025-08-28 | `Qwen/Qwen2-VL-72B-Instruct` | No | | 2025-08-28 | `nvidia/Llama-3.1-Nemotron-70B-Instruct-HF` | No | | 2025-08-28 | `perplexity-ai/r1-1776` | No | | 2025-08-28 | `meta-llama/Meta-Llama-3-8B-Instruct` | No | | 2025-08-28 | `google/gemma-2-27b-it` | No | | 2025-08-28 | `Qwen/Qwen2-72B-Instruct` | No | | 2025-08-28 | `meta-llama/Llama-Vision-Free` | No | | 2025-08-28 | `Qwen/Qwen2.5-14B` | No | | 2025-08-28 | `meta-llama-llama-3-3-70b-instruct-lora` | No | | 2025-08-28 | `meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo` | No | | 2025-08-28 | `NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO` | No | | 2025-08-28 | `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` | No | | 2025-08-28 | `black-forest-labs/FLUX.1-depth` | No | | 2025-08-28 | `black-forest-labs/FLUX.1-redux` | No | | 2025-08-28 | `meta-llama/Llama-3-8b-chat-hf` | No | | 2025-08-28 | `black-forest-labs/FLUX.1-canny` | No | | 2025-08-28 | `meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo` | No | | 2025-06-13 | `gryphe-mythomax-l2-13b` | No | | 2025-06-13 | `mistralai-mixtral-8x22b-instruct-v0-1` | No | | 2025-06-13 | `mistralai-mixtral-8x7b-v0-1` | No | | 2025-06-13 | `togethercomputer-m2-bert-80m-2k-retrieval` | No | | 2025-06-13 | `togethercomputer-m2-bert-80m-8k-retrieval` | No | | 2025-06-13 | `whereisai-uae-large-v1` | No | | 2025-06-13 | `google-gemma-2-9b-it` | No | | 2025-06-13 | `google-gemma-2b-it` | No | | 2025-06-13 | `gryphe-mythomax-l2-13b-lite` | No | | 2025-05-16 | `meta-llama-llama-3-2-3b-instruct-turbo-lora` | No | | 2025-05-16 | `meta-llama-meta-llama-3-8b-instruct-turbo` | No | | 2025-04-24 | `meta-llama/Llama-2-13b-chat-hf` | No | | 2025-04-24 | `meta-llama-meta-llama-3-70b-instruct-turbo` | No | | 2025-04-24 | `meta-llama-meta-llama-3-1-8b-instruct-turbo-lora` | No | | 2025-04-24 | `meta-llama-meta-llama-3-1-70b-instruct-turbo-lora` | No | | 2025-04-24 | `meta-llama-llama-3-2-1b-instruct-lora` | No | | 2025-04-24 | `microsoft-wizardlm-2-8x22b` | No | | 2025-04-24 | `upstage-solar-10-7b-instruct-v1` | No | | 2025-04-14 | `stabilityai/stable-diffusion-xl-base-1.0` | No | | 2025-04-04 | `meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo-lora` | No | | 2025-03-27 | `mistralai/Mistral-7B-v0.1` | No | | 2025-03-25 | `Qwen/QwQ-32B-Preview` | No | | 2025-03-13 | `databricks-dbrx-instruct` | No | | 2025-03-11 | `meta-llama/Meta-Llama-3-70B-Instruct-Lite` | No | | 2025-03-08 | `Meta-Llama/Llama-Guard-7b` | No | | 2025-02-06 | `sentence-transformers/msmarco-bert-base-dot-v5` | No | | 2025-02-06 | `bert-base-uncased` | No | | 2024-10-29 | `Qwen/Qwen1.5-72B-Chat` | No | | 2024-10-29 | `Qwen/Qwen1.5-110B-Chat` | No | | 2024-10-07 | `NousResearch/Nous-Hermes-2-Yi-34B` | No | | 2024-10-07 | `NousResearch/Hermes-3-Llama-3.1-405B-Turbo` | No | | 2024-08-22 | `NousResearch/Nous-Hermes-2-Mistral-7B-DPO` | No | | 2024-08-22 | `SG161222/Realistic_Vision_V3.0_VAE` | No | | 2024-08-22 | `meta-llama/Llama-2-70b-chat-hf` | No | | 2024-08-22 | `mistralai/Mixtral-8x22B` | No | | 2024-08-22 | `Phind/Phind-CodeLlama-34B-v2` | No | | 2024-08-22 | `meta-llama/Meta-Llama-3-70B` | No | | 2024-08-22 | `teknium/OpenHermes-2p5-Mistral-7B` | No | | 2024-08-22 | `openchat/openchat-3.5-1210` | No | | 2024-08-22 | `WizardLM/WizardCoder-Python-34B-V1.0` | No | | 2024-08-22 | `NousResearch/Nous-Hermes-2-Mixtral-8x7B-SFT` | No | | 2024-08-22 | `NousResearch/Nous-Hermes-Llama2-13b` | No | | 2024-08-22 | `zero-one-ai/Yi-34B-Chat` | No | | 2024-08-22 | `codellama/CodeLlama-34b-Instruct-hf` | No | | 2024-08-22 | `codellama/CodeLlama-34b-Python-hf` | No | | 2024-08-22 | `teknium/OpenHermes-2-Mistral-7B` | No | | 2024-08-22 | `Qwen/Qwen1.5-14B-Chat` | No | | 2024-08-22 | `stabilityai/stable-diffusion-2-1` | No | | 2024-08-22 | `meta-llama/Llama-3-8b-hf` | No | | 2024-08-22 | `prompthero/openjourney` | No | | 2024-08-22 | `runwayml/stable-diffusion-v1-5` | No | | 2024-08-22 | `wavymulder/Analog-Diffusion` | No | | 2024-08-22 | `Snowflake/snowflake-arctic-instruct` | No | | 2024-08-22 | `deepseek-ai/deepseek-coder-33b-instruct` | No | | 2024-08-22 | `Qwen/Qwen1.5-7B-Chat` | No | | 2024-08-22 | `Qwen/Qwen1.5-32B-Chat` | No | | 2024-08-22 | `cognitivecomputations/dolphin-2.5-mixtral-8x7b` | No | | 2024-08-22 | `garage-bAInd/Platypus2-70B-instruct` | No | | 2024-08-22 | `google/gemma-7b-it` | No | | 2024-08-22 | `meta-llama/Llama-2-7b-chat-hf` | No | | 2024-08-22 | `Qwen/Qwen1.5-32B` | No | | 2024-08-22 | `Open-Orca/Mistral-7B-OpenOrca` | No | | 2024-08-22 | `codellama/CodeLlama-13b-Instruct-hf` | No | | 2024-08-22 | `NousResearch/Nous-Capybara-7B-V1p9` | No | | 2024-08-22 | `lmsys/vicuna-13b-v1.5` | No | | 2024-08-22 | `Undi95/ReMM-SLERP-L2-13B` | No | | 2024-08-22 | `Undi95/Toppy-M-7B` | No | | 2024-08-22 | `meta-llama/Llama-2-13b-hf` | No | | 2024-08-22 | `codellama/CodeLlama-70b-Instruct-hf` | No | | 2024-08-22 | `snorkelai/Snorkel-Mistral-PairRM-DPO` | No | | 2024-08-22 | `togethercomputer/LLaMA-2-7B-32K-Instruct` | No | | 2024-08-22 | `Austism/chronos-hermes-13b` | No | | 2024-08-22 | `Qwen/Qwen1.5-72B` | No | | 2024-08-22 | `zero-one-ai/Yi-34B` | No | | 2024-08-22 | `codellama/CodeLlama-7b-Instruct-hf` | No | | 2024-08-22 | `togethercomputer/evo-1-131k-base` | No | | 2024-08-22 | `codellama/CodeLlama-70b-hf` | No | | 2024-08-22 | `WizardLM/WizardLM-13B-V1.2` | No | | 2024-08-22 | `meta-llama/Llama-2-7b-hf` | No | | 2024-08-22 | `google/gemma-7b` | No | | 2024-08-22 | `Qwen/Qwen1.5-1.8B-Chat` | No | | 2024-08-22 | `Qwen/Qwen1.5-4B-Chat` | No | | 2024-08-22 | `lmsys/vicuna-7b-v1.5` | No | | 2024-08-22 | `zero-one-ai/Yi-6B` | No | | 2024-08-22 | `Nexusflow/NexusRaven-V2-13B` | No | | 2024-08-22 | `google/gemma-2b` | No | | 2024-08-22 | `Qwen/Qwen1.5-7B` | No | | 2024-08-22 | `NousResearch/Nous-Hermes-llama-2-7b` | No | | 2024-08-22 | `togethercomputer/alpaca-7b` | No | | 2024-08-22 | `Qwen/Qwen1.5-14B` | No | | 2024-08-22 | `codellama/CodeLlama-70b-Python-hf` | No | | 2024-08-22 | `Qwen/Qwen1.5-4B` | No | | 2024-08-22 | `togethercomputer/StripedHyena-Hessian-7B` | No | | 2024-08-22 | `allenai/OLMo-7B-Instruct` | No | | 2024-08-22 | `togethercomputer/RedPajama-INCITE-7B-Instruct` | No | | 2024-08-22 | `togethercomputer/LLaMA-2-7B-32K` | No | | 2024-08-22 | `togethercomputer/RedPajama-INCITE-7B-Base` | No | | 2024-08-22 | `Qwen/Qwen1.5-0.5B-Chat` | No | | 2024-08-22 | `microsoft/phi-2` | No | | 2024-08-22 | `Qwen/Qwen1.5-0.5B` | No | | 2024-08-22 | `togethercomputer/RedPajama-INCITE-7B-Chat` | No | | 2024-08-22 | `togethercomputer/RedPajama-INCITE-Chat-3B-v1` | No | | 2024-08-22 | `togethercomputer/GPT-JT-Moderation-6B` | No | | 2024-08-22 | `Qwen/Qwen1.5-1.8B` | No | | 2024-08-22 | `togethercomputer/RedPajama-INCITE-Instruct-3B-v1` | No | | 2024-08-22 | `togethercomputer/RedPajama-INCITE-Base-3B-v1` | No | | 2024-08-22 | `WhereIsAI/UAE-Large-V1` | No | | 2024-08-22 | `allenai/OLMo-7B` | No | | 2024-08-22 | `togethercomputer/evo-1-8k-base` | No | | 2024-08-22 | `WizardLM/WizardCoder-15B-V1.0` | No | | 2024-08-22 | `codellama/CodeLlama-13b-Python-hf` | No | | 2024-08-22 | `allenai-olmo-7b-twin-2t` | No | | 2024-08-22 | `sentence-transformers/msmarco-bert-base-dot-v5` | No | | 2024-08-22 | `codellama/CodeLlama-7b-Python-hf` | No | | 2024-08-22 | `hazyresearch/M2-BERT-2k-Retrieval-Encoder-V1` | No | | 2024-08-22 | `bert-base-uncased` | No | | 2024-08-22 | `mistralai/Mistral-7B-Instruct-v0.1-json` | No | | 2024-08-22 | `mistralai/Mistral-7B-Instruct-v0.1-tools` | No | | 2024-08-22 | `togethercomputer-codellama-34b-instruct-json` | No | | 2024-08-22 | `togethercomputer-codellama-34b-instruct-tools` | No | | **Notes on model support:** | | | * The support column reflects the current [supported models](/docs/dedicated-endpoints/models) catalog for dedicated model inference and is updated automatically as the catalog changes. * Models marked "Yes" can be deployed as on-demand dedicated endpoints, either under the listed ID or as the underlying base model of a serving variant (for example, a deprecated `-FP8` or `-Turbo` ID). * Models marked "No" are not available as on-demand endpoints and require migration to a different model or a monthly reserved dedicated endpoint. ### Fine-tuning The table below lists all models removed from the fine-tuning service, most recent first. These models can no longer be used as a base model for a fine-tuning job. Where a close equivalent exists, the suggested replacement is listed. A blank cell means there is no direct equivalent. See [Supported models](/docs/fine-tuning/supported-models) for the full list of models available today. | Removal date | Model | Suggested replacement | | :- | :- | :- | | 2026-09-11 | `nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16` | | | 2026-09-11 | `nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16` | | | 2026-09-11 | `Qwen/Qwen3.5-35B-A3B-Base` | `Qwen/Qwen3.5-35B-A3B` | | 2026-07-29 | `nvidia/NVIDIA-Nemotron-Nano-9B-v2` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen3-Next-80B-A3B-Instruct` | `Qwen/Qwen3.5-122B-A10B` | | 2026-07-29 | `Qwen/Qwen3-Next-80B-A3B-Thinking` | `Qwen/Qwen3.5-122B-A10B` | | 2026-07-29 | `Qwen/Qwen3-0.6B` | `Qwen/Qwen3.5-0.8B` | | 2026-07-29 | `Qwen/Qwen3-0.6B-Base` | `Qwen/Qwen3.5-0.8B` | | 2026-07-29 | `Qwen/Qwen3-1.7B` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `Qwen/Qwen3-1.7B-Base` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `Qwen/Qwen3-4B` | `Qwen/Qwen3.5-4B` | | 2026-07-29 | `Qwen/Qwen3-4B-Base` | `Qwen/Qwen3.5-4B` | | 2026-07-29 | `Qwen/Qwen3-8B` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen3-8B-Base` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen3-14B` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen3-14B-Base` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen3-32B` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen3-30B-A3B-Base` | `Qwen/Qwen3.6-35B-A3B` | | 2026-07-29 | `Qwen/Qwen3-30B-A3B` | `Qwen/Qwen3.6-35B-A3B` | | 2026-07-29 | `Qwen/Qwen3-30B-A3B-Instruct-2507` | `Qwen/Qwen3.6-35B-A3B` | | 2026-07-29 | `Qwen/Qwen3-235B-A22B` | `Qwen/Qwen3.5-397B-A17B` | | 2026-07-29 | `Qwen/Qwen3-235B-A22B-Instruct-2507` | `Qwen/Qwen3.5-397B-A17B` | | 2026-07-29 | `Qwen/Qwen3-Coder-30B-A3B-Instruct` | `Qwen/Qwen3.6-35B-A3B` | | 2026-07-29 | `Qwen/Qwen3-Coder-480B-A35B-Instruct` | | | 2026-07-29 | `Qwen/Qwen3-VL-8B-Instruct` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen3-VL-32B-Instruct` | | | 2026-07-29 | `Qwen/Qwen3-VL-30B-A3B-Instruct` | `Qwen/Qwen3.5-4B` | | 2026-07-29 | `Qwen/Qwen3-VL-235B-A22B-Instruct` | | | 2026-07-29 | `Qwen/Qwen2.5-72B-Instruct` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `Qwen/Qwen2.5-72B` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `Qwen/Qwen2.5-32B-Instruct` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen2.5-32B` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen2.5-14B-Instruct` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen2.5-14B` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `Qwen/Qwen2.5-7B-Instruct` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen2.5-7B` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen2.5-3B-Instruct` | `Qwen/Qwen3.5-4B` | | 2026-07-29 | `Qwen/Qwen2.5-3B` | `Qwen/Qwen3.5-4B` | | 2026-07-29 | `Qwen/Qwen2.5-1.5B-Instruct` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `Qwen/Qwen2.5-1.5B` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `Qwen/Qwen2-72B-Instruct` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `Qwen/Qwen2-72B` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `Qwen/Qwen2-7B-Instruct` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen2-7B` | `Qwen/Qwen3.5-9B` | | 2026-07-29 | `Qwen/Qwen2-1.5B-Instruct` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `Qwen/Qwen2-1.5B` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `moonshotai/Kimi-K2.5` | `moonshotai/Kimi-K2.6` | | 2026-07-29 | `moonshotai/Kimi-K2-Thinking` | `moonshotai/Kimi-K2.6` | | 2026-07-29 | `moonshotai/Kimi-K2-Instruct-0905` | `moonshotai/Kimi-K2.6` | | 2026-07-29 | `moonshotai/Kimi-K2-Instruct` | `moonshotai/Kimi-K2.6` | | 2026-07-29 | `moonshotai/Kimi-K2-Base` | `moonshotai/Kimi-K2.6` | | 2026-07-29 | `zai-org/GLM-5` | `zai-org/GLM-5.1` | | 2026-07-29 | `zai-org/GLM-4.7` | `zai-org/GLM-5.1` | | 2026-07-29 | `zai-org/GLM-4.6` | `zai-org/GLM-5.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1-0528` | `deepseek-ai/DeepSeek-V3.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1` | `deepseek-ai/DeepSeek-V3.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-V3-0324` | `deepseek-ai/DeepSeek-V3.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-V3` | `deepseek-ai/DeepSeek-V3.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-V3.1-Base` | `deepseek-ai/DeepSeek-V3.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-V3-Base` | `deepseek-ai/DeepSeek-V3.1` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1-Distill-Llama-70B` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1-Distill-Llama-70B-32k` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1-Distill-Llama-70B-131k` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1-Distill-Qwen-14B` | `Qwen/Qwen3.5-27B` | | 2026-07-29 | `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` | `Qwen/Qwen3.5-2B` | | 2026-07-29 | `meta-llama/Llama-4-Scout-17B-16E` | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | | 2026-07-29 | `meta-llama/Llama-4-Maverick-17B-128E` | `meta-llama/Llama-4-Maverick-17B-128E-Instruct` | | 2026-07-29 | `meta-llama/Llama-3.3-70B-32k-Instruct-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Llama-3.3-70B-131k-Instruct-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Llama-3.2-3B-Instruct` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Llama-3.2-3B` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Llama-3.2-1B-Instruct` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Llama-3.2-1B` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-8B-131k-Instruct-Reference` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-8B-Reference` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-8B-131k-Reference` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-70B-Instruct-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-70B-32k-Instruct-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-70B-131k-Instruct-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-70B-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-70B-32k-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-70B-131k-Reference` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-405B-Instruct-Reference` | | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-405B-Reference` | | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-405B-10k-Instruct-Reference` | | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-405B-10k-Reference` | | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-405B-8k-Instruct-Reference` | | | 2026-07-29 | `meta-llama/Meta-Llama-3.1-405B-8k-Reference` | | | 2026-07-29 | `meta-llama/Meta-Llama-3-8B-Instruct` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3-8B` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | | 2026-07-29 | `meta-llama/Meta-Llama-3-70B-Instruct` | `meta-llama/Llama-3.3-70B-Instruct-Reference` | | 2026-07-29 | `google/gemma-3-270m` | `Qwen/Qwen3.5-0.8B` | | 2026-07-29 | `google/gemma-3-270m-it` | `Qwen/Qwen3.5-0.8B` | | 2026-07-29 | `google/gemma-3-1b-it` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-1b-pt` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-4b-it` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-4b-it-VLM` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-4b-pt` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-12b-it` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-12b-it-VLM` | `google/gemma-4-31B-it-VLM` | | 2026-07-29 | `google/gemma-3-12b-pt` | `google/gemma-4-26B-A4B-it` | | 2026-07-29 | `google/gemma-3-27b-it` | `google/gemma-4-31B-it` | | 2026-07-29 | `google/gemma-3-27b-it-VLM` | `google/gemma-4-31B-it-VLM` | | 2026-07-29 | `google/gemma-3-27b-pt` | `google/gemma-4-31B-it` | | 2026-07-29 | `mistralai/Mixtral-8x7B-v0.1` | `mistralai/Mixtral-8x7B-Instruct-v0.1` | | 2026-07-29 | `mistralai/Mistral-7B-Instruct-v0.2` | `mistralai/Mixtral-8x7B-Instruct-v0.1` | | 2026-07-29 | `mistralai/Mistral-7B-v0.1` | `mistralai/Mixtral-8x7B-Instruct-v0.1` | | 2026-07-29 | `togethercomputer/llama-2-7b-chat` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | ## Recommended actions * Regularly check this page for updates on model deprecations. * Plan your migration well in advance of the removal date to ensure a smooth transition. * If you have any questions or need assistance with migration, contact the Together AI support team. For the most up-to-date information on model availability, support, and recommended alternatives, check the API documentation or contact the Together AI support team. # DSPy Source: https://docs.together.ai/docs/dspy Use DSPy to program language models with Together AI. DSPy is a framework for programming language models rather than relying on static prompts. It enables you to build modular AI systems with code instead of hand-crafted prompting, and it offers methods to automatically optimize these systems. Features * Programmatic approach to LLM interactions through Python. * Modular components for building complex AI pipelines. * Self-improvement algorithms that optimize prompts and weights. * Support for various applications from simple classifiers to RAG systems and agent loops. ## Installing libraries ```shell Shell theme={null} uv add dspy ``` Set your Together API key: ```shell Shell theme={null} export TOGETHER_API_KEY=*** ``` ## Example Set up and connect DSPy to LLMs on Together AI. ```python Python theme={null} import dspy # Configure dspy with an LLM from Together AI lm = dspy.LM( "together_ai/Qwen/Qwen3.5-9B", api_key=os.environ.get("TOGETHER_API_KEY"), api_base="https://api.together.ai/v1", ) # Now you can call the LLM directly as follows lm("Say this is a test!", temperature=0.7) # => ['This is a test!'] lm( messages=[{"role": "user", "content": "Say this is a test!"}] ) # => ['This is a test!'] ``` Now you can set up a DSPy module, like `dspy.ReAct` with a task-specific signature. For example, `question -> answer: float` tells the module to take a question and to produce a floating point number answer below. ```python Python theme={null} # Configure dspy to use the LLM dspy.configure(lm=lm) # Gives the agent access to a python interpreter def evaluate_math(expression: str): return dspy.PythonInterpreter({}).execute(expression) # Gives the agent access to a wikipedia search tool def search_wikipedia(query: str): results = dspy.ColBERTv2(url="http://20.102.90.50:2017/wiki17_abstracts")( query, k=3 ) return [x["text"] for x in results] # setup ReAct module with question and math answer signature react = dspy.ReAct( "question -> answer: float", tools=[evaluate_math, search_wikipedia], ) pred = react( question="What is 9362158 divided by the year of birth of David Gregory of Kinnairdy castle?" ) print(pred.answer) ``` ## Next steps > [!NOTE] > > ### DSPy - Together AI notebook > > Learn more about building agents using DSPy with Together AI in this [notebook](https://github.com/togethercomputer/together-cookbook/blob/main/agents/DSPy/DSPy_Agents.ipynb). # Error codes Source: https://docs.together.ai/docs/error-codes Look up API error status codes, their causes, and quick fixes. | Code | Cause | Solution | | - | - | - | | 400 - Invalid Request | The request is misconfigured, the input token count plus `max_tokens` exceeds the model's [context length](/docs/inference-models), or a request to the [dedicated model inference](/docs/dedicated-endpoints/overview) management API includes an unknown field. | Check that the request is [valid JSON](/reference/chat-completions) and your [API key](https://api.together.ai/settings/projects/~current/api-keys) is correct. Use the prompt format the model expects, which differs between Mistral and Llama models. If the request exceeds the context length, lower `max_tokens`. For a chat model, you can also set `max_tokens` to `null` to let the model decide when to stop generating. If a management API request returns an `unknown field "..."` error, [remove the named field](/docs/dedicated-endpoints/manage#troubleshooting). | | 401 - Authentication Error | The API key is missing or invalid. | Check that you're using the correct [API key](https://api.together.ai/settings/projects/~current/api-keys) and [passing it correctly](/reference/chat-completions). | | 402 - Payment Required | Your organization's balance has reached its [spend cut-off](/docs/billing-spend-controls) (\$0 for prepaid accounts), or the model requires a positive credit balance. | [Add credits](https://api.together.ai/settings/organization/~current/billing) to resume service. If you've already paid, wait up to 5 minutes for your balance to update, then retry. | | 403 - Forbidden | Your account can't access the requested model or feature. For example, your plan doesn't include the model, the model requires a credit card on file, your organization has turned off [passthrough models](/docs/privacy-and-security#passthrough-third-party-models), or the account is blocked. | The error message names the reason. Upgrade your plan or add a payment method in your [billing settings](https://api.together.ai/settings/organization/~current/billing), or ask an organization admin to turn on passthrough models. If your account is blocked, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). | | 404 - Not Found | The endpoint URL or model name is invalid. | Check that the endpoint URL matches the [API reference](/reference/chat-completions) and that the [model you're querying is available](/docs/inference-models). | | 413 - Request Entity Too Large | The request body is larger than the endpoint accepts. Limits vary by endpoint. | Reduce the request size. Pass large images or audio as a URL instead of embedding them in the request body. Direct audio uploads are capped at 80 MB (see [transcription limits](/docs/inference/transcription/overview#limits)). | | 429 - Too Many Requests | Together is limiting serverless requests during high demand, or a deployment on a [dedicated endpoint](/docs/dedicated-endpoints/manage) would exceed your project's or organization's GPU quota for its GPU type. | For serverless [rate limiting](/docs/serverless/rate-limits), reduce your request rate, spread out bursts, and retry with exponential backoff. For GPU quota, lower the requested replica count, stop unused deployments on that GPU type, or [contact support](https://portal.usepylon.com/together-ai/forms/support-request) to raise the quota. If the platform itself is out of capacity for that GPU type, retry later. | | 500 - Server Error | An unknown server error occurred. | Wait briefly, then retry. If the error persists, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). | | 503 - Service Unavailable | The service is temporarily unavailable, for example during high demand. | Wait briefly, then retry with exponential backoff. If the error persists, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). | | 504 - Timeout | The request didn't complete in time. | Wait briefly, then retry. If the error persists, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). | | 524 - Cloudflare Timeout | The connection timed out at the network edge. | Wait briefly, then retry. If the error persists, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). | | 529 - Overloaded | The model has reached its maximum replica count and can't take more requests. | Wait briefly, then retry with exponential backoff. If the error persists, [contact support](https://portal.usepylon.com/together-ai/forms/support-request) to raise the model's maximum replica count. | If you see an error code that isn't listed here, or a solution doesn't resolve the error, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). # Parameters and result formats Source: https://docs.together.ai/docs/evaluations-reference Parameters, result formats, and template syntax for the evaluations API. Reference for the parameters, result formats, and templates used by the evaluations API. For concepts, see [Evaluations](/docs/ai-evaluations). For the full request schema, see the [create evaluation](/reference/create-evaluation) API reference. ## Judge configuration The `judge` object configures the model that assesses each input. It is required for every evaluation type. | Parameter | Type | Default | Description | | - | - | - | - | | `model` | `string` | required | Model ID, dedicated endpoint ID, or external shortcut for the judge. | | `model_source` | `string` | required | One of `serverless`, `dedicated`, or `external`. | | `system_template` | `string` | required | Jinja2 template with the judge's assessment instructions. | | `external_api_token` | `string` | none | Provider API token. Required when `model_source` is `external`. | | `external_base_url` | `string` | none | Custom OpenAI `chat/completions`-compatible base URL for external models. | | `max_tokens` | `int` | `32768` | Maximum tokens the judge can generate. Increase for reasoning models that spend output budget on chain-of-thought. | | `temperature` | `float` | `0.05` | Sampling temperature for the judge. | | `num_workers` | `int` | varies | Concurrent judge inference workers. Defaults: `serverless` 25, `dedicated` 5 (minimum), `external` 2 with a provider shortcut or 20 when `external_base_url` is set. | During execution, the service appends its own output-format instruction to the judge's prompt, requiring a JSON response with a `feedback` field and the verdict (a `label`, `score`, or choice). Judge responses that don't parse into a valid verdict are counted in `invalid_label_count` or `invalid_score_count` in the results. ## Model configuration `model_to_evaluate`, `model_a`, and `model_b` each accept either a `string` naming a dataset column that already holds responses, or a model configuration object that generates fresh responses. The object uses these fields. | Parameter | Type | Default | Description | | - | - | - | - | | `model` | `string` | required | Serverless model ID, dedicated endpoint ID, or external shortcut. | | `model_source` | `string` | required | One of `serverless`, `dedicated`, or `external`. | | `system_template` | `string` | required | Jinja2 template with generation instructions. | | `input_template` | `string` | required | Jinja2 template that formats the dataset input, for example `{{prompt}}`. | | `max_tokens` | `int` | `1024` | Maximum tokens for generation. | | `temperature` | `float` | `0.05` | Sampling temperature for generation. | | `external_api_token` | `string` | none | Provider API token. Required when `model_source` is `external`. | | `external_base_url` | `string` | none | Custom OpenAI-compatible base URL for external models. | | `num_workers` | `int` | varies | Concurrent inference workers, with the same defaults as the judge. | ## Evaluation type parameters Every type also requires `input_data_file_path`, the file ID of the uploaded dataset. ### Classify | Parameter | Type | Default | Description | | - | - | - | - | | `labels` | `list[string]` | required | Classification categories the judge chooses from. | | `pass_labels` | `list[string]` | required | Labels counted as passing for the pass percentage. At least one label must be listed. | | `model_to_evaluate` | `object` or `string` | required | Model configuration object, or a dataset column name. | ### Score | Parameter | Type | Default | Description | | - | - | - | - | | `min_score` | `float` | required | Minimum score the judge can assign. | | `max_score` | `float` | required | Maximum score the judge can assign. | | `pass_threshold` | `float` | required | Score at or above which a sample is considered passing. Must be between `min_score` and `max_score`. | | `model_to_evaluate` | `object` or `string` | required | Model configuration object, or a dataset column name. | ### Compare | Parameter | Type | Default | Description | | - | - | - | - | | `model_a` | `object` or `string` | required | First model configuration object, or a dataset column name. | | `model_b` | `object` or `string` | required | Second model configuration object, or a dataset column name. | | `disable_position_bias_correction` | `boolean` | `false` | When `false`, the judge runs twice per sample with positions swapped and the verdicts are reconciled to cancel position bias. Set to `true` to run a single original-order pass, roughly halving judge cost and latency. | When both `model_a` and `model_b` are configuration objects, their inference runs execute in parallel. Under the default two-pass correction, the winner is declared only when both passes agree. Disagreement is recorded as a tie. If only one pass produces a parseable verdict, that verdict decides, and the row is flagged with `is_invalid_judge_output` in the result file. ## Dataset columns Every column in the input dataset must be used by the job. A column counts as used when it is one of the following: * **Template-referenced:** Injected with a `{{column_name}}` placeholder in any model or judge `system_template` or `input_template`. A nested reference like `{{info.question}}` counts for its top-level column, `info`. * **A pre-generated response column:** Named as the string value of `model_to_evaluate`, `model_a`, or `model_b`. * **The image column:** `image_data_urls`, for [vision evaluations](/docs/run-an-evaluation#prepare-a-dataset). A dataset with any other column fails validation shortly after the job starts running, ending in `user_error` status with the offending columns listed in `results.error`: ```text Text theme={null} Unsupported dataset column(s): ['category', 'id']. Each column must be referenced by a model or judge template, or be a recognized field ('image_data_urls'). Remove unused columns or reference them in a template. ``` Strip metadata columns such as `id` or `category` before uploading, or keep a column by referencing it in a template, for example passing `{{ground_truth}}` to the judge as a reference answer. ## Job lifecycle Creating a job returns a `workflow_id` and a `pending` status. The job then moves through `queued` and `running` before reaching `completed`. A job that fails ends in `error` (an internal failure) or `user_error` (a problem with the request or dataset), with the failure reason in `results.error`. Retrieving the job returns the current status, a timestamped `status_updates` entry for each transition, the request `parameters`, and, once the job completes, the aggregated `results`: ```json JSON theme={null} { "workflow_id": "eval-7df2-1751287840", "type": "compare", "status": "completed", "status_updates": [ { "status": "pending", "message": "Job created and pending for processing", "timestamp": "2025-06-30T12:50:40.722334754Z" }, { "status": "queued", "message": "Job status updated", "timestamp": "2025-06-30T12:50:47.476306172Z" }, { "status": "running", "message": "Job status updated", "timestamp": "2025-06-30T12:51:02.439097636Z" }, { "status": "completed", "message": "Job status updated", "timestamp": "2025-06-30T12:51:57.261327077Z" } ], "parameters": { "judge": { "model": "openai/gpt-oss-120b", "model_source": "serverless", "system_template": "..." }, "model_a": "response_a", "model_b": "response_b", "input_data_file_path": "file-64febadc-ef84-415d-aabe-1e4e6a5fd9ce" }, "created_at": "2025-06-30T12:50:40.723521Z", "updated_at": "2025-06-30T12:51:57.261342Z", "results": { "A_wins": 1, "B_wins": 13, "Ties": 6, "generation_fail_count": 0, "judge_fail_count": 0, "result_file_id": "file-95c8f0a3-e8cf-43ea-889a-e79b1f1ea1b9" } } ``` ## Result formats A completed job returns aggregated results and a `result_file_id`. The aggregated fields depend on the evaluation type. ### Classify | Field | Type | Description | | - | - | - | | `error` | `string` | Present only when the job fails. | | `label_counts` | `object` | Count of each assigned label, for example `{"positive": 45, "negative": 30}`. | | `pass_percentage` | `float` | Percentage of samples with labels in `pass_labels`. | | `generation_fail_count` | `int` | Failed generations when using a model configuration. | | `judge_fail_count` | `int` | Samples the judge could not evaluate. | | `invalid_label_count` | `int` | Judge responses that could not be parsed into a valid label. | | `result_file_id` | `string` | File ID for the row-level results. | ### Score | Field | Type | Description | | - | - | - | | `error` | `string` | Present only when the job fails. | | `aggregated_scores.mean_score` | `float` | Mean of all numeric scores. | | `aggregated_scores.std_score` | `float` | Standard deviation of scores. | | `aggregated_scores.pass_percentage` | `float` | Percentage of scores meeting the pass threshold. | | `failed_samples` | `int` | Total samples that failed processing. | | `invalid_score_count` | `int` | Scores outside the allowed range or unparseable. | | `generation_fail_count` | `int` | Failed generations when using a model configuration. | | `judge_fail_count` | `int` | Samples the judge could not evaluate. | | `result_file_id` | `string` | File ID for per-sample scores and feedback. | ### Compare | Field | Type | Description | | - | - | - | | `error` | `string` | Present only when the job fails. | | `A_wins` | `int` | Count where model A was preferred. | | `B_wins` | `int` | Count where model B was preferred. | | `Ties` | `int` | Count where the judge found no clear winner. | | `generation_fail_count` | `int` | Failed generations from either model. | | `judge_fail_count` | `int` | Samples the judge could not evaluate. | | `result_file_id` | `string` | File ID for the detailed pairwise decisions. | > [!NOTE] > > Field names above match the raw API response. The Python SDK's typed results object exposes them as snake\_case attributes (`a_wins`, `b_wins`, `ties`). ### Result files Pass the `result_file_id` to the [Files API](/reference/get-files-id-content) to download the full report. Each line holds the original input, any generated responses, the judge's decision and feedback, and an `evaluation_successful` field (`true` or `false`) indicating whether the row was processed successfully. The result file retains every input row. If more than 30% of rows fail generation or judging, the job itself fails instead. For large result files, stream the download line by line instead of buffering it: ```python Python theme={null} from together import Together client = Together() with client.files.with_streaming_response.content( id=result_file_id ) as response: for line in response.iter_lines(): print(line) ``` For a compare evaluation with generated responses, a result line looks like this: ```json JSON theme={null} { "prompt": "What is the capital of France?", "MODEL_TO_EVALUATE_OUTPUT_A": "Paris.", "MODEL_TO_EVALUATE_OUTPUT_B": "The capital of France is Paris, a city on the Seine known for the Eiffel Tower and the Louvre.", "judge_raw_output_original": "{\"feedback\": \"Response B provides the same core information but adds useful context.\", \"choice\": \"B\"}", "judge_raw_output_flipped": "{\"feedback\": \"Response A adds useful context about location and landmarks.\", \"choice\": \"A\"}", "choice_original": "B", "judge_feedback_original_order": "Response B provides the same core information but adds useful context.", "choice_flipped": "B", "judge_feedback_flipped_order": "Response A adds useful context about location and landmarks.", "final_decision": "B", "evaluation_successful": true, "is_invalid_judge_output": false } ``` The two `choice_*` and `judge_feedback_*` pairs come from the two position-bias-correction passes. `choice_flipped` is expressed in original-order terms, so the flipped pass's raw `"A"` above records the same winner. With `disable_position_bias_correction: true`, only the original-order fields are present. Classify and score result lines follow the same pattern, with the judge's `label` or `score` and `feedback` in place of the pairwise fields. ## Templates Both `system_template` and `input_template` support [Jinja2](https://jinja.palletsprojects.com/en/stable/) syntax. Reference a dataset column by wrapping its name in double braces to inject its value into the prompt. Given this dataset row: ```json JSON theme={null} { "prompt": "What is the capital of France?" } ``` And this template: ```python Python theme={null} input_template = "Please answer the following question: {{prompt}}" ``` The rendered input becomes: ```text Text theme={null} Please answer the following question: What is the capital of France? ``` Reference nested fields with dot notation. Given: ```json JSON theme={null} { "info": { "question": "What is the capital of France?", "answer": "Paris" } } ``` Access the nested field with: ```python Python theme={null} input_template = "Please answer: {{info.question}}" ``` Common uses include passing a reference answer to the judge, giving per-row generation instructions, and selecting which columns to send to the model being evaluated. For more Jinja2 functionality, see the [interactive template playground](https://huggingface.co/spaces/huggingfacejs/chat-template-playground) and the [Hugging Face templates guide](https://huggingface.co/blog/chat-templates). # Supported models Source: https://docs.together.ai/docs/evaluations-supported-models Serverless models and external provider shortcuts supported by the evaluations API. The evaluations API supports three model sources for both the judge and the models being evaluated: Together AI serverless models, your own dedicated model inference endpoints, and external provider models. Set the `model_source` field to choose between them. ## Serverless models Set `model_source = "serverless"` to use Together AI serverless inference. The evaluations service keeps its own allowlist of serverless models, separate from the full [serverless catalog](/docs/serverless/models). The models below can serve as the judge or as the model being evaluated; this table syncs daily from the allowlist. | Model | Model ID | | :- | :- | | Qwen3.5 9B FP8 | `Qwen/Qwen3.5-9B` | | Qwen3.6 Plus | `Qwen/Qwen3.6-Plus` | | DeepSeek V4 Pro 0813 | `deepseek-ai/DeepSeek-V4-Pro-0813` | | OpenAI GPT-OSS 120B | `openai/gpt-oss-120b` | | GLM 5.2 | `zai-org/GLM-5.2` | | GLM 5.3 | `zai-org/GLM-5.3` | | GLM 5.3 Flash | `zai-org/GLM-5.3-Flash` | **Example configuration:** ```python Python theme={null} model_config = { "model": "Qwen/Qwen3.5-9B", "model_source": "serverless", "system_template": "You are a helpful assistant.", "input_template": "{{prompt}}", "max_tokens": 4096, "temperature": 0.7, } ``` ### Vision-capable models To evaluate image inputs, use a serverless model that accepts images, such as the Qwen VL family. The evaluated model, and the judge if it should also see the image, must be vision-capable. Browse the [serverless models](/docs/serverless/models) catalog to find models that support vision, and see [the evaluations page](/docs/ai-evaluations#datasets-and-templates) for how to add images to a dataset. ## Dedicated models To evaluate a model served on [dedicated model inference](/docs/dedicated-endpoints/overview), set `model_source = "dedicated"` and enter the endpoint ID (`ep_abc123`, from the deploy output or `tg endpoints ls`) in the `model` field. The endpoint must have a running deployment. Requests fail with `endpoint_not_ready` while it's stopped. In the [evaluations console](https://api.together.ai/evaluations), live dedicated model inference endpoints appear under **My Endpoints** in the model picker. Legacy dedicated endpoints appear under **My Legacy Endpoints**. Only endpoints with at least one live deployment are listed. Selecting an endpoint sets `model_source` to `dedicated` and uses the endpoint name as `model`. **Example configuration:** ```python Python theme={null} model_config = { "model": "", "model_source": "dedicated", "system_template": "You are a helpful assistant.", "input_template": "{{prompt}}", "max_tokens": 512, "temperature": 0.7, } ``` ## External models Set `model_source = "external"` to use models from external providers. > [!WARNING] > > External models require an API token from the provider. Set the `external_api_token` parameter with the provider's API key. ### Supported shortcuts Use these shortcuts in the `model` field, and the API resolves the provider base URL automatically. | Provider | Model | Model ID | | :- | :- | :- | | Anthropic | Claude Haiku 4.5 | `anthropic/claude-haiku-4-5` | | Anthropic | Claude Opus 4.5 | `anthropic/claude-opus-4-5` | | Anthropic | Claude Opus 4.6 | `anthropic/claude-opus-4-6` | | Anthropic | Claude Opus 4.7 | `anthropic/claude-opus-4-7` | | Anthropic | Claude Sonnet 4.5 | `anthropic/claude-sonnet-4-5` | | Anthropic | Claude Sonnet 4.6 | `anthropic/claude-sonnet-4-6` | | Google | Gemini 2.5 Flash | `google/gemini-2.5-flash` | | Google | Gemini 2.5 Flash Lite | `google/gemini-2.5-flash-lite` | | Google | Gemini 2.5 Pro | `google/gemini-2.5-pro` | | Google | Gemini 3 Flash Preview | `google/gemini-3-flash-preview` | | Google | Gemini 3 Pro Preview | `google/gemini-3-pro-preview` | | Google | Gemini 3.1 Flash Lite | `google/gemini-3.1-flash-lite` | | Google | Gemini 3.1 Pro Preview | `google/gemini-3.1-pro-preview` | | OpenAI | GPT-4.1 | `openai/gpt-4.1` | | OpenAI | GPT-4.1 Mini | `openai/gpt-4.1-mini` | | OpenAI | GPT-4.1 Nano | `openai/gpt-4.1-nano` | | OpenAI | GPT-4o | `openai/gpt-4o` | | OpenAI | GPT-4o Mini | `openai/gpt-4o-mini` | | OpenAI | GPT-5.3 Chat Latest | `openai/gpt-5.3-chat-latest` | | OpenAI | GPT-5.4 | `openai/gpt-5.4` | | OpenAI | GPT-5.4 Mini | `openai/gpt-5.4-mini` | | OpenAI | GPT-5.4 Nano | `openai/gpt-5.4-nano` | | OpenAI | GPT-5.5 | `openai/gpt-5.5` | | OpenAI | o3 | `openai/o3` | | OpenAI | o4-mini | `openai/o4-mini` | **Example configuration with a shortcut:** ```python Python theme={null} import os model_config = { "model": "openai/gpt-5.5", "model_source": "external", "external_api_token": os.environ["OPENAI_API_KEY"], "system_template": "You are a helpful assistant.", "input_template": "{{prompt}}", "max_tokens": 512, "temperature": 0.7, } ``` ### Custom base URL To use any OpenAI `chat/completions`-compatible API, specify a custom `external_base_url`: ```python Python theme={null} import os model_config = { "model": "mistral-small-latest", "model_source": "external", "external_api_token": os.environ["MISTRAL_API_KEY"], "external_base_url": "https://api.mistral.ai/", "system_template": "You are a helpful assistant.", "input_template": "{{prompt}}", "max_tokens": 512, "temperature": 0.7, } ``` > [!NOTE] > > The external API must be [OpenAI `chat/completions`-compatible](/docs/inference/openai-compatibility). # Bring your own model Source: https://docs.together.ai/docs/fine-tuning/byom Fine-tune a Hugging Face model that isn't in the Together catalog. Together's bring-your-own-model (BYOM) flow lets you fine-tune a model from a Hugging Face repository that isn't in the official catalog, by pairing a base model from Together (the training template) with your custom checkpoint from Hugging Face (the actual weights to tune). ## When to BYOM Use the BYOM flow when: * **You want to start from a community variant:** A specialized model on Hugging Face (medical, legal, code) sometimes makes a better starting point than a generic base. * **You're continuing your own previous work:** Upload your last checkpoint to Hugging Face and resume training on Together. * **A new model isn't in the catalog yet:** As long as it has a supported architecture under 100B parameters, you can fine-tune it. ## Requirements Your model must meet these constraints: * **Architecture:** CausalLM only (text generation). * **Size:** Under 100 billion parameters. * **Weights:** `.safetensors` format. * **No custom code:** `trust_remote_code=True` is not allowed. * **Access:** The Hugging Face repo is public, or you have an API token with read access. * **Framework compatibility:** Transformers v5.10 or earlier. You'll also need a Together base model whose architecture matches your custom checkpoint (Llama, Qwen, Mistral, Gemma, etc.) and whose `max_seq_length` is no larger than your checkpoint supports. ## Launch the job Launch the job by pairing the base model (template) with `from_hf_model` (your checkpoint): ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3.5-9B" \ --from-hf-model "Qwen/Qwen3.5-9B-Base" \ --n-epochs 3 \ --learning-rate 1e-5 \ --suffix "custom-v1" ``` ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.create( model="Qwen/Qwen3.5-9B", # base template from_hf_model="Qwen/Qwen3.5-9B-Base", # your custom model training_file="", n_epochs=3, learning_rate=1e-5, suffix="custom-v1", # hf_api_token="hf_xxxxxxxxxxxx", # for a private repo # hf_model_revision="abc123def456", # to pin a specific commit ) print(job.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.create({ model: "Qwen/Qwen3.5-9B", from_hf_model: "Qwen/Qwen3.5-9B-Base", training_file: "", n_epochs: 3, learning_rate: 1e-5, suffix: "custom-v1", }); console.log(job.id); ``` | Parameter | Purpose | | - | - | | `model` | A base model from Together's catalog. Its config provides the training template and inference setup. | | `from_hf_model` | The Hugging Face repo with your custom weights. | | `hf_api_token` | Only needed for private repos. Omit for public ones. Passing a dummy value can cause a 400 error. | | `hf_model_revision` | Optional. Pin to a specific commit hash instead of `main`. | ## Pick the base template Match these three variables to pick the base template: * **Architecture:** Must match (treat Code Llama as Llama, etc.). * **Size:** As close to your custom checkpoint as the catalog allows. If every option is larger, pick the smallest. * **Max sequence length:** The base's max must be at least as large as your checkpoint's, and ideally not much larger. For example: `Qwen/Qwen3.5-9B-Base` has Qwen3.5 architecture and 9B parameters. The catalog has a direct match, `Qwen/Qwen3.5-9B`: the same architecture and size, with a max sequence length that covers the checkpoint's. ## Watch and deploy BYOM jobs use the same lifecycle as catalog jobs: * [Poll the job](/docs/fine-tuning/monitoring#poll-until-the-job-is-done) with the SDK or CLI. * Deploy the result on a [dedicated endpoint](/docs/fine-tuning/deployment). Your fine-tuned model appears under **My Models** in the [dashboard](https://api.together.ai/models) once training completes. The base model dictates whether the result can be hosted. If the base model isn't in the [supported models](/docs/dedicated-endpoints/models) list for dedicated model inference, the fine-tune can't be deployed as a dedicated endpoint. Pick a supported base before training. ## Troubleshooting * **Training fails with a CUDA out-of-memory error:** Reduce `batch_size` or use a smaller base template. * **Training fails with a checkpoint validation error:** The architecture doesn't match the base template, or a parameter is out of range. Confirm that the checkpoint is a CausalLM model, and compare its `config.json` with the base template's. * **Training fails with a runtime error:** The checkpoint is likely corrupted or incomplete. Re-upload it to Hugging Face. * **Model uses `trust_remote_code`:** BYOM doesn't support models that need custom code. Use a similar model that doesn't, or [contact support](https://portal.usepylon.com/together-ai/forms/support-request) to ask Together to add the model to the catalog. * **Training fails with an internal error:** The platform notifies the Together team automatically. If the error persists, contact support with the job ID. ## FAQ **Can I fine-tune a low-rank adapter (LoRA)?** Yes. Pass the adapter repo as `from_hf_model` in a [LoRA job](/docs/fine-tuning/lora-vs-full) whose LoRA settings (`lora_r`, `lora_alpha`, `lora_dropout`, and `lora_trainable_modules`) exactly match the adapter's configuration. Training continues from the adapter's weights on top of the base model, without merging the adapter first. The job outputs a trained adapter plus merged weights, like any other LoRA job. **Can I train a model I uploaded for dedicated model inference?** No. Models you [upload for dedicated model inference](/docs/dedicated-endpoints/custom-models) aren't visible to the fine-tuning API. Upload the model to Hugging Face instead, and pass the repo as `from_hf_model`. **Will my fine-tuned model work for inference?** Yes, if the base model you specified is supported, the architecture matches, and training completes successfully. Models built on unsupported architectures may not run reliably. If you need to run one, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). # Data preparation Source: https://docs.together.ai/docs/fine-tuning/data-preparation Format your training file as JSONL or Parquet to match your task, then validate and upload. The fine-tuning API accepts two file formats: JSONL for text data and Parquet for pre-tokenized data. Pick JSONL unless you need to set custom attention masks or labels, or you want to skip tokenization to speed up repeated experiments. The file size limit for either format is 100 GB. The file ID returned by `client.files.upload()` is what you pass as `training_file` to a fine-tuning job. ## Pick a data format Each line of a JSONL file is one training example, formatted to match your task. | Format | When to use | Key fields | | - | - | - | | [Conversational](#conversational-data) | Multi-turn chat or single-turn chat. | `messages` | | [Instruction](#instruction-data) | Prompt and completion pairs. | `prompt`, `completion` | | [Preference](#preference-data) | Paired preferred and dispreferred outputs for [DPO](/docs/fine-tuning/preference-tuning). | `input`, `preferred_output`, `non_preferred_output` | | [Generic text](#generic-text-data) | Free-form text completion. | `text` | | [Tool-calling](#tool-calling-data) | Training a model to invoke tools. | `messages`, `tools` | | [Reasoning](#reasoning-data) | Chain-of-thought data for reasoning models. | `messages` with `reasoning` | If the same file has two possible formats (for example both `text` and `messages`), the server rejects it. Trim unused fields before upload to speed up data transfer. ### Conversational data Conversations are represented using a `messages` array. Each message has a `role` (`system`, `user`, or `assistant`) and `content`. The conversation must start with `system` or `user` and alternate `user` and `assistant` afterwards. ```json theme={null} { "messages": [ {"role": "system", "content": "This is a system prompt."}, {"role": "user", "content": "Hello, how are you?"}, {"role": "assistant", "content": "I'm doing well, thank you! How can I help you?"}, {"role": "user", "content": "Can you explain machine learning?"}, {"role": "assistant", "content": "Machine learning is..."} ] } ``` By default, training computes loss only on `assistant` messages. Pass `train_on_inputs=True` to include the rest. To mask or weight individual messages, set [per-message weights](#data-weights). The dataset is automatically formatted into the model's [chat template](https://huggingface.co/docs/transformers/main/en/chat_templating) if one is defined. Instruction-tuned models always have a chat template. Base models usually don't. Example datasets: * [allenai/WildChat](https://huggingface.co/datasets/allenai/WildChat). * [davanstrien/cosmochat](https://huggingface.co/datasets/davanstrien/cosmochat). ### Instruction data Each line carries a `prompt` and a `completion` field. ```json theme={null} {"prompt": "...", "completion": "..."} {"prompt": "...", "completion": "..."} ``` By default, training computes loss only on `completion`. Pass `train_on_inputs=True` to include `prompt`. To scale a sample's contribution to the loss, set a [sample weight](#data-weights). Example datasets: * [meta-math/MetaMathQA](https://huggingface.co/datasets/meta-math/MetaMathQA). * [glaiveai/glaive-code-assistant](https://huggingface.co/datasets/glaiveai/glaive-code-assistant). ### Generic text data Each line carries a single `text` field. Use this for plain text completions. ```json theme={null} {"text": "..."} {"text": "..."} ``` Example datasets: * [unified\_joke\_explanations.jsonl](https://huggingface.co/datasets/laion/OIG/resolve/main/unified_joke_explanations.jsonl). * [togethercomputer/RedPajama-Data-1T-Sample](https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T-Sample). ### Preference data Used for [preference fine-tuning](/docs/fine-tuning/preference-tuning) with DPO. Each line carries: * `input.messages`: a context in conversational format. * `preferred_output`: a single assistant message representing the ideal response. * `non_preferred_output`: a single assistant message representing the suboptimal response. ```json theme={null} { "input": { "messages": [ {"role": "assistant", "content": "Hi! I'm powered by Together AI's open-source models. Ask me anything."}, {"role": "user", "content": "What's open-source AI?"} ] }, "preferred_output": [ {"role": "assistant", "content": "Open-source AI means models are free to use, modify, and share. Together AI makes it easy to fine-tune and deploy them."} ], "non_preferred_output": [ {"role": "assistant", "content": "It means the code is public."} ] } ``` Each output must contain exactly one assistant message. ### Tool-calling data For [training a model to invoke tools](/docs/fine-tuning/function-calling), the line carries a `tools` array listing the available tools. Assistant messages can include `tool_calls` instead of `content`, and `tool`-role messages carry call results. ```json theme={null} { "messages": [ {"role": "user", "content": "What is the current temperature in San Francisco?"}, {"role": "assistant", "tool_calls": [ {"id": "call_abc123", "type": "function", "function": { "name": "getCurrentWeather", "arguments": "{\"location\": \"San Francisco\"}" }} ]}, {"role": "tool", "content": "{\"temperature\":\"65\",\"unit\":\"fahrenheit\"}"} ], "tools": [ {"type": "function", "function": { "name": "getCurrentWeather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA."} }, "required": ["location"] } }} ] } ``` For preference fine-tuning, the `tools` field nests inside `input`: ```json theme={null} { "input": { "messages": [{"role": "user", "content": "What is the current temperature in San Francisco?"}], "tools": [ {"type": "function", "function": { "name": "getCurrentWeather", "description": "Get the current weather in a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]} }} ] }, "preferred_output": [ {"role": "assistant", "tool_calls": [ {"id": "call_abc123", "type": "function", "function": { "name": "getCurrentWeather", "arguments": "{\"location\": \"San Francisco\"}" }} ]} ], "non_preferred_output": [ {"role": "assistant", "content": "Sorry, I can't help you with that."} ] } ``` ### Reasoning data For [fine-tuning reasoning models](/docs/fine-tuning/reasoning), assistant messages support a `reasoning` or `reasoning_content` field that carries the chain of thought. ```json theme={null} { "messages": [ {"role": "user", "content": "What is the capital of France?"}, { "role": "assistant", "reasoning": "France is in Western Europe. Its capital is Paris.", "content": "The capital of France is Paris." } ] } ``` When fine-tuning reasoning models on conversational data, only the last assistant message is trained on by default. For multi-turn reasoning, split the conversation so each assistant message is the final message in its own example. > [!WARNING] > > Reasoning models should always be fine-tuned with reasoning data. Training without it can degrade the model's reasoning ability. If your dataset doesn't include reasoning, use an instruct model instead. For preference fine-tuning, both outputs carry `reasoning`: ```json theme={null} { "input": { "messages": [{"role": "user", "content": "What is the capital of France?"}] }, "preferred_output": [ {"role": "assistant", "reasoning": "France is in Western Europe. Its capital is Paris.", "content": "The capital of France is Paris."} ], "non_preferred_output": [ {"role": "assistant", "reasoning": "Let me think about European capitals.", "content": "The capital of France is Berlin."} ] } ``` ## Data weights Two independent controls adjust how much each part of your data contributes to the training loss. You can use either one on its own or both together in the same file. ### Per-message weights Set a `weight` on an individual message to control whether it contributes to the loss. Only `0` and `1` are supported: a message with `weight=0` is masked, and `weight=1` includes it. This is a finer-grained version of `train_on_inputs`, letting you mask or include specific messages rather than whole roles. Per-message weights are only available for [conversational data](#conversational-data), since they weight individual messages. ```json theme={null} { "messages": [ {"role": "user", "content": "Question A", "weight": 0}, {"role": "assistant", "content": "Answer A", "weight": 1} ] } ``` ### Sample weights Set a root-level `weight` on a line to scale that entire sample's contribution to the loss. It's a non-negative floating-point multiplier applied to the sample's tokens, and it works with every JSONL format and training method, including instruction data. ```json theme={null} {"prompt": "What is photosynthesis?", "completion": "Photosynthesis is...", "weight": 0.9} {"prompt": "What is mitosis?", "completion": "Mitosis is...", "weight": 0.1} ``` ### Combining weights You can set per-message weights and a sample weight in the same conversational file. The sample weight scales the loss for the whole line, and the per-message weights determine which messages within it contribute. ```json theme={null} { "messages": [ {"role": "user", "content": "Can you explain machine learning?", "weight": 0}, {"role": "assistant", "content": "Machine learning is...", "weight": 1} ], "weight": 0.9 } { "messages": [ {"role": "user", "content": "Can you explain why?", "weight": 0}, {"role": "assistant", "content": "I can't", "weight": 1} ], "weight": 0.1 } ``` ## Packing For JSONL training data, Together uses [sample packing](https://huggingface.co/docs/trl/main/en/reducing_memory_usage#packing): multiple short examples are concatenated up to `max_seq_length` so each training window uses the full context length instead of being padded out. Packing is enabled by default and makes the effective batch size larger than the `batch_size` you set, which significantly reduces the total number of training steps and overall training time. To control packing, either set the [`packing` flag](/reference/post-fine-tunes#body-packing) to `false` for JSONL input, or supply a pre-tokenized [Parquet file](#tokenized-parquet-data). The `packing` flag applies only to JSONL input. It has no effect on Parquet data. ## Tokenized (Parquet) data Use Parquet when you want to skip tokenization on every job, customize attention masks or labels, or run with a tokenizer that differs from the base model's. The file must be `.parquet` and under 100 GB. Allowed fields: | Field | Required | Description | | - | - | - | | `input_ids` | Yes | Token IDs fed to the model. | | `attention_mask` | Yes | 1 for tokens the model should attend to, 0 for padding. | | `labels` | No | Target token IDs. Use `-100` to mask a position from the loss. Defaults to `input_ids`. | | `position_ids` | No | Position IDs. Reset to 0 at each example boundary inside a packed sequence and increment by 1. Padding tokens also receive 0. | > [!NOTE] > > You don't need to shift `labels` relative to `input_ids`. The trainer shifts them internally for next-token prediction. Here's a worked example with the [together-py tokenize\_data.py script](https://github.com/togethercomputer/together-py/blob/main/examples/tokenize_data.py): ```bash theme={null} # With packing (recommended) python tokenize_data.py \ --tokenizer="NousResearch/Nous-Hermes-2-Mixtral-8x7B-SFT" \ --max-seq-length=32768 \ --add-labels \ --packing \ --out-filename="processed_packed.parquet" # Without packing python tokenize_data.py \ --tokenizer="NousResearch/Nous-Hermes-2-Mixtral-8x7B-SFT" \ --max-seq-length=32768 \ --add-labels \ --out-filename="processed_padded.parquet" ``` If `--packing` is passed, the script concatenates multiple short sequences into each `max_seq_length` window to reduce wasted compute, matching the [packing](#packing) training applies by default. Otherwise, each example is padded to its own window. Loading the resulting Parquet: ```python Python theme={null} from datasets import load_dataset packed = load_dataset( "parquet", data_files={"train": "processed_packed.parquet"} ) padded = load_dataset( "parquet", data_files={"train": "processed_padded.parquet"} ) print(packed["train"]) print(padded["train"]) ``` ## Validate and upload Run a local data validation check before uploading to avoid unnecessary charges. The client-side check verifies the file is UTF-8, each non-empty line parses as JSON, the line count exceeds the minimum, and the file is under the maximum size. Full schema validation (conversation roles, tool calls, and other dataset requirements) runs on the server during ingestion after upload, and is reported through the file's `processing_status`. ```bash CLI theme={null} tg files check "train.jsonl" --json tg files upload "train.jsonl" ``` ```python Python theme={null} import json from together import Together from together.lib.utils import check_file from together.lib.resources import FileUploadProgress client = Together() report = check_file("train.jsonl") print(json.dumps(report, indent=2)) assert report["is_check_passed"] def on_progress(event: FileUploadProgress) -> None: print(f"{event.uploaded_bytes}/{event.total_bytes}") train_file = client.files.upload( file="train.jsonl", purpose="fine-tune", check=True, progress_callback=on_progress, ) print(train_file.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const trainFile = await client.files.upload("train.jsonl", "fine-tune"); console.log(trainFile.id); ``` In the Python snippet, the optional `progress_callback` receives `FileUploadProgress` events (`uploaded_bytes`, `total_bytes`) as the upload runs. Omit it to upload silently. `check_file()` returns a report you can inspect before uploading. A passing file looks like: ```json theme={null} { "is_check_passed": true, "message": "Checks passed", "found": true, "file_size": 23777505, "utf8": true, "line_type": true, "text_field": true, "key_value": true, "has_min_samples": true, "num_samples": 7199, "load_json": true, "load_csv": null, "filetype": "jsonl" } ``` Successful upload returns a file object with an `id` field. Save the ID—you'll pass it as `training_file` to `client.fine_tuning.create()`. Before starting a job, preview how the file tokenizes with [`tg fine-tuning preview`](/reference/cli/finetune#preview). See the [quickstart](/docs/fine-tuning/quickstart) for the full fine-tuning lifecycle. > [!NOTE] > > If you upload a file whose contents already exist on Together AI, `client.files.upload()` doesn't create a duplicate. It returns the existing file's metadata, including its `id`, so you can reuse it directly. To force a re-upload, delete the existing file first with `client.files.delete()`. ### Wait for server-side validation Upload returns before ingestion finishes, so poll the Files API until `processing_status` reaches `COMPLETED` before you use the file. If the dataset doesn't meet fine-tuning requirements, `processing_status` becomes `INVALID_FORMAT` and `validation_report.error` carries a user-facing description of the problem. ```bash CLI theme={null} # Inspect processing_status and validation_report tg files retrieve ``` ```python Python theme={null} import time from together import Together client = Together() while True: meta = client.files.retrieve(train_file.id) if meta.processing_status == "COMPLETED": break if meta.processing_status == "INVALID_FORMAT": # validation_report.error carries a user-facing reason. raise ValueError( f"file is not valid for fine-tuning: {meta.validation_report}" ) if meta.processing_status == "FAILED": raise RuntimeError( f"file processing did not complete: {meta.processing_status}" ) time.sleep(5) ``` The exact `validation_report` schema may evolve, so treat `processing_status` as the authoritative readiness signal. ## Split into train and validation To carve a validation set out of a single JSONL file: ```bash theme={null} split_ratio=0.9 total=$(wc -l < train_full.jsonl) split_lines=$((total * split_ratio / 1)) head -n $split_lines train_full.jsonl > train.jsonl tail -n +$((split_lines + 1)) train_full.jsonl > validation.jsonl ``` Then pass both files to the job and set `n_evals` above 0: ```python Python theme={null} job = client.fine_tuning.create( training_file="", validation_file="", n_evals=10, model="Qwen/Qwen3-8B", ) ``` The model evaluates against the validation set at the specified intervals. Eval loss appears in the [training metrics](/docs/fine-tuning/monitoring) and (if `wandb_api_key` is set) on your W\&B dashboard. # Deploy a fine-tuned model Source: https://docs.together.ai/docs/fine-tuning/deployment Serve your fine-tuned model on a dedicated endpoint or download it for local inference. Once a fine-tuning job completes, your model is available for inference in two ways: hosted on a dedicated endpoint at Together AI, or downloaded as a standalone checkpoint. ## Requirements * A completed [fine-tuning job](/docs/fine-tuning/quickstart). * One of the job's two registry identifiers for the trained weights. Look for them in the `tg fine-tuning retrieve` output on a completed job: * `model_object_id` (an `ml_...` value): The model-registry ID. The CLI takes it directly, and the SDK and API take it inside a `projects/{project_id}/models/{model_id}` path. * `model_object_name` (a `/` value): The qualified registry name. The CLI accepts it in place of the ID. The SDK and API don't. * Together CLI version `3.0.0` or later. Check your version with `tg --version`. To install or upgrade, run `uv tool install "together[cli]" --upgrade`. ## Deploy on a dedicated endpoint Together AI serves fine-tuned models through [dedicated model inference](/docs/dedicated-endpoints/overview). A completed fine-tuning job is already a private model in your project, so you deploy it directly, with no upload step. > [!WARNING] > > Dedicated model inference bills per minute per running replica, even when idle. Scale the deployment to zero or delete the endpoint when you're done to stop billing. > [tab] CLI > > Deploy the fine-tune by its `model_object_name` or its `model_object_id`. The `deploy` command creates the endpoint, attaches a deployment, and routes all traffic to it in one step: > > ```bash CLI theme={null} > # Retrieve the job to copy its identifiers (model_object_name and model_object_id) > tg fine-tuning retrieve "" > > # Deploy the fine-tuned model to a new endpoint > # (pass instead to deploy by ID) > tg endpoints deploy "" \ > --endpoint my-finetuned-endpoint > ``` > > To deploy by name, pass it in full, including the project slug (`acme-corp/my-model-abc123`). The bare model name doesn't resolve, and neither does `model_output_name`. The CLI resolves a name only when exactly one model in your project matches it. > > If the model has more than one [deployment profile](/docs/dedicated-endpoints/configs), pass `--config ` to choose one. List a model's profiles with `tg models configs ""`. > > Poll until the deployment reaches `DEPLOYMENT_STATE_READY`: > > ```bash CLI theme={null} > tg endpoints get "" > ``` > > Once the deployment is `READY`, pass the **endpoint string** (`your-project-slug/my-finetuned-endpoint`, printed by the deploy output) as the `model` parameter and send the request to `https://api-inference.together.ai`: > > ```bash cURL theme={null} > curl -s https://api-inference.together.ai/v1/chat/completions \ > -H "Authorization: Bearer $TOGETHER_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "model": "your-project-slug/my-finetuned-endpoint", > "messages": [{"role": "user", "content": "Hello!"}] > }' > ``` > > To stop billing when you're done, delete the endpoint with `rm --force`, which also deletes its deployment: > > ```bash CLI theme={null} > tg endpoints rm "" --force > ``` > > If you plan to use the endpoint again, scale the deployment to zero instead. This stops billing without deleting anything. For the full teardown order, see [Delete resources](/docs/dedicated-endpoints/manage#delete-resources). > [tab] SDK > > The SDK has no single-call equivalent of the CLI's `deploy`, so you run the same steps yourself: create the endpoint, bind the model and a config to a deployment, then route traffic to it. Reference the fine-tune by its **Model Object ID** (`ml_...`, the job's `model_object_id`) inside a `projects/{project_id}/models/{model_id}` resource path. Only the CLI resolves `model_object_name`, so the SDK can't take it. > > ```python Python theme={null} > from together import Together > > client = Together() > identity = client.whoami() > if identity.type != "project_api_key": > raise RuntimeError("TOGETHER_API_KEY must be a project API key") > project_id = identity.project.id > > # Reference the fine-tune by its Model Object ID (ml_...) and a config > # for the base model. List configs: tg models configs . > model = f"projects/{project_id}/models/" > config = f"projects/{project_id}/configs/" > > # 1. Create the endpoint. > endpoint = client.endpoints.create( > project_id=project_id, > name="my-finetuned-endpoint", > ) > > # 2. Bind the model and config to a deployment. > deployment = client.endpoints.deployments.create( > endpoint.id, > project_id=project_id, > name="prod", > model=model, > config=config, > autoscaling={"min_replicas": 1, "max_replicas": 1}, > ) > > # 3. Route 100% of traffic to the deployment. > client.endpoints.update( > endpoint.id, > project_id=project_id, > traffic_split=[{"deployment_id": deployment.id, "weight": 1}], > ) > print(endpoint.name) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > const identity = await client.whoami(); > if (identity.type !== "project_api_key") { > throw new Error("TOGETHER_API_KEY must be a project API key"); > } > const projectId = identity.project.id; > > // Reference the fine-tune by its Model Object ID (ml_...) and a config > // for the base model. List configs: tg models configs . > const model = `projects/${projectId}/models/`; > const config = `projects/${projectId}/configs/`; > > // 1. Create the endpoint. > const endpoint = await client.endpoints.create({ > projectId, > name: "my-finetuned-endpoint", > }); > > // 2. Bind the model and config to a deployment. > const deployment = await client.endpoints.deployments.create( > endpoint.id, > { > projectId, > name: "prod", > model, > config, > autoscaling: { minReplicas: 1, maxReplicas: 1 }, > }, > ); > > // 3. Route 100% of traffic to the deployment. > await client.endpoints.update(endpoint.id, { > projectId, > trafficSplit: [{ deploymentId: deployment.id, weight: 1 }], > }); > console.log(endpoint.name); > ``` > > Poll the deployment's `status.state` until it reaches `DEPLOYMENT_STATE_READY`: > > ```python Python theme={null} > deployment = client.endpoints.deployments.retrieve( > deployment.id, > project_id=project_id, > endpoint_id=endpoint.id, > ) > print(deployment.status.state) > ``` > > ```typescript TypeScript theme={null} > const current = await client.endpoints.deployments.retrieve( > deployment.id, > { projectId, endpointId: endpoint.id }, > ); > console.log(current.status.state); > ``` > > Once the deployment is `READY`, pass the **endpoint string** (`your-project-slug/my-finetuned-endpoint`, returned as `endpoint.name`) as the `model` parameter and point the SDK's base URL at `https://api-inference.together.ai`: > > ```python Python theme={null} > from together import Together > > # A dedicated client for inference: this base URL serves only > # inference, not the fine-tuning or files APIs. > inference_client = Together(base_url="https://api-inference.together.ai") > > response = inference_client.chat.completions.create( > model="your-project-slug/my-finetuned-endpoint", > messages=[{"role": "user", "content": "Hello!"}], > ) > print(response.choices[0].message.content) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > // A dedicated client for inference: this base URL serves only > // inference, not the fine-tuning or files APIs. > const inferenceClient = new Together({ > baseURL: "https://api-inference.together.ai", > }); > > const response = await inferenceClient.chat.completions.create({ > model: "your-project-slug/my-finetuned-endpoint", > messages: [{ role: "user", content: "Hello!" }], > }); > console.log(response.choices[0].message.content); > ``` > > The SDK has no equivalent of the CLI's `rm --force` either. To stop billing when you're done, scale the deployment to zero, then delete the deployment and the endpoint once it reaches `DEPLOYMENT_STATE_STOPPED`: > > ```python Python theme={null} > # Scale to zero to stop billing. > client.endpoints.deployments.update( > deployment.id, > project_id=project_id, > endpoint_id=endpoint.id, > autoscaling={"min_replicas": 0, "max_replicas": 0}, > ) > > # Once it's DEPLOYMENT_STATE_STOPPED, drop its traffic weight, then > # delete the deployment and the endpoint. > client.endpoints.update( > endpoint.id, > project_id=project_id, > traffic_split=[{"deployment_id": deployment.id, "weight": 0}], > ) > client.endpoints.deployments.delete( > deployment.id, project_id=project_id, endpoint_id=endpoint.id > ) > client.endpoints.delete(endpoint.id, project_id=project_id) > ``` > > ```typescript TypeScript theme={null} > // Scale to zero to stop billing. > await client.endpoints.deployments.update(deployment.id, { > projectId, > endpointId: endpoint.id, > autoscaling: { minReplicas: 0, maxReplicas: 0 }, > }); > > // Once it's DEPLOYMENT_STATE_STOPPED, drop its traffic weight, then > // delete the deployment and the endpoint. > await client.endpoints.update(endpoint.id, { > projectId, > trafficSplit: [{ deploymentId: deployment.id, weight: 0 }], > }); > await client.endpoints.deployments.delete(deployment.id, { > projectId, > endpointId: endpoint.id, > }); > await client.endpoints.delete(endpoint.id, { projectId }); > ``` > > If you plan to use the endpoint again, scale the deployment to zero and skip the deletes. This stops billing without deleting anything. For the full teardown order, see [Delete resources](/docs/dedicated-endpoints/manage#delete-resources). > [tab] UI > > **1. Open your models** > > Go to [My models](https://api.together.ai/models?category=my-models). Your fine-tuned models appear here once training finishes. > > **2. Create the endpoint** > > Select your fine-tuned model, then select **Create dedicated endpoint**. > > **3. Configure the deployment** > > Choose a deployment configuration (hardware and GPU count) and set the replica bounds. > > **4. Deploy** > > Select **Deploy**. Provisioning takes up to 10 minutes. You can navigate away while it runs. > > **5. Stop when done** > > When you're not using the endpoint, open it from the dashboard and stop or delete it to halt per-minute billing. ## Run locally To run your model outside Together, download the checkpoint by job ID: ```bash CLI theme={null} tg fine-tuning download "" ``` ```python Python theme={null} from together import Together client = Together() response = client.fine_tuning.content(ft_id="", checkpoint="merged") response.write_to_file("my-model/model.tar.zst") ``` ```typescript TypeScript theme={null} import Together from "together-ai"; import fs from "node:fs"; const client = new Together(); const response = await client.fineTuning.content({ ft_id: "", checkpoint: "merged" }); const buffer = Buffer.from(await response.arrayBuffer()); fs.writeFileSync("my-model/model.tar.zst", buffer); ``` ### Choose a checkpoint type The `checkpoint` parameter selects what to download. If you omit it, the API picks a default automatically: `merged` for low-rank adapter (LoRA) jobs and `model_output_path` for full fine-tunes. You can also pass `checkpoint_step`, which downloads a specific intermediate step and overrides `checkpoint`. Valid values depend on how the job was trained. | Job type | Valid `checkpoint` values | What you get | | - | - | - | | LoRA fine-tune | `merged`, `adapter`, or `model_output_path` | `merged` combines the base model and adapter into self-contained weights, the usual choice for running the model locally or uploading it elsewhere. `adapter` returns only the LoRA adapter weights, so you can load them on top of the base model yourself (for example, with PEFT or vLLM). | | Full fine-tune | `model_output_path` only | The full set of trained model weights. `adapter` returns an error for full fine-tunes. | `model_output_path` returns the raw training output directory before any merging. It works for both job types but is mainly useful for advanced workflows that need the unmodified artifacts. For LoRA jobs, prefer `merged` or `adapter`. For full fine-tunes, it's the only option. The output is a `.tar.zst` archive that uses [ZStandard](https://github.com/facebook/zstd) compression. On macOS, install `zstd` with Homebrew and decompress: ```bash theme={null} brew install zstd cd my-model zstd -d model.tar.zst tar -xvf model.tar ``` You should see: ```text theme={null} tokenizer_config.json special_tokens_map.json pytorch_model.bin generation_config.json tokenizer.json config.json ``` Load the model with Hugging Face Transformers: ```python Python theme={null} from transformers import AutoTokenizer, AutoModelForCausalLM import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") tokenizer = AutoTokenizer.from_pretrained("./my-model") model = AutoModelForCausalLM.from_pretrained( "./my-model", trust_remote_code=True, ).to(device) input_ids = tokenizer.encode("Space robots are", return_tensors="pt").to( device ) output = model.generate(input_ids, max_length=128, temperature=0.7) print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` To download a specific checkpoint instead of the final one, pass `--checkpoint-step ` to `tg fine-tuning download` (or `checkpoint_step=` to `client.fine_tuning.content()`). List checkpoints with `tg fine-tuning list-checkpoints `. ## Model registry object IDs When a job uploads its output artifacts to the Together model registry alongside the primary storage write, the job and checkpoint responses include the registry object and revision IDs, plus qualified object names in `/` form. Use the IDs to reference the uploaded weights in downstream workflows, such as binding a fine-tuned adapter to a dedicated endpoint. The CLI's [`deploy`](#deploy-on-a-dedicated-endpoint) command also accepts the qualified name. On a completed job in the [fine-tuning jobs dashboard](https://api.together.ai/jobs), the **Output model** field shows `model_object_name` and links to that model in the registry by `model_object_id`. The object ID fields are omitted when the registry upload did not run or did not succeed. A name can still be present for a job whose upload never ran, but the CLI can't resolve it, so treat the matching `*_object_id` as the signal that the artifact reached the registry. Object names are resolved on the fly on [`GET /fine-tunes/{id}`](/reference/get-fine-tunes-id) and [`GET /fine-tunes/{id}/checkpoints`](/reference/get-fine-tunes-id-checkpoint) only (not on list jobs). If the project slug cannot be resolved, the name fields fall back to the corresponding object ID. ### On the job [`GET /fine-tunes/{id}`](/reference/get-fine-tunes-id) includes the final artifact IDs once the job reaches `completed`: | Field | Description | | - | - | | `model_object_id` | Registry object ID for the final model weights (for example, `ml_…`). Present when the job produced a model artifact and the upload succeeded. | | `model_object_revision_id` | Registry revision ID for the final model weights (for example, `rv_…`). | | `model_object_name` | Qualified registry name for the final model weights (for example, `acme-corp/my-model-abc123`). Pass it to `tg endpoints deploy` in place of `model_object_id`. The `` part comes from `model_output_name` (the segment after `/` when namespaced, or the whole string otherwise). | | `adapter_object_id` | Registry object ID for the final adapter weights on LoRA jobs. | | `adapter_object_revision_id` | Registry revision ID for the final adapter weights on LoRA jobs. | | `adapter_object_name` | Qualified adapter name on LoRA jobs (for example, `acme-corp/my-model-abc123-adapter`). | ```bash CLI theme={null} tg fine-tuning retrieve "" ``` ```python Python theme={null} job = client.fine_tuning.retrieve(id="") if job.api_model_object_id: print(job.api_model_object_id, job.api_model_object_revision_id) print(job.api_model_object_name) if job.adapter_object_id: print(job.adapter_object_id, job.adapter_object_revision_id) print(job.adapter_object_name) ``` ```typescript TypeScript theme={null} const job = await client.fineTuning.retrieve(""); if (job.model_object_id) { console.log(job.model_object_id, job.model_object_revision_id); console.log(job.model_object_name); } if (job.adapter_object_id) { console.log(job.adapter_object_id, job.adapter_object_revision_id); console.log(job.adapter_object_name); } ``` ### On checkpoints [`GET /fine-tunes/{id}/checkpoints`](/reference/get-fine-tunes-id-checkpoint) returns the same ID pair on each checkpoint entry: | Field | Description | | - | - | | `object_id` | Registry object ID for that checkpoint's artifact (for example, `ml_…`). | | `object_revision_id` | Registry revision ID for that checkpoint's artifact (for example, `rv_…`). | | `object_name` | Qualified registry name for that checkpoint (for example, `acme-corp/my-model-abc123-100` for an intermediate model checkpoint, or `acme-corp/my-model-abc123-adapter` for the final adapter). | Intermediate checkpoints carry the IDs from the upload at that step. Final model and adapter checkpoints in the list reuse the job-level IDs from the table above. ```bash CLI theme={null} tg fine-tuning list-checkpoints "" ``` ```python Python theme={null} checkpoints = client.fine_tuning.list_checkpoints("") for cp in checkpoints.data: if cp.object_id: print(cp.step, cp.object_id, cp.object_revision_id, cp.object_name) ``` ```typescript TypeScript theme={null} const checkpoints = await client.fineTuning.listCheckpoints(""); for (const cp of checkpoints.data) { if (cp.object_id) { console.log(cp.step, cp.object_id, cp.object_revision_id, cp.object_name); } } ``` ## Troubleshooting * **The job has no `model_object_id` yet:** The job hasn't reached `completed`. [Poll its status](/docs/fine-tuning/monitoring#poll-until-the-job-is-done) with `client.fine_tuning.retrieve(id=...)` until it's done. * **`You don't have permission to access this resource` from `tg endpoints create`, or `Unknown command "deploy"` from `tg endpoints deploy`:** Your Together CLI is older than `3.0.0`. CLI 2.x creates endpoints through the [retired v1 endpoints API](/docs/dedicated-endpoints/migrate-from-v1) and reports the resulting HTTP 403 as a permissions error. Your API key and model aren't the problem. [Upgrade the CLI](#requirements), then deploy with `tg endpoints deploy`. * **`endpoints_v1_create_access_disabled` (HTTP 403):** You're calling the [retired v1 endpoints API](/docs/dedicated-endpoints/migrate-from-v1), for example with `client.endpoints.create(...)` in SDK 2.x. Upgrade `together` to `3.0.0` or later, then rerun the SDK steps in [Deploy on a dedicated endpoint](#deploy-on-a-dedicated-endpoint). * **`Multiple configs found for model` when deploying:** The model has more than one deployment profile. List its profiles with `tg models configs ""`, then rerun with `--config `. * **`Model not found` when deploying by name:** Pass `model_object_name` in full, including the project slug, and check that the job reports a `model_object_id`. Without one, the weights never reached the registry, so neither identifier resolves. If the name still fails, deploy by `model_object_id`. * **`Multiple models found for ""`:** More than one model visible in your project has the same final name segment. Deploy by `model_object_id`, which is unambiguous. * **Either identifier fails with a key from another project:** The model belongs to the project the job ran in, and both identifiers resolve only within your key's project. Use a key scoped to the project that owns the model. * **Deploy fails because the base model isn't supported:** Not every base model can be hosted on dedicated model inference, and `-Reference` models often can't be deployed. Before you train, confirm that the base model appears in the [supported models](/docs/dedicated-endpoints/models) list. * **404 on inference:** Point the SDK's base URL at `https://api-inference.together.ai`, or at `https://api-inference.together.ai/v1` for OpenAI-compatible clients. Pass the endpoint string (`your-project-slug/`, printed in the deploy output) as the `model` parameter, not the `model_object_id`. ## Next steps > [card] [Upload a custom model](/docs/dedicated-endpoints/custom-models) > > Upload your own model weights from outside the Together catalog. > [card] [Manage endpoints](/docs/dedicated-endpoints/manage) > > Inspect, start, stop, update, and delete dedicated endpoints. > [card] [Configure autoscaling](/docs/dedicated-endpoints/scaling) > > Tune replica bounds and autoscale a deployment on the metric that fits your workload. # Early stopping Source: https://docs.together.ai/docs/fine-tuning/early-stopping Halt a fine-tuning job when validation loss stops improving. Early stopping halts a job when the validation loss stops improving and promotes the best available checkpoint as the final model. Use this feature when you're not sure how many epochs the run actually needs, and you want to avoid paying for steps that don't improve model performance. The job still finishes as `completed` with a deployable model, and the unused steps are refunded automatically. You can enable early stopping for both [supervised fine-tuning](/docs/fine-tuning/supervised) and [preference tuning with direct preference optimization (DPO)](/docs/fine-tuning/preference-tuning) jobs. Early stopping is driven by validation, so it requires a [validation file and one or more evaluations](/docs/fine-tuning/data-preparation#split-into-train-and-validation). ## Enable early stopping To turn on early stopping, supply a validation file, set `n_evals` high enough to detect a plateau, and set `early_stopping_enabled=true` in your job creation call: ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --validation-file "" \ --model "Qwen/Qwen3.5-9B" \ --n-epochs 5 \ --n-evals 10 \ --early-stopping-enabled \ --early-stopping-patience 2 \ --early-stopping-min-delta 0.0 \ --early-stopping-warmup-evals 1 ``` ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.create( training_file="", validation_file="", model="Qwen/Qwen3.5-9B", n_epochs=5, n_evals=10, early_stopping_enabled=True, early_stopping_patience=2, early_stopping_min_delta=0.0, early_stopping_warmup_evals=1, ) print(job.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.create({ training_file: "", validation_file: "", model: "Qwen/Qwen3.5-9B", n_epochs: 5, n_evals: 10, early_stopping_enabled: true, early_stopping_patience: 2, early_stopping_min_delta: 0.0, early_stopping_warmup_evals: 1, }); console.log(job.id); ``` ## Parameters | Parameter | Default | Description | | - | - | - | | `early_stopping_enabled` | `false` | Turn early stopping on. Requires `validation_file` and `n_evals >= patience + warmup_evals + 1`. | | `early_stopping_patience` | `2` | Number of consecutive non-improving evaluations to allow before stopping. | | `early_stopping_min_delta` | `0.0` | Minimum decrease in `eval_loss` that counts as an improvement. | | `early_stopping_warmup_evals` | `1` | Initial evaluations to skip before patience starts counting. Their `eval_loss` still updates the best value that later evaluations are compared against. | ## Retrieve the result When the job finishes, retrieve it and read the early stopping fields off the response: ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.retrieve(id="") print(job.early_stopped) # True if the run was halted early print(job.early_stopping_best_step) # step of the promoted checkpoint print(job.early_stopping_best_metric) # eval_loss at that step ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.retrieve(""); console.log(job.early_stopped); // true if the run was halted early console.log(job.early_stopping_best_step); // step of the promoted checkpoint console.log(job.early_stopping_best_metric); // eval_loss at that step ``` The response surfaces the early stopping decision and the best checkpoint: * `early_stopped`: `true` if patience was exhausted or a non-finite (NaN/Inf) eval loss halted the run, otherwise `false`. * `early_stopping_best_step`: The training step whose checkpoint was promoted as the final model, or the halt step when no improving evaluation was recorded. * `early_stopping_best_metric`: The value of `eval_loss` at that step (`null` if no improving evaluation was recorded). For example, a job that requested 5 epochs but stopped once the validation loss plateaued returns something like this (abbreviated to the relevant fields): ```json theme={null} { "id": "ft-9a8b7c6d-5e4f-3a2b-1c0d-9e8f7a6b5c4d", "status": "completed", "model": "Qwen/Qwen3.5-9B", "n_epochs": 5, "epochs_completed": 3, "n_evals": 10, "evals_completed": 6, "total_steps": 120, "steps_completed": 72, "early_stopped": true, "early_stopping_best_step": 48, "early_stopping_best_metric": 0.4213 } ``` Here the best evaluation landed at step 48. The next two evaluations didn't improve on it (because `early_stopping_patience` is 2), so the run halted at step 72 and the step-48 checkpoint was promoted as the final model. `steps_completed` (72) is below `total_steps` (120), and the unused steps are refunded. The [events log](/reference/get-fine-tunes-id-events) also records an `early_stopped` entry at the halt step and a `refund` entry for the unused steps, which are credited back to your project automatically. To see the full history of `eval_loss` across evaluations and understand why early stopping fired, [retrieve the job's metrics](/docs/fine-tuning/monitoring#retrieve-metrics). ## Find the final checkpoint An early-stopped job ships the final checkpoint from `early_stopping_best_step`, not the halt step. When you [list checkpoints](/reference/cli/finetune#list-checkpoints), the final entry's `step` field reports that promoted step, so it matches `early_stopping_best_step` on the job. A job that didn't stop early reports the last completed step instead. To confirm this, retrieve the job and compare its `early_stopping_best_step` against the final checkpoint's `step`: ```bash CLI theme={null} tg fine-tuning list-checkpoints ``` ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.retrieve("") checkpoints = client.fine_tuning.list_checkpoints("") final = next( c for c in checkpoints.data if "intermediate" not in c.checkpoint_type.lower() ) # For an early-stopped job, these two values match. print(final.step, job.early_stopping_best_step) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.retrieve(""); const checkpoints = await client.fineTuning.listCheckpoints(""); const final = checkpoints.data.find( (c) => !c.checkpoint_type.toLowerCase().includes("intermediate"), ); // For an early-stopped job, these two values match. console.log(final?.step, job.early_stopping_best_step); ``` # Function-calling fine-tuning Source: https://docs.together.ai/docs/fine-tuning/function-calling Train a model to invoke tools and structured functions reliably. Function-calling fine-tuning adapts a model to invoke tools in response to user queries. The result is a model that produces well-formed `tool_calls` with high reliability, useful for agents and any pipeline that depends on structured function invocation. This page covers the function-calling data shape, supported models, and launch parameters. ## Supported models The following models support function-calling fine-tuning. See [supported models](/docs/fine-tuning/supported-models) for context lengths and batch limits. > [accordion] Supported models > > | Organization | Model | API ID | > | - | - | - | > | Z.ai | GLM 5.3 | `zai-org/GLM-5.3` | > | Z.ai | GLM 5.2 | `zai-org/GLM-5.2` | > | Z.ai | GLM 5.1 | `zai-org/GLM-5.1` | > | Qwen | Qwen3.8 27B | `Qwen/Qwen3.8-27B` | > | Qwen | Qwen3.6 35B A3B | `Qwen/Qwen3.6-35B-A3B` | > | Qwen | Qwen3.5 9B | `Qwen/Qwen3.5-9B` | > | Qwen | Qwen3.5 4B | `Qwen/Qwen3.5-4B` | > | Qwen | Qwen3.6 27B | `Qwen/Qwen3.6-27B` | > | Qwen | Qwen3.5 397B A17B | `Qwen/Qwen3.5-397B-A17B` | > | Qwen | Qwen3.5 122B A10B | `Qwen/Qwen3.5-122B-A10B` | > | Qwen | Qwen3.5 35B A3B | `Qwen/Qwen3.5-35B-A3B` | > | Qwen | Qwen3.5 27B | `Qwen/Qwen3.5-27B` | > | Moonshot AI | Kimi K2.7 Code | `moonshotai/Kimi-K2.7-Code` | > | Moonshot AI | Kimi K2.6 | `moonshotai/Kimi-K2.6` | > | Google | Gemma 4 31B IT | `google/gemma-4-31B-it` | > | Google | Gemma 4 31B IT VLM | `google/gemma-4-31B-it-VLM` | > | Google | Gemma 4 26B A4B IT | `google/gemma-4-26B-A4B-it` | > | OpenAI | GPT-OSS 20B | `openai/gpt-oss-20b` | > | OpenAI | GPT-OSS 120B | `openai/gpt-oss-120b` | > | Meta | Llama 4 Scout 17B 16E Instruct | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | > | Meta | Llama 4 Scout 17B 16E Instruct VLM | `meta-llama/Llama-4-Scout-17B-16E-Instruct-VLM` | > | Meta | Llama 4 Maverick 17B 128E Instruct | `meta-llama/Llama-4-Maverick-17B-128E-Instruct` | > | Meta | Llama 4 Maverick 17B 128E Instruct VLM | `meta-llama/Llama-4-Maverick-17B-128E-Instruct-VLM` | > | Meta | Llama 3.3 70B Instruct Reference | `meta-llama/Llama-3.3-70B-Instruct-Reference` | > | Meta | Meta Llama 3.1 8B Instruct Reference | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | ## Prepare your data Prepare data in a JSONL file. Each line should carry: * `messages`: The conversation. Assistant messages can include `tool_calls` (a list of structured invocation objects) in place of `content`. Tool results come back via messages with the `tool` role. * `tools`: A list of available tools for the example. ### Conversational format ```json theme={null} { "messages": [ {"role": "system", "content": "You are a helpful travel planning assistant."}, {"role": "user", "content": "What is the current temperature in San Francisco?"}, { "role": "assistant", "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "getCurrentWeather", "arguments": "{\"location\": \"San Francisco, CA\"}" } } ] }, {"role": "tool", "content": "{\"location\": \"San Francisco\", \"temperature\": \"65\", \"unit\": \"fahrenheit\"}"} ], "tools": [ { "type": "function", "function": { "name": "getCurrentWeather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA."} }, "required": ["location"] } } } ] } ``` ### Preference format For preference fine-tuning, the `tools` array nests inside `input`. See [Preference tuning](/docs/fine-tuning/preference-tuning) for the broader DPO workflow. ```json theme={null} { "input": { "messages": [ {"role": "system", "content": "You are a helpful travel planning assistant."}, {"role": "user", "content": "What is the current temperature in San Francisco?"} ], "tools": [ {"type": "function", "function": { "name": "getCurrentWeather", "description": "Get the current weather in a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]} }} ] }, "preferred_output": [ {"role": "assistant", "tool_calls": [ {"id": "call_abc123", "type": "function", "function": { "name": "getCurrentWeather", "arguments": "{\"location\": \"San Francisco, CA\"}" }} ]} ], "non_preferred_output": [ {"role": "assistant", "content": "Sorry, I can't help you with that."} ] } ``` ## Validate and upload Upload your data using the Together Python/TypeScript SDK or the [Together CLI](/reference/cli/getting-started): ```bash CLI theme={null} tg files check "function_calling_dataset.jsonl" tg files upload "function_calling_dataset.jsonl" ``` ```python Python theme={null} from together import Together client = Together() train_file = client.files.upload( file="function_calling_dataset.jsonl", purpose="fine-tune", check=True, ) print(train_file.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const trainFile = await client.files.upload( "function_calling_dataset.jsonl", "fine-tune", ); console.log(trainFile.id); ``` ## Launch the job Low-rank adapter (LoRA) training is the default and recommended training mode. Pass `lora=False` for full fine-tuning. ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3-8B" \ --lora ``` ```python Python theme={null} job = client.fine_tuning.create( training_file=train_file.id, model="Qwen/Qwen3-8B", lora=True, ) print(job.id) ``` ```typescript TypeScript theme={null} const job = await client.fineTuning.create({ training_file: trainFile.id, model: "Qwen/Qwen3-8B", lora: true, }); console.log(job.id); ``` For details on all available parameters, see the [API reference](/reference/cli/finetune). ## Watch and deploy Function-calling jobs use the same lifecycle as text jobs: * [Poll the job](/docs/fine-tuning/monitoring#poll-until-the-job-is-done) with the SDK or CLI. Expect 10 to 30 minutes for a LoRA job on an 8B model with a few thousand examples. * Deploy the result on a [dedicated endpoint](/docs/fine-tuning/deployment) and call it with the same [function-calling request shape](/docs/inference/function-calling/overview) as the base model. # LoRA vs. full fine-tuning Source: https://docs.together.ai/docs/fine-tuning/lora-vs-full Choose between LoRA and full fine-tuning, then tune LoRA's rank and target modules. Together AI supports two fine-tuning implementations: * **Low-rank adapter (LoRA):** Trains a small set of adapter weights on top of the frozen base model. * **Full fine-tuning:** Updates every weight in the base model. LoRA is the default on Together AI, because it trains 0.1% to 1% of the parameters that full fine-tuning would, costs less, and produces a compact adapter rather than a full set of model weights. Both [supervised fine-tuning](/docs/fine-tuning/supervised) and [preference fine-tuning](/docs/fine-tuning/preference-tuning) support LoRA and full fine-tuning. > [!NOTE] > > **Serving a LoRA fine-tune:** Fine-tuned adapters are served on [dedicated endpoints](/docs/fine-tuning/deployment), not through the per-token serverless API. Serverless LoRA inference (including Serverless Multi-LoRA) has been discontinued. To serve several adapters on shared hardware, [attach them to one deployment of their base model](/docs/post-training/multi-lora-deployment). This works for adapters from post-training on supported base models. Deploy other adapters one per deployment. ## Choose a method Use LoRA when: * **You're starting a new fine-tune:** LoRA gets you a working model fastest and at the lowest cost. * **You want to ship multiple adapters from the same base:** Adapters are small and can be swapped on a single hosted base model. * **You're tuning style, format, or domain vocabulary:** These are the kinds of updates that LoRA handles best. Use full fine-tuning when: * **The base behavior needs a substantial change:** A model that doesn't know the task you're training for may need every weight updated, not only an adapter. * **LoRA results plateau below your target:** Try increasing `lora_r` and `lora_alpha` first, and if quality still falls short, switch to full fine-tuning. ## Set the method on your job The `lora` parameter defaults to `True`. Pass `lora=False` (or `--no-lora` on the CLI) to run a full fine-tune instead. Everything else about the job stays the same. ```bash CLI theme={null} # LoRA (default) tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3.5-27B" \ --lora # Full fine-tuning tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3.5-27B" \ --no-lora ``` ```python Python theme={null} from together import Together client = Together() # LoRA (default) — lora=True is optional job = client.fine_tuning.create( training_file="", model="Qwen/Qwen3.5-27B", lora=True, ) # Full fine-tuning job = client.fine_tuning.create( training_file="", model="Qwen/Qwen3.5-27B", lora=False, ) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); // LoRA (default) — lora: true is optional const loraJob = await client.fineTuning.create({ training_file: "", model: "Qwen/Qwen3.5-27B", lora: true, }); // Full fine-tuning const fullJob = await client.fineTuning.create({ training_file: "", model: "Qwen/Qwen3.5-27B", lora: false, }); ``` ## LoRA settings For the parameters that tune LoRA itself (`lora_r`, `lora_alpha`, `lora_dropout`, `lora_trainable_modules`), see the [fine-tuning API reference](/reference/post-fine-tunes). If you don't set `lora_r`, the job uses the model's default rank, and `lora_alpha` defaults to twice the rank. The default can be lower than the highest rank a model supports. Both values are listed in [Supported models](/docs/fine-tuning/supported-models). To check a specific model, run [`tg fine-tuning model-limits `](/reference/cli/finetune#model-limits). ## Default target modules When you don't set `lora_trainable_modules`, it defaults to `all-linear`, which applies LoRA to the modules listed for each model in the tables below. To customize, pass a comma-separated list of module names instead. Each module you list must appear in the model's allow-list. Whitespace around module names is ignored, but a non-empty value that parses to no modules (for example `","` or `" , "`) is rejected. > [accordion] Default target modules by model > > ### Text models > > | Model | Default target modules | > | - | - | > | `moonshotai/Kimi-K2.7-Code` | `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `mlp.gate_proj`, `mlp.up_proj`, `mlp.down_proj` | > | `moonshotai/Kimi-K2.6` | `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `mlp.gate_proj`, `mlp.up_proj`, `mlp.down_proj` | > | `zai-org/GLM-5.3` | `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `o_proj` | > | `zai-org/GLM-5.2` | `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `o_proj` | > | `zai-org/GLM-5.1` | `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `o_proj` | > | `openai/gpt-oss-20b` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `openai/gpt-oss-120b` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `deepseek-ai/DeepSeek-V4-Flash-0731` | `q_a_proj`, `q_b_proj`, `kv_proj`, `o_b_proj`, `shared_experts.gate_proj`, `shared_experts.up_proj`, `shared_experts.down_proj` | > | `deepseek-ai/DeepSeek-V4-Flash` | `q_a_proj`, `q_b_proj`, `kv_proj`, `o_b_proj`, `shared_experts.gate_proj`, `shared_experts.up_proj`, `shared_experts.down_proj` | > | `deepseek-ai/DeepSeek-V3.1` | `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `mlp.gate_proj`, `mlp.up_proj`, `mlp.down_proj` | > | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | `k_proj`, `o_proj`, `q_proj`, `v_proj`, `shared_expert.gate_proj`, `shared_expert.up_proj`, `shared_expert.down_proj`, `feed_forward.gate_proj`, `feed_forward.up_proj`, `feed_forward.down_proj` | > | `meta-llama/Llama-4-Maverick-17B-128E-Instruct` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `meta-llama/Llama-3.3-70B-Instruct-Reference` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `mistralai/Mixtral-8x7B-Instruct-v0.1` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `google/gemma-4-31B-it` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `google/gemma-4-26B-A4B-it` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `Qwen/Qwen3.5-35B-A3B` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `Qwen/Qwen3.5-122B-A10B` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `Qwen/Qwen3.5-397B-A17B` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `Qwen/Qwen3.6-35B-A3B` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > > ### Multimodal models > > | Model | Default target modules | > | - | - | > | `meta-llama/Llama-4-Scout-17B-16E-Instruct-VLM` | `k_proj`, `o_proj`, `q_proj`, `v_proj`, `shared_expert.gate_proj`, `shared_expert.up_proj`, `shared_expert.down_proj`, `feed_forward.gate_proj`, `feed_forward.up_proj`, `feed_forward.down_proj` | > | `meta-llama/Llama-4-Maverick-17B-128E-Instruct-VLM` | `k_proj`, `o_proj`, `q_proj`, `v_proj` | > | `Qwen/Qwen3.5-4B` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `Qwen/Qwen3.5-9B` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `Qwen/Qwen3.5-27B` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `Qwen/Qwen3.6-27B` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `Qwen/Qwen3.8-27B` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | > | `google/gemma-4-31B-it-VLM` | `k_proj`, `up_proj`, `o_proj`, `q_proj`, `down_proj`, `v_proj`, `gate_proj` | ## Target MoE expert layers On mixture-of-experts (MoE) models, you can apply LoRA to the expert feed-forward projections. Use expert LoRA when your task depends on the model's domain knowledge (the feed-forward experts) rather than its attention patterns, for example when you adapt an MoE base model to a new domain or task family. Expert LoRA is available only on some MoE models. Other models reject expert modules when you create the job. To see the modules a model accepts, run [`tg fine-tuning model-limits `](/reference/cli/finetune#model-limits). To target the experts, set `lora_trainable_modules` to the expert modules `w_up`, `w_gate`, and `w_down`: ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3.6-35B-A3B" \ --lora \ --lora-trainable-modules "w_up,w_gate,w_down" ``` ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.create( training_file="", model="Qwen/Qwen3.6-35B-A3B", lora=True, lora_trainable_modules="w_up,w_gate,w_down", ) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.create({ training_file: "", model: "Qwen/Qwen3.6-35B-A3B", lora: true, lora_trainable_modules: "w_up,w_gate,w_down", }); ``` To train the attention and expert projections in the same job, list both sets of modules, for example `k_proj,o_proj,q_proj,v_proj,w_up,w_gate,w_down`. ## What to expect from full fine-tuning * **Supported models:** Full fine-tuning is available for a [subset of the models](/docs/fine-tuning/supported-models) that support LoRA. Large mixture-of-experts models, long-context variants, and some vision-language models are LoRA-only. * **Smaller batch sizes:** Because full fine-tuning updates every weight, it carries a larger memory footprint, so the maximum batch size for a given model is generally smaller than the LoRA equivalent. * **Higher cost:** Full fine-tuning trains every parameter rather than the 0.1% to 1% a LoRA job touches, so it consumes more compute and costs more. See [pricing](/docs/fine-tuning/pricing) for details. To check a single model before submitting a job, read `supports_full_training` from the model limits endpoint. When it's `False`, the model is LoRA-only, and passing `lora=False` returns a validation error. ```python theme={null} from together import Together client = Together() limits = client.fine_tuning.model_limits(model_name="") print(limits.supports_full_training) ``` ## Continue training from a checkpoint Instead of starting from a base model, you can have a new job start from a previously completed job by passing `from_checkpoint` in one of the [accepted formats](/docs/fine-tuning/quickstart#continue-from-a-checkpoint). When the previous job is a LoRA job, the new job handles its adapter in one of two ways: * **Continue it:** The new job picks up the same adapter and keeps training it. The result is still a single adapter on the same base weights. * **Merge it:** Together folds the adapter into its base weights, producing a standalone set of weights, and the new job trains on those instead. The original adapter is no longer a separate, swappable artifact. In either case, the adapter stays tied to its *base weights* (the base model weights, or the output of an earlier full fine-tune). The result of the new job depends on the training type of both jobs: | Previous job | New job | What happens | | - | - | - | | Full | Full | Training continues on the full weights. No adapter is involved. | | Full | LoRA | A new adapter trains on top of the previous job's full weights. | | LoRA | Full | The adapter is merged into its base weights, then full fine-tuning trains the merged weights. | | LoRA | LoRA, same LoRA settings | Training continues on the same adapter. | | LoRA | LoRA, different LoRA settings | The adapter is merged into its base weights, then a new adapter with the new settings trains on top. | The [LoRA settings](#lora-settings) (`lora_r`, `lora_alpha`, `lora_dropout`, and `lora_trainable_modules`) define the adapter's shape, so an adapter can only continue training when all four match the previous job. To guarantee a continuation, omit the training type and the LoRA settings on the new job, so it inherits all of them from the previous job. Any value you set that differs from the previous job triggers a merge instead. Once a job has merged a parent adapter, its own adapter can't be continued either. The next job in the chain starts from that job's merged weights whatever its training type or LoRA settings, and a LoRA job trains a new adapter on them. Pass a checkpoint that includes the merged weights (a step that saved only an adapter is rejected at creation). The new job produces a checkpoint based on its own training type. A full fine-tune outputs full model weights (`--checkpoint-type default`). A LoRA job outputs an adapter plus merged weights (`--checkpoint-type adapter` or `merged` on [`tg fine-tuning download`](/reference/cli/finetune#download-model-weights)). The merged weights contain everything trained so far, including any parent adapter that was merged along the way. See [Choose a checkpoint type](/docs/fine-tuning/deployment#choose-a-checkpoint-type) for the SDK equivalents and what each artifact contains. In two cases the adapter can't be merged, so the platform rejects the new job at creation unless the LoRA settings match the previous job exactly: * **The previous job started from a Hugging Face model:** The rejection error names the settings that differ. * **The base model supports LoRA training only:** These models never produce full weights, so there is nothing to merge the adapter into. ## Serve your model How you deploy depends on the method: * **LoRA:** After the job completes, [deploy the merged model](/docs/fine-tuning/deployment) on a dedicated endpoint. * **Full fine-tuning:** The job produces a complete model rather than a compact adapter. [Deploy it on a dedicated endpoint](/docs/fine-tuning/deployment), or download the weights for local use. # Monitor a fine-tuning job Source: https://docs.together.ai/docs/fine-tuning/monitoring Poll job status, retrieve per-step loss and evaluation metrics, and stream training progress to Weights & Biases. The Together AI platform records metrics at every training and evaluation step. You can pull them during a job to watch loss curves live, or after the job completes to compare runs. ## View metrics in the dashboard Open a job on the [fine-tuning jobs dashboard](https://api.together.ai/fine-tuning) and use the **Metrics** tab to chart training progress. Metrics stream in while a job runs and stay available after it completes. Use the filter control (funnel icon) in the metrics toolbar to adjust how points are sampled: * **Sampling rate:** Cap how many training points are plotted (maps to the `resolution` query parameter, default 100). * **Step range:** Limit the chart to a contiguous step window (maps to `global_step_from` and `global_step_to`). The same **Metrics filtering** controls are available when you [compare fine-tuning runs](https://api.together.ai/fine-tuning?view=comparison) side by side, so you can align sampling and step windows across selected jobs. Select **Apply** to re-fetch, or **Restore defaults** to clear custom filters. ## Download the tokenized dataset When a job has produced a tokenized dataset archive, the job details on the [fine-tuning jobs dashboard](https://api.together.ai/fine-tuning) show a **Tokenized dataset** row with **Download**. Selecting **Download** opens a presigned archive URL in a new tab. When the archive upload finishes, the job events include a `tokenized_dataset_upload_complete` event. The event `message` appends the CLI download command, for example: ```text theme={null} Tokenized dataset archive uploaded. Run the following command to download the data: tg ft download-tokenized-dataset ft-xxxx ``` List events with `tg fine-tuning list-events ` or [`GET /fine-tunes/{id}/events`](/reference/get-fine-tunes-id-events). The same message appears on the console **Events** tab. `tg ft` is the shorthand for `tg fine-tuning`. The row appears only when the job response includes `tokenized_dataset_path`. If the archive is not available yet, use the API or CLI later, or wait for tokenization to finish. Download it with [`tg fine-tuning download-tokenized-dataset`](/reference/cli/finetune#download-tokenized-dataset) or [`GET /fine-tunes/{id}/download-tokenized-dataset`](/reference/get-fine-tunes-id-download-tokenized-dataset). ## Poll until the job is done A fine-tuning job moves through the states: `pending → queued → running → uploading → completed`. Queue wait is typically under an hour but varies with platform load. Once a job is running, multiply the duration of the first epoch by `n_epochs` to estimate remaining training time. Use this loop to poll until the job reaches a terminal state, then fetch the metrics. The terminal states are `completed`, `error`, and `cancelled`. If you launched the job with [early stopping](/docs/fine-tuning/early-stopping), the terminal status is still `completed` even when training ended ahead of `n_epochs`. The response sets `early_stopped=true` and exposes the winning checkpoint via `early_stopping_best_step` and `early_stopping_best_metric`. ```bash CLI theme={null} tg fine-tuning retrieve "" # When status is "completed", pull metrics: tg fine-tuning list-metrics "" --json > metrics.json ``` ```python Python theme={null} import os import time from together import Together client = Together() job_id = "ft-xxxx-yyyy" deadline = time.time() + 6 * 60 * 60 # safety cap: 6 hours while True: job = client.fine_tuning.retrieve(id=job_id) print(job.status) if job.status in ("completed", "error", "cancelled"): break if time.time() > deadline: raise TimeoutError(f"Job {job_id} still {job.status} after 6 hours") time.sleep(60) if job.status != "completed": raise RuntimeError(f"Job ended with status: {job.status}") metrics = client.fine_tuning.list_metrics(job_id) for step in metrics.metrics: print(step) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const jobId = "ft-xxxx-yyyy"; const deadline = Date.now() + 6 * 60 * 60 * 1000; const terminal = new Set(["completed", "error", "cancelled"]); let job = await client.fineTuning.retrieve(jobId); while (!terminal.has(job.status)) { if (Date.now() > deadline) { throw new Error(`Job ${jobId} still ${job.status} after 6 hours`); } await new Promise((r) => setTimeout(r, 60000)); job = await client.fineTuning.retrieve(jobId); console.log(job.status); } if (job.status !== "completed") { throw new Error(`Job ended with status: ${job.status}`); } const metrics = await client.fineTuning.listMetrics(jobId); console.log(metrics); ``` > [!NOTE] > > **Expected job durations:** A small low-rank adapter (LoRA) job on an 8B model with under 1,000 examples typically completes in 10 to 30 minutes after queue. A full job on a 70B model with hundreds of thousands of examples can take several hours. Save your job ID: you can poll from any session without re-uploading data. ## Cancel or delete a job Cancel a running job if you started it by mistake or no longer need it. You're billed only for the steps that completed before cancellation. ```bash CLI theme={null} tg fine-tuning cancel "" ``` ```python Python theme={null} client.fine_tuning.cancel(id="") ``` Delete a finished job to remove it along with the files it produced. ```bash CLI theme={null} tg fine-tuning delete "" ``` ```python Python theme={null} client.fine_tuning.delete(id="") ``` > [!WARNING] > > Deleting a job can't be undone. It destroys every file the job produced, including intermediate and final checkpoints. ## Retrieve metrics The `list_metrics` call returns every recorded step. The CLI renders ASCII charts by default. Pass `--json` to get raw output. ```bash CLI theme={null} # ASCII charts (default) tg fine-tuning list-metrics "" # Raw JSON metrics tg fine-tuning list-metrics "" --json # Save the ASCII charts to a file tg fine-tuning list-metrics "" > plots.txt # Save the JSON metrics to a file tg fine-tuning list-metrics "" --json > metrics.json ``` ```python Python theme={null} metrics = client.fine_tuning.list_metrics("") for step in metrics.metrics: print(step) ``` ```typescript TypeScript theme={null} const metrics = await client.fineTuning.listMetrics(""); for (const step of metrics.metrics) { console.log(step); } ``` ## Filter by step or time All filter parameters are optional. Omit them to retrieve every recorded step. ```bash CLI theme={null} tg fine-tuning list-metrics "" \ --global-step-from 100 \ --global-step-to 500 \ --logged-at-from 2026-01-01T00:00:00 \ --logged-at-to 2026-01-02T00:00:00 \ --json ``` ```python Python theme={null} from datetime import datetime metrics = client.fine_tuning.list_metrics( "", global_step_from=100, global_step_to=500, logged_at_from=datetime.fromisoformat("2026-01-01T00:00:00+00:00"), logged_at_to=datetime.fromisoformat("2026-01-02T00:00:00+00:00"), ) ``` ```typescript TypeScript theme={null} const metrics = await client.fineTuning.listMetrics("", { global_step_from: 100, global_step_to: 500, logged_at_from: "2026-01-01T00:00:00", logged_at_to: "2026-01-02T00:00:00", }); ``` ## Downsample with resolution For long runs, pass `resolution` to cap the response at a fixed number of uniformly sampled training steps. Eval metrics are always returned in full regardless of this setting. ```bash CLI theme={null} tg fine-tuning list-metrics "" --resolution 50 --json ``` ```python Python theme={null} metrics = client.fine_tuning.list_metrics("", resolution=50) ``` ```typescript TypeScript theme={null} const metrics = await client.fineTuning.listMetrics("", { resolution: 50, }); ``` ## Sample output Training and eval steps are returned as separate objects. Training steps contain `train/*` keys, eval steps contain `eval/*`. When both fire at the same step, both objects appear: ```json theme={null} [ { "timestamp": 1779196193564587000, "train/global_step": 1, "train/epoch": 0.1, "train/loss": 2.43, "train/grad_norm": 1.21, "train/learning_rate": 1e-5 }, { "timestamp": 1779196253564587000, "train/global_step": 2, "train/epoch": 0.2, "train/loss": 2.11, "train/grad_norm": 0.94, "train/learning_rate": 9e-6 }, { "timestamp": 1779196313564587000, "train/global_step": 3, "train/epoch": 0.3, "train/loss": 1.98, "train/grad_norm": 0.87, "train/learning_rate": 8e-6 }, { "timestamp": 1779196314564587000, "train/global_step": 3, "train/epoch": 0.3, "eval/loss": 2.05 } ] ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `global_step_from` | integer | Return only metrics with `global_step` ≥ this value. | | `global_step_to` | integer | Return only metrics with `global_step` ≤ this value. | | `logged_at_from` | string or datetime | Return only metrics logged at or after this ISO 8601 timestamp. | | `logged_at_to` | string or datetime | Return only metrics logged at or before this ISO 8601 timestamp. | | `resolution` | integer | Maximum number of uniformly sampled training metric points. Does not affect eval metrics. | ## Available metrics Every job reports `train/global_step`, `train/loss`, `train/grad_norm`, `train/learning_rate`, and `timestamp`. When you supply `validation_file` and set `n_evals > 0`, the response also includes `eval/loss` and other validation metrics. ### Preference-tuning jobs A direct preference optimization (DPO) job emits everything above and adds reward and divergence metrics to the same `list_metrics` payload. They show up as extra `train/*` keys during training and, when evaluation is enabled, matching `eval/*` keys: * **Reward and accuracy:** The reward assigned to the preferred and non-preferred responses, plus the share of examples where the preferred reward is higher. * **KL divergence:** How far the trained model's output distribution has drifted from the reference model. * **Per-side log probabilities:** Separate values for the preferred and non-preferred outputs, useful for debugging stalled runs. Retrieval, filtering, and downsampling work the same way regardless of method. For what these values mean and how to interpret them during a run, see [DPO metrics](/docs/fine-tuning/preference-tuning#dpo-metrics). ## Stream to Weights & Biases Pass `wandb_api_key` when [creating the job](/docs/fine-tuning/quickstart#step-2-launch-the-job) to mirror these metrics to your W\&B workspace in real time. # Overview Source: https://docs.together.ai/docs/fine-tuning/overview Adapt a base model to a task by training it on your data. > [!TIP] > > If you need to drive the training loop from your own code, or you want to train with reinforcement learning, use [post-training](/docs/post-training/overview). It runs SFT, DPO, and GRPO against GPUs you provision, billed per GPU-minute. Fine-tuning tailors a pretrained model to a smaller, targeted dataset so it performs better on a specific task or domain. Together AI handles the full lifecycle: data upload, training, hosting, and inference on a [dedicated endpoint](/docs/dedicated-endpoints/overview). Together AI currently supports two fine-tuning approaches: * **Low-rank adapter (LoRA):** Trains a small set of adapter weights on top of the frozen base model. This is the default training mode, as it's faster, cheaper, and the right choice for most use cases. * **Full fine-tuning:** Updates every weight in the base model. Uses more compute, but can outperform LoRA when the base behavior needs to shift substantially. See [LoRA vs. full fine-tuning](/docs/fine-tuning/lora-vs-full) to choose between them. This choice is separate from the training method you pick below. You can launch a fine-tuning job from the console, through the API/SDK, or with the CLI: ```bash theme={null} # upload your training data tg files upload train.jsonl # start a LoRA fine-tuning job tg fine-tuning create --training-file --model Qwen/Qwen3.8-27B --lora # check progress tg fine-tuning retrieve ``` The [fine-tuning quickstart](/docs/fine-tuning/quickstart) breaks down this flow and shows the SDK equivalents. ## Get started > [card] [Quickstart](/docs/fine-tuning/quickstart) > > Prepare your data, launch a LoRA job on Qwen3 8B, and evaluate the result. > [card] [Supported models](/docs/fine-tuning/supported-models) > > Browse every base model you can fine-tune, with context lengths and batch sizes. > [card] [Pricing](/docs/fine-tuning/pricing) > > See how Together AI bills for training tokens and dedicated hosting. > [card] [Bring your own model](/docs/fine-tuning/byom) > > Fine-tune a model from the Hugging Face Hub that isn't in the Together catalog. ## Prepare your data Your training dataset needs to be a JSONL or Parquet file, formatted to match your task. See the [data preparation guide](/docs/fine-tuning/data-preparation) for the schemas, validation rules, and example datasets. ```python Python theme={null} from together import Together client = Together() train_file = client.files.upload( file="train.jsonl", purpose="fine-tune", check=True, ) print(train_file.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const trainFile = await client.files.upload("train.jsonl", "fine-tune"); console.log(trainFile.id); ``` ```bash cURL theme={null} curl -X POST https://api.together.ai/v1/files/upload \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -F "purpose=fine-tune" \ -F "file_name=train.jsonl" \ -F "file=@train.jsonl" ``` ## Training methods > [card] [Supervised fine-tuning](/docs/fine-tuning/supervised) > > Train on demonstration data with one target completion per example. The default method. > [card] [Preference fine-tuning](/docs/fine-tuning/preference-tuning) > > Align a model with rankings over preferred and dispreferred responses using DPO. ## Advanced guides > [card] [Vision fine-tuning](/docs/fine-tuning/vision) > > Fine-tune vision-language models on samples with image and text data. > [card] [Function calling](/docs/fine-tuning/function-calling) > > Train a model to invoke tools and structured functions reliably. > [card] [Reasoning fine-tuning](/docs/fine-tuning/reasoning) > > Train a reasoning model with chain-of-thought data. > [card] [LoRA vs. full fine-tuning](/docs/fine-tuning/lora-vs-full) > > Choose how much of the model to update, and tune LoRA's rank and target modules. ## Monitor and deploy > [card] [Monitor a job](/docs/fine-tuning/monitoring) > > Poll job status, then retrieve per-step loss and evaluation metrics. > [card] [Deploy your model](/docs/fine-tuning/deployment) > > Serve your fine-tuned model on a dedicated endpoint or download it for local use. # Preference fine-tuning Source: https://docs.together.ai/docs/fine-tuning/preference-tuning Align a model with paired preferred and dispreferred responses using DPO. Preference fine-tuning trains a model on paired examples that show which responses you want it to generate and which it should avoid. Together AI implements this with [Direct Preference Optimization (DPO)](https://arxiv.org/abs/2305.18290). This is more effective than supervised fine-tuning when you have ranked outputs for the same prompt. ## When to use preference tuning Consider using preference tuning when: * **You have ranked pairs of responses for the same prompt:** Standard supervised fine-tuning (SFT) only learns from a single target completion per example. DPO learns from the gap between good and bad (preferred and dispreferred) responses. * **You're polishing a model that already works:** DPO is most effective as a refinement step. If your data is far from the base model's pretraining distribution, [run SFT first and continue with DPO](#combine-sft-and-dpo) from that checkpoint. * **You want to reduce specific failure modes:** Pair the failure as `non_preferred_output` against the desired behavior. Skip DPO if your dataset is single-target. Use [supervised fine-tuning](/docs/fine-tuning/supervised) instead. ## Prepare your data Each line in the JSONL file carries: * `input.messages`: the context, in [conversational format](/docs/fine-tuning/data-preparation#conversational-data). * `preferred_output`: a list containing exactly one assistant message representing the ideal response. * `non_preferred_output`: a list containing exactly one assistant message representing the suboptimal response. ```json theme={null} { "input": { "messages": [ {"role": "assistant", "content": "Hello, how can I assist you today?"}, {"role": "user", "content": "Can you tell me about the rise of the Roman Empire?"} ] }, "preferred_output": [ {"role": "assistant", "content": "The Roman Empire rose from a small city-state founded in 753 BCE. Through military conquests and strategic alliances, Rome expanded across the Italian peninsula. After the Punic Wars, it grew even stronger, and in 27 BCE, Augustus became the first emperor, marking the start of the Roman Empire."} ], "non_preferred_output": [ {"role": "assistant", "content": "The Roman Empire rose due to military strength and strategic alliances."} ] } ``` > [!WARNING] > > Each output must contain exactly one assistant message. Preference tuning does not support pre-tokenized Parquet datasets. [Contact us](https://portal.usepylon.com/together-ai/forms/support-request) if you need this feature. For tool-calling preference data, see [data preparation](/docs/fine-tuning/data-preparation#tool-calling-data). For reasoning preference data, see [reasoning preference format](/docs/fine-tuning/data-preparation#reasoning-data). ## Launch a DPO job Set `training_method` to `"dpo"`. The full list of DPO parameters lives in the [API reference](/reference/post-fine-tunes). ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "meta-llama/Llama-3.2-3B-Instruct" \ --lora \ --training-method "dpo" \ --dpo-beta 0.2 ``` ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.create( training_file="", model="meta-llama/Llama-3.2-3B-Instruct", lora=True, training_method="dpo", dpo_beta=0.2, ) print(job.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.create({ training_file: "", model: "meta-llama/Llama-3.2-3B-Instruct", lora: true, training_method: "dpo", dpo_beta: 0.2, }); console.log(job.id); ``` ## DPO parameters | Parameter | Type | Default | Description | | - | - | - | - | | `dpo_beta` | float | `0.1` | How far the model is allowed to drift from the reference model. Lower values (around `0.1`) update more aggressively toward the preferred output. Higher values (around `0.7`) stay closer to the reference. Useful range is `0.05` to `0.9`. | | `dpo_normalize_logratios_by_length` | bool | `false` | Normalize log ratios by sample length during loss calculation. | | `dpo_reference_free` | bool | `false` | Train without a reference model. When enabled, the loss skips the reference model's log probabilities instead of penalizing drift from it. | | `rpo_alpha` | float | `0.0` | Incorporate the NLL loss on selected samples with this weight. | | `simpo_gamma` | float | `0.0` | Add a margin to the loss, force-enable length normalization, and exclude reference logits. Matches the [SimPO](https://arxiv.org/pdf/2405.14734) loss. | > [!NOTE] > > For [low-rank adapter (LoRA) long-context fine-tuning](/docs/fine-tuning/supported-models), half the context length is used for the preferred response and half for the non-preferred response. On a 32K model, effective context per side is 16K. Preference tuning ignores the `train_on_inputs` flag because the loss is computed from the preferred and non-preferred outputs. To stop a DPO run automatically when validation loss plateaus, see [early stopping](/docs/fine-tuning/early-stopping). ## DPO metrics Beyond standard training metrics, DPO jobs report: * **Accuracy:** The share of examples where the reward for the preferred response exceeds the reward for the non-preferred response. * **KL divergence:** How much the trained model's output distribution has diverged from the reference model's. Higher values mean the trained model has moved further from the reference. * **Per-side log probabilities:** For both preferred and non-preferred outputs, useful for debugging stalled runs. You can [retrieve these values](/docs/fine-tuning/monitoring#preference-tuning-jobs) during or after a run. ## Combine SFT and DPO The recommended workflow when your training data differs substantially from the base model's pretraining distribution: 1. Run a [supervised fine-tune](/docs/fine-tuning/supervised) on the concatenation of context and preferred output, using one of the supported [SFT data formats](/docs/fine-tuning/data-preparation). 2. Continue training the resulting checkpoint with DPO. Pass the previous job's checkpoint to `from_checkpoint`: ```python Python theme={null} job = client.fine_tuning.create( training_file="", from_checkpoint="", training_method="dpo", dpo_beta=0.2, ) ``` SFT first followed by DPO usually produces a noticeably better model than DPO alone for out-of-domain tasks. # Pricing Source: https://docs.together.ai/docs/fine-tuning/pricing Fine-tuning is billed per token processed at per-model rates for each training method and type. Together AI bills fine-tuning by the total number of tokens processed across training and validation. Each model has its own per-token rates, which depend on the training method (supervised or DPO) and on whether you train a low-rank adapter (LoRA) or run full fine-tuning. For current rates, see [together.ai/pricing](https://www.together.ai/pricing#fine-tuning). After training, hosting on a [dedicated endpoint](/docs/fine-tuning/deployment) is billed separately by the minute. ## How tokens are counted The total tokens processed in a job is equal to: ```text theme={null} total_tokens = (n_epochs × tokens_per_training_dataset) + (n_evals × tokens_per_validation_dataset) ``` Tokenization occurs shortly after the job starts. Your final token count and price are calculated and recorded after tokenization completes, after which they appear on the [fine-tuning jobs dashboard](https://api.together.ai/jobs) and in `client.fine_tuning.retrieve(id=)`. If you disable [packing](/reference/post-fine-tunes#body-packing), training tokens are computed as `dataset_length` × [`max_seq_length`](/reference/post-fine-tunes#body-max-seq-length) instead. ## Estimate job cost There are three ways to estimate the cost of a fine-tuning job before launching it: 1. **CLI:** When you submit a job with [`tg fine-tuning create`](/reference/cli/finetune#create), the CLI prints the estimated price and asks for confirmation before the job is submitted. 2. **Together AI console:** On the [new fine-tuning job page](https://api.together.ai/fine-tuning/new), the estimate appears once you select a model and dataset. 3. **API/SDK:** Call the [estimate price endpoint](/reference/post-fine-tunes-estimate-price) with the same parameters you plan to submit to the create job endpoint. The response includes the estimated total price, the estimated training and evaluation token counts, your credit limit, and whether you are allowed to proceed: ```python Python theme={null} import os from together import Together client = Together(api_key=os.environ.get("TOGETHER_API_KEY")) estimate = client.fine_tuning.estimate_price( training_file="file-abc123", model="meta-llama/Meta-Llama-3.1-8B-Instruct-Reference", n_epochs=3, training_method={"method": "sft"}, training_type={"type": "Lora", "lora_r": 8}, ) print(estimate) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together({ apiKey: process.env.TOGETHER_API_KEY }); const estimate = await client.fineTuning.estimatePrice({ training_file: "file-abc123", model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Reference", n_epochs: 3, training_method: { method: "sft" }, training_type: { type: "Lora", lora_r: 8 }, }); console.log(estimate); ``` > [!NOTE] > > The cost estimate is only available after your input datasets pass [server-side validation](/docs/fine-tuning/data-preparation#wait-for-server-side-validation). ## Cancelled and early-stopped jobs When a running job is cancelled or [stopped early](/docs/fine-tuning/early-stopping), you pay for completed steps only. To check how many steps a job completed, retrieve it and read `steps_completed`: ```bash theme={null} tg fine-tuning retrieve --json | jq '.steps_completed' ``` ## Failed jobs If a job fails, for example due to an invalid input or an internal Together AI-side error, all charges are fully refunded, including any completed steps. ## Minimum spend Fine-tuning jobs have a \$4.00 minimum charge. Some models are exempt. See [fine-tuning pricing](https://www.together.ai/pricing#fine-tuning) for the current rates and exceptions. ## Hosting charges After training, your fine-tuned model can be served on a dedicated endpoint that bills per minute based on the hardware attached. These charges are separate from your fine-tuning job cost and continue until you [stop or delete the endpoint](/docs/fine-tuning/deployment). # Fine-tuning quickstart Source: https://docs.together.ai/docs/fine-tuning/quickstart Prepare a conversational dataset, launch a LoRA job on Qwen3.5 9B, and evaluate the fine-tuned model. > [!TIP] > > Using a coding agent? Install the [together-ai](https://github.com/togethercomputer/skills/tree/main/skills/together-ai) skill so your agent writes correct fine-tuning code automatically. See [Coding agent setup](/docs/agent-skills) for the install flow. Fine-tuning trains a pretrained model on your own examples so it performs better on a specific task or domain. Use it when prompting alone doesn't reliably get you the output format, tone, or domain knowledge you need. In this quickstart, you'll prepare a conversational dataset (CoQA), upload it, launch a low-rank adapter (LoRA) job on Qwen3.5 9B, watch it complete, deploy the result, and compare it to the base model. End-to-end runtime is roughly 20 to 40 minutes for the example dataset. To choose between LoRA and full fine-tuning, or between training methods, see the [overview](/docs/fine-tuning/overview). You can find a runnable notebook for this tutorial [on GitHub](https://github.com/togethercomputer/together-cookbook/blob/main/fine-tuning/Finetuning_Guide.ipynb). ## Requirements Before you begin, make sure you have: * [A Together AI account and API key](https://api.together.ai/settings/projects/~first/api-keys). * [The Together CLI](/reference/cli/getting-started) or the [Python / TypeScript SDK](/docs/quickstart) installed. * Python installed, with [`datasets`](https://huggingface.co/docs/datasets), [`transformers`](https://huggingface.co/docs/transformers), and [`tqdm`](https://tqdm.github.io/) if you want to follow the data-prep step verbatim: ```bash theme={null} uv tool install "together[cli]" --upgrade uv init --no-workspace # optional uv add together datasets transformers tqdm ``` If you use the CLI, log in with your browser: ```bash theme={null} tg login ``` Export your API key for the SDK and cURL examples. You need it even if you use the CLI, because [Step 4](#step-4-deploy-and-call-your-model) calls your model with the SDK or cURL: ```bash theme={null} export TOGETHER_API_KEY= ``` ## Step 1: Prepare your dataset This quickstart uses the CoQA conversational dataset. Together AI supports four text data formats: [conversational](/docs/fine-tuning/data-preparation#conversational-data), [instruction](/docs/fine-tuning/data-preparation#instruction-data), [preference](/docs/fine-tuning/data-preparation#preference-data), and [generic text](/docs/fine-tuning/data-preparation#generic-text-data). JSONL is the default file format, but you can use Parquet for pre-tokenized data and custom loss masking. Transform CoQA into the conversational shape: ```python Python theme={null} from datasets import load_dataset coqa = load_dataset("stanfordnlp/coqa") system_prompt = ( "Read the story and extract answers for the questions.\nStory: {}" ) def map_fields(row): messages = [ {"role": "system", "content": system_prompt.format(row["story"])} ] for q, a in zip(row["questions"], row["answers"]["input_text"]): messages.append({"role": "user", "content": q}) messages.append({"role": "assistant", "content": a}) return {"messages": messages} train = coqa["train"].map( map_fields, remove_columns=coqa["train"].column_names ) train.to_json("coqa_train.jsonl") ``` > [!TIP] > > To train the model on only part of each example (for instance, the assistant turns but not the user turns), you can use [loss masking](/reference/post-fine-tunes#body-train-on-inputs) or [data weights](/docs/fine-tuning/data-preparation#data-weights). Next we'll upload the file. `files.upload()` runs a local structural check by default (`check=True`), catching basic formatting errors such as non-UTF-8 encoding or malformed JSON lines before the file is sent. To [inspect the check report](/docs/fine-tuning/data-preparation#validate-and-upload) yourself before uploading, run `check_file()` first: ```bash CLI theme={null} tg files upload "coqa_train.jsonl" ``` ```python Python theme={null} from together import Together client = Together() train_file = client.files.upload( file="coqa_train.jsonl", purpose="fine-tune", check=True, ) print(train_file.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const trainFile = await client.files.upload("coqa_train.jsonl", "fine-tune"); console.log(trainFile.id); ``` > [!TIP] > > For very large files, you can skip the local check with `check=False` to speed up the upload. After upload, the server validates the full schema (conversation roles, tool calls, and other dataset requirements) during ingestion, reported through the file's `processing_status`. To see files you've already uploaded, list them with `client.files.list()` (`tg files list`). > [!NOTE] > > If you upload a file whose contents already exist on Together AI, `client.files.upload()` doesn't create a duplicate. It returns the existing file's metadata, including its `id`, so you can reuse it directly. To force a re-upload, delete the existing file first with `client.files.delete()`. Upload returns before ingestion finishes, so poll the Files API until `processing_status` reaches `COMPLETED` before launching the job. If validation rejects the dataset, `processing_status` becomes `INVALID_FORMAT` and `validation_report.error` carries the reason. ```python Python theme={null} import time while True: meta = client.files.retrieve(train_file.id) if meta.processing_status == "COMPLETED": break if meta.processing_status == "INVALID_FORMAT": raise ValueError( f"file is not valid for fine-tuning: {meta.validation_report}" ) if meta.processing_status == "FAILED": raise RuntimeError( f"file processing did not complete: {meta.processing_status}" ) time.sleep(5) ``` Once processing finishes, the file metadata reflects the outcome. A successful validation (`processing_status: COMPLETED`): ```json theme={null} { "processing_status": "COMPLETED", "validation_report": { "valid": true, "dataset_format": "conversation", "nlines": 7199 } } ``` A user-correctable failure (`processing_status: INVALID_FORMAT`): ```json theme={null} { "processing_status": "INVALID_FORMAT", "validation_report": { "valid": false, "error_type": "INVALID_FORMAT", "error": "Line 7: `messages[1]` must contain a `role` field" } } ``` Save the `id` from the upload response. You'll pass it as `training_file` in the next step. ## Step 2: Launch the job `client.fine_tuning.create()` starts a LoRA job by default. The example below tunes Qwen3.5 9B for three epochs. See the [API reference](/reference/cli/finetune) for the full list of parameters. ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3.5-9B" \ --train-on-inputs auto \ --lora \ --n-epochs 3 \ --n-checkpoints 1 \ --warmup-ratio 0 \ --learning-rate 1e-5 \ --suffix "qwen35_9b_demo" ``` ```python Python theme={null} job = client.fine_tuning.create( training_file=train_file.id, model="Qwen/Qwen3.5-9B", n_epochs=3, n_checkpoints=1, learning_rate=1e-5, warmup_ratio=0, train_on_inputs="auto", lora=True, suffix="qwen35_9b_demo", # wandb_api_key=os.environ.get("WANDB_API_KEY"), # optional ) print(job.id) ``` ```typescript TypeScript theme={null} const job = await client.fineTuning.create({ training_file: trainFile.id, model: "Qwen/Qwen3.5-9B", n_epochs: 3, n_checkpoints: 1, learning_rate: 1e-5, warmup_ratio: 0, train_on_inputs: "auto", lora: true, suffix: "qwen35_9b_demo", }); console.log(job.id); ``` Response: ```text theme={null} ft-d1522ffb-8f3e-4106-9774-aed81e0164a4 ``` Save the job ID. > [accordion] Job parameters > > Here are some common job parameters: > > | Parameter | Required | Default | Notes | > | - | - | - | - | > | `training_file` | Required | n/a | File ID from Step 1. | > | `model` | Required | n/a | Base model to fine-tune. | > | `lora` | Optional | `true` | Set `false` for full fine-tuning. | > | `n_epochs` | Optional | `1` | Passes through the training set. | > | `learning_rate` | Optional | `0.00001` | Step size. | > | `batch_size` | Optional | `"max"` | Examples per optimization step. With [packing](/docs/fine-tuning/data-preparation#packing) enabled (the default for JSONL), a step can cover several short examples, so this isn't the same as JSONL lines per step. | > | `warmup_ratio` | Optional | `0.0` | Fraction of steps for LR warmup. | > | `weight_decay` | Optional | `0.0` | L2 regularization. | > | `max_grad_norm` | Optional | `1.0` | Gradient-clipping threshold. Set to `0` to disable clipping. | > | `train_on_inputs` | Optional | `"auto"` | Mask user or prompt tokens from the loss. | > | `suffix` | Optional | n/a | Up to 64 characters appended to the output model name. | > | `n_checkpoints` | Optional | `1` | Intermediate checkpoints saved during training. | > | `n_evals` | Optional | `0` | Evaluations against `validation_file` during training. | > | `hf_api_token` | Optional | n/a | Only required for a private Hugging Face base. Omit otherwise. | > > See the [API reference](/reference/post-fine-tunes) for the full list of parameters. > [!WARNING] > > Each `fine_tuning.create()` call starts a new billed job. If you get a retryable error, run `client.fine_tuning.list()` first to make sure you aren't launching a duplicate. ## Step 3: Watch the job complete Jobs move through these states: `pending → queued → running → uploading → completed`. Queue wait time is typically under an hour. Once running, multiply the first epoch's duration by `n_epochs` to estimate the time remaining. Poll for completion (or error/cancellation), then read the job's registry identifiers: ```bash CLI theme={null} tg fine-tuning retrieve "" # Sample events tg fine-tuning list-events "" ``` ```python Python theme={null} import time job_id = job.id deadline = time.time() + 6 * 60 * 60 # safety cap: 6 hours while True: status = client.fine_tuning.retrieve(id=job_id) print(status.status) if status.status in ("completed", "error", "cancelled"): break if time.time() > deadline: raise TimeoutError(f"Job still {status.status} after 6 hours") time.sleep(60) if status.status != "completed": raise RuntimeError(f"Job ended with status: {status.status}") # Registry identifiers for the trained weights. The CLI's deploy takes # either. The SDK takes the ID. model_output_name isn't deployable. model_object_id = status.api_model_object_id print(model_object_id, status.api_model_object_name) ``` ```typescript TypeScript theme={null} const deadline = Date.now() + 6 * 60 * 60 * 1000; const terminal = new Set(["completed", "error", "cancelled"]); let status = await client.fineTuning.retrieve(job.id); while (!terminal.has(status.status)) { if (Date.now() > deadline) { throw new Error(`Job still ${status.status} after 6 hours`); } await new Promise((r) => setTimeout(r, 60000)); status = await client.fineTuning.retrieve(job.id); console.log(status.status); } if (status.status !== "completed") { throw new Error(`Job ended with status: ${status.status}`); } // Registry identifiers for the trained weights. The CLI's deploy takes // either. The SDK takes the ID. model_output_name isn't deployable. const modelObjectId = status.model_object_id; console.log(modelObjectId, status.model_object_name); ``` Here's a sample event log: ```text theme={null} Fine tune request created Job started at 2026-04-03T03:19:46Z Model data downloaded at 2026-04-03T03:19:48Z WandB run initialized. Training started for Qwen/Qwen3.5-9B Epoch completed, at step 24 Epoch completed, at step 48 Epoch completed, at step 72 Training completed for Qwen/Qwen3.5-9B at 2026-04-03T03:27:55Z Uploading output model Model upload complete Job finished at 2026-04-03T03:31:33Z ``` You can also monitor the run on the [fine-tuning jobs dashboard](https://api.together.ai/jobs). For per-step loss curves, see [training metrics](/docs/fine-tuning/monitoring). ## Step 4: Deploy and call your model Fine-tuned models run on Together AI through [dedicated model inference](/docs/fine-tuning/deployment). A completed job is already a private model in your project, so there's no upload step. Deploy it with `tg endpoints deploy` by either identifier from Step 3 (`model_object_name` or `model_object_id`). The deploy commands require Together CLI version `3.0.0` or later. The CLI's `deploy` command creates the endpoint, attaches a deployment, and routes all traffic to it in one step. Then poll until the deployment reaches `DEPLOYMENT_STATE_READY`: ```bash CLI theme={null} # Deploy the fine-tuned model to a new endpoint # (pass instead to deploy by ID) tg endpoints deploy "" \ --endpoint qwen-finetune # Poll until the deployment reaches DEPLOYMENT_STATE_READY # (pass the endpoint ID from the deploy output) tg endpoints get "" ``` The SDK has no single-call equivalent, so it runs the same steps individually, referencing the fine-tune by its Model Object ID (`ml_...`). The SDK and API don't accept the name: ```python Python theme={null} from together import Together client = Together() identity = client.whoami() if identity.type != "project_api_key": raise RuntimeError("TOGETHER_API_KEY must be a project API key") project_id = identity.project.id # Reference the fine-tune by its Model Object ID (ml_...) and a config # for the base model. List configs: tg models configs . model = f"projects/{project_id}/models/" config = f"projects/{project_id}/configs/" endpoint = client.endpoints.create( project_id=project_id, name="qwen-finetune", ) deployment = client.endpoints.deployments.create( endpoint.id, project_id=project_id, name="prod", model=model, config=config, autoscaling={"min_replicas": 1, "max_replicas": 1}, ) client.endpoints.update( endpoint.id, project_id=project_id, traffic_split=[{"deployment_id": deployment.id, "weight": 1}], ) # Poll until ready deployment = client.endpoints.deployments.retrieve( deployment.id, project_id=project_id, endpoint_id=endpoint.id ) print(endpoint.name, deployment.status.state) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const identity = await client.whoami(); if (identity.type !== "project_api_key") { throw new Error("TOGETHER_API_KEY must be a project API key"); } const projectId = identity.project.id; // Reference the fine-tune by its Model Object ID (ml_...) and a config // for the base model. List configs: tg models configs . const model = `projects/${projectId}/models/`; const config = `projects/${projectId}/configs/`; const endpoint = await client.endpoints.create({ projectId, name: "qwen-finetune", }); const deployment = await client.endpoints.deployments.create( endpoint.id, { projectId, name: "prod", model, config, autoscaling: { minReplicas: 1, maxReplicas: 1 }, }, ); await client.endpoints.update(endpoint.id, { projectId, trafficSplit: [{ deploymentId: deployment.id, weight: 1 }], }); console.log(endpoint.name); ``` Once the deployment is ready, send a request. The deploy output prints the **endpoint string** (`your-project-slug/qwen-finetune`): pass this as the `model` parameter. Point the SDK's base URL at `https://api-inference.together.ai`: ```python Python theme={null} from together import Together # A dedicated client for inference: this base URL serves only # inference, not the fine-tuning or files APIs. inference_client = Together(base_url="https://api-inference.together.ai") response = inference_client.chat.completions.create( model="your-project-slug/qwen-finetune", messages=[{"role": "user", "content": "What is the capital of France?"}], max_tokens=128, ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; // A dedicated client for inference: this base URL serves only // inference, not the fine-tuning or files APIs. const inferenceClient = new Together({ baseURL: "https://api-inference.together.ai", }); const response = await inferenceClient.chat.completions.create({ model: "your-project-slug/qwen-finetune", messages: [{ role: "user", content: "What is the capital of France?" }], max_tokens: 128, }); console.log(response.choices[0].message.content); ``` ```bash cURL theme={null} curl -s https://api-inference.together.ai/v1/chat/completions \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-project-slug/qwen-finetune", "messages": [{"role": "user", "content": "What is the capital of France?"}], "max_tokens": 128 }' ``` When you're done, delete the endpoint and its deployment to stop billing: ```bash CLI theme={null} tg endpoints rm "" --force ``` > [!NOTE] > > Pass the endpoint string (`your-project-slug/qwen-finetune`, printed by the deploy output) as the `model` parameter, not the Model Object ID. If `deploy` reports that the model has more than one deployment profile, re-run it with `--config `. List a model's profiles with `tg models configs ""`. > [!TIP] > > Congrats! You fine-tuned a model, deployed it to a dedicated endpoint, and ran inference end-to-end. ## Step 5: Compare against the base model (optional) To measure the impact of fine-tuning, run the same prompts through the base model and the fine-tuned model. > [!NOTE] > > **Many fine-tunable base models aren't available on [serverless](/docs/serverless/models):** For example, calling `Qwen/Qwen3.5-9B` directly returns `Unable to access non-serverless model`. To compare, deploy the base on its own [dedicated endpoint](/docs/dedicated-endpoints/overview), evaluate against its endpoint string, then tear that endpoint down too. Serverless bases (those with a per-token price listed on the [models dashboard](https://api.together.ai/models)) can be called directly without deploying anything. This [GitHub notebook](https://github.com/togethercomputer/together-cookbook/blob/main/fine-tuning/Finetuning_Guide.ipynb) runs an Exact Match and F1 comparison on the CoQA validation split. Here's a sample result from one run: | Model | EM | F1 | | - | - | - | | Base | 0.01 | 0.18 | | Fine-tuned | 0.32 | 0.41 | ## Stop the endpoint Dedicated model inference bills per minute per running replica as long as the deployment is running. Step 4 deletes the endpoint at the end, but if you skipped that step or want to delete it later, run: ```bash theme={null} tg endpoints rm "" --force ``` Find the endpoint ID by running `tg endpoints ls`. ## Continue from a checkpoint Resume training from an existing job by passing `from_checkpoint`: ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --from-checkpoint "" ``` ```python Python theme={null} job = client.fine_tuning.create( training_file="", from_checkpoint="", ) ``` `from_checkpoint` accepts the output model name, the job ID, or a specific step in the form `ft-...:{STEP_NUM}`. List available checkpoints with `tg fine-tuning list-checkpoints `. > [!NOTE] > > Whether training continues the previous job's LoRA adapter or merges it into the base model depends on the [training types and LoRA settings of both jobs](/docs/fine-tuning/lora-vs-full#continue-training-from-a-checkpoint). ## Next steps > [card] [Data preparation](/docs/fine-tuning/data-preparation) > > See the full schema for conversational, instruction, preference, and tokenized data. > [card] [Supported models](/docs/fine-tuning/supported-models) > > Browse base models with context lengths and batch size limits. > [card] [Preference tuning](/docs/fine-tuning/preference-tuning) > > Align a model with paired preferred and dispreferred responses. > [card] [Deploy your model](/docs/fine-tuning/deployment) > > Hosting, teardown, and local inference for fine-tuned models. # Reasoning fine-tuning Source: https://docs.together.ai/docs/fine-tuning/reasoning Train a reasoning model on chain-of-thought data. Reasoning fine-tuning adapts a model that supports chain-of-thought reasoning. By providing `reasoning` or `reasoning_content` alongside the final assistant response, you shape how the model thinks through problems before producing an answer. This page covers the reasoning data shape, supported models, and launch parameters. > [!WARNING] > > Reasoning models should always be fine-tuned with reasoning data. Training a reasoning model without it can degrade its reasoning ability. If your dataset doesn't include reasoning, use an instruct model instead. ## Supported models The following models support reasoning fine-tuning. See [supported models](/docs/fine-tuning/supported-models) for context lengths and batch limits. > [accordion] Supported models > > | Organization | Model | API ID | > | - | - | - | > | DeepSeek | DeepSeek V4 Flash 0731 | `deepseek-ai/DeepSeek-V4-Flash-0731` | > | DeepSeek | DeepSeek V4 Flash | `deepseek-ai/DeepSeek-V4-Flash` | > | Z.ai | GLM 5.3 | `zai-org/GLM-5.3` | > | Z.ai | GLM 5.2 | `zai-org/GLM-5.2` | > | Z.ai | GLM 5.1 | `zai-org/GLM-5.1` | > | Qwen | Qwen3.8 27B | `Qwen/Qwen3.8-27B` | > | Qwen | Qwen3.6 35B A3B | `Qwen/Qwen3.6-35B-A3B` | > | Qwen | Qwen3.5 9B | `Qwen/Qwen3.5-9B` | > | Qwen | Qwen3.5 4B | `Qwen/Qwen3.5-4B` | > | Qwen | Qwen3.6 27B | `Qwen/Qwen3.6-27B` | > | Qwen | Qwen3.5 397B A17B | `Qwen/Qwen3.5-397B-A17B` | > | Qwen | Qwen3.5 122B A10B | `Qwen/Qwen3.5-122B-A10B` | > | Qwen | Qwen3.5 35B A3B | `Qwen/Qwen3.5-35B-A3B` | > | Qwen | Qwen3.5 27B | `Qwen/Qwen3.5-27B` | > | Google | Gemma 4 31B IT | `google/gemma-4-31B-it` | > | Google | Gemma 4 31B IT VLM | `google/gemma-4-31B-it-VLM` | > | Google | Gemma 4 26B A4B IT | `google/gemma-4-26B-A4B-it` | > | OpenAI | GPT-OSS 20B | `openai/gpt-oss-20b` | > | OpenAI | GPT-OSS 120B | `openai/gpt-oss-120b` | ## Prepare your data Prepare data in a JSONL file. Each assistant message should carry the chain of thought in a `reasoning` (or `reasoning_content`) field and the final answer in `content`. ### Conversational format ```json theme={null} { "messages": [ {"role": "user", "content": "What is the capital of France?"}, { "role": "assistant", "reasoning": "The user is asking about the capital of France. France is a country in Western Europe. Its capital city is Paris, which has been the capital since the 10th century.", "content": "The capital of France is Paris." } ] } ``` > [!NOTE] > > When fine-tuning reasoning models on conversational data, only the last assistant message is trained on by default. For multi-turn reasoning, split the conversation so each assistant message is the final message in its own example. ### Preference format For preference fine-tuning, both outputs carry `reasoning`. See [preference tuning](/docs/fine-tuning/preference-tuning) for the broader DPO workflow. ```json theme={null} { "input": { "messages": [ {"role": "user", "content": "What is the capital of France?"} ] }, "preferred_output": [ { "role": "assistant", "reasoning": "France is in Western Europe. Its capital is Paris.", "content": "The capital of France is Paris." } ], "non_preferred_output": [ { "role": "assistant", "reasoning": "Let me think about European capitals.", "content": "The capital of France is Berlin." } ] } ``` ## Validate and upload Upload your data using the Together Python/TypeScript SDK or the [Together CLI](/reference/cli/getting-started): ```bash CLI theme={null} tg files check "reasoning_dataset.jsonl" tg files upload "reasoning_dataset.jsonl" ``` ```python Python theme={null} from together import Together client = Together() train_file = client.files.upload( file="reasoning_dataset.jsonl", purpose="fine-tune", check=True, ) print(train_file.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const trainFile = await client.files.upload( "reasoning_dataset.jsonl", "fine-tune", ); console.log(trainFile.id); ``` ## Launch the job Low-rank adapter (LoRA) training is the default. Pass `lora=False` for full fine-tuning. ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3-8B" \ --lora ``` ```python Python theme={null} job = client.fine_tuning.create( training_file=train_file.id, model="Qwen/Qwen3-8B", lora=True, ) print(job.id) ``` ```typescript TypeScript theme={null} const job = await client.fineTuning.create({ training_file: trainFile.id, model: "Qwen/Qwen3-8B", lora: true, }); console.log(job.id); ``` For details on every available parameter, see the [API reference](/reference/cli/finetune). ## Watch and deploy Reasoning jobs use the same lifecycle as text jobs: * [Poll the job](/docs/fine-tuning/monitoring#poll-until-the-job-is-done) with the SDK or CLI. Expect 10 to 30 minutes for a LoRA job on an 8B model with a few thousand examples. * Deploy the result on a [dedicated endpoint](/docs/fine-tuning/deployment). * Call the endpoint with the same chat-completions shape. The model emits `reasoning_content` alongside `content` for clients that surface it. See [Inference → Reasoning](/docs/inference/chat/reasoning) for details. # Supervised fine-tuning Source: https://docs.together.ai/docs/fine-tuning/supervised Train a model on demonstration data with supervised fine-tuning (SFT). Supervised fine-tuning (SFT) trains a model on *demonstration data*: examples that pair an input with the exact completion you want the model to produce. It's the default training method on Together AI and the right starting point for most use cases. To train on ranked pairs of good and bad responses instead, see [preference fine-tuning](/docs/fine-tuning/preference-tuning). Both methods share the same [job lifecycle](/docs/fine-tuning/quickstart). ## When to use supervised fine-tuning Use SFT when: * **You have demonstrations of the target behavior:** Each example shows one correct completion for an input, which is the standard format for instruction and conversational data. * **You want to teach a new task, style, or format:** SFT shifts the model toward the patterns in your training data. * **You're starting a new fine-tune:** SFT should be your foundation for most use cases. If you later need to align the model against ranked outputs, run [direct preference optimization (DPO)](/docs/fine-tuning/preference-tuning) on top of the SFT checkpoint. If your input dataset is made up of paired preferred and dispreferred responses for the same input, you can start with [preference fine-tuning](/docs/fine-tuning/preference-tuning) instead. ## Prepare your data SFT accepts [conversational, instruction, and general text formats](/docs/fine-tuning/data-preparation). Each line carries a single target completion. ## Launch a fine-tuning job Pass a training file and a base model. SFT is the default `training_method`, so you don't need to set it. Here's the minimum code to start a supervised fine-tuning job: ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3.5-9B" ``` ```python Python theme={null} from together import Together client = Together() job = client.fine_tuning.create( training_file="", model="Qwen/Qwen3.5-9B", ) print(job.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const job = await client.fineTuning.create({ training_file: "", model: "Qwen/Qwen3.5-9B", }); console.log(job.id); ``` ## Key parameters These are the parameters you'll reach for most often. The full list lives in the [fine-tuning API reference](/reference/post-fine-tunes). | Parameter | Default | Description | | - | - | - | | `n_epochs` | `1` | Number of passes over the dataset. Range is 1 to 20. | | `learning_rate` | `0.00001` | Learning rate multiplier. | | `batch_size` | `max` | Per-iteration batch size. See [supported models](/docs/fine-tuning/supported-models) for the min and max per model. | | `train_on_inputs` | `auto` | Whether to compute loss on the input tokens. `auto` masks inputs for conversational and instruction data, and trains on them for general text data. | | `validation_file` | none | A held-out file to evaluate against during training. Required when `n_evals > 0`. | | `suffix` | none | Up to 40 characters appended to the output model name to tell your fine-tunes apart. | To stop a run automatically when validation loss plateaus, see [early stopping](/docs/fine-tuning/early-stopping). ## Choose LoRA or full fine-tuning SFT runs as either low-rank adapter (LoRA) training (the default) or full fine-tuning. That choice is independent of the training method and affects cost, batch size, and how you deploy the result. See [LoRA vs. full fine-tuning](/docs/fine-tuning/lora-vs-full) to decide and to configure LoRA's rank and target modules. ## Next steps > [card] [Track training](/docs/fine-tuning/monitoring) > > Retrieve per-step loss, learning rate, and evaluation metrics. > [card] [Deploy your model](/docs/fine-tuning/deployment) > > Serve the result on a dedicated endpoint or download the weights. > [card] [Continue with DPO](/docs/fine-tuning/preference-tuning) > > Continue training the SFT checkpoint with DPO to align it against ranked outputs. # Supported models Source: https://docs.together.ai/docs/fine-tuning/supported-models Every base model available for fine-tuning, with context length and batch size limits. The tables below list every model available through the fine-tuning API. Context lengths are the maximum for that model in SFT and DPO modes. Batch sizes refer to packed batches for text formats. See [data preparation](/docs/fine-tuning/data-preparation) for details on packing. > [!WARNING] > > Some models can be fine-tuned but cannot be deployed as dedicated endpoints. To verify deployability before training, confirm the base model appears in the [supported models](/docs/dedicated-endpoints/models) list for dedicated model inference (or run `tg models configs `). If it isn't listed there, the fine-tune can't be hosted on a dedicated endpoint. [Fill out this form](https://www.together.ai/forms/model-requests) to request a model that isn't in the list. > [card] [LoRA fine-tuning](#lora-fine-tuning) > [card] [Full fine-tuning](#full-fine-tuning) > [card] [Vision-language](#vision-language-models) > [card] [LoRA target modules](#lora-target-modules) ## LoRA fine-tuning | Organization | Model | API ID | Context (SFT) | Context (DPO) | Max batch (SFT) | Max batch (DPO) | Min batch | Grad accum | Default LoRA rank | Max LoRA rank | | - | - | - | - | - | - | - | - | - | - | - | | DeepSeek | DeepSeek V4 Flash 0731 | `deepseek-ai/DeepSeek-V4-Flash-0731` | 131072 | 32768 | 1 | 1 | 1 | 8 | 64 | 128 | | DeepSeek | DeepSeek V3.1 | `deepseek-ai/DeepSeek-V3.1` | 65536 | 32768 | 2 | 2 | 2 | 8 | 16 | 16 | | DeepSeek | DeepSeek V4 Flash | `deepseek-ai/DeepSeek-V4-Flash` | 131072 | 32768 | 1 | 1 | 1 | 8 | 64 | 128 | | Z.ai | GLM 5.3 | `zai-org/GLM-5.3` | 50688 | 25344 | 1 | 1 | 1 | 1 | 16 | 16 | | Z.ai | GLM 5.2 | `zai-org/GLM-5.2` | 50688 | 25344 | 1 | 1 | 1 | 1 | 16 | 16 | | Z.ai | GLM 5.1 | `zai-org/GLM-5.1` | 50688 | 25344 | 1 | 1 | 1 | 1 | 16 | 16 | | Qwen | Qwen3.8 27B | `Qwen/Qwen3.8-27B` | 131072 | 65536 | 2 | 2 | 2 | 4 | 64 | 128 | | Qwen | Qwen3.6 35B A3B | `Qwen/Qwen3.6-35B-A3B` | 65536 | 32768 | 8 | 8 | 8 | 1 | 64 | 128 | | Qwen | Qwen3.5 9B | `Qwen/Qwen3.5-9B` | 65536 | 49152 | 8 | 8 | 8 | 1 | 64 | 128 | | Qwen | Qwen3.5 4B | `Qwen/Qwen3.5-4B` | 131072 | 65536 | 8 | 8 | 8 | 1 | 64 | 128 | | Qwen | Qwen3.6 27B | `Qwen/Qwen3.6-27B` | 131072 | 65536 | 2 | 2 | 2 | 4 | 64 | 128 | | Qwen | Qwen3.5 397B A17B | `Qwen/Qwen3.5-397B-A17B` | 32768 | 16384 | 16 | 16 | 16 | 1 | 64 | 128 | | Qwen | Qwen3.5 122B A10B | `Qwen/Qwen3.5-122B-A10B` | 65536 | 32768 | 16 | 16 | 16 | 1 | 64 | 128 | | Qwen | Qwen3.5 35B A3B | `Qwen/Qwen3.5-35B-A3B` | 65536 | 32768 | 8 | 8 | 8 | 1 | 64 | 128 | | Qwen | Qwen3.5 27B | `Qwen/Qwen3.5-27B` | 131072 | 65536 | 2 | 2 | 2 | 4 | 64 | 128 | | Moonshot AI | Kimi K2.7 Code | `moonshotai/Kimi-K2.7-Code` | 32768 | 16384 | 4 | 4 | 4 | 8 | 16 | 16 | | Moonshot AI | Kimi K2.6 | `moonshotai/Kimi-K2.6` | 32768 | 16384 | 4 | 4 | 4 | 8 | 16 | 16 | | Google | Gemma 4 31B IT | `google/gemma-4-31B-it` | 49152 | 24576 | 4 | 4 | 4 | 2 | 64 | 128 | | Google | Gemma 4 31B IT VLM | `google/gemma-4-31B-it-VLM` | 24576 | 12288 | 8 | 8 | 8 | 1 | 64 | 128 | | Google | Gemma 4 26B A4B IT | `google/gemma-4-26B-A4B-it` | 49152 | 24576 | 4 | 4 | 4 | 2 | 64 | 128 | | OpenAI | GPT-OSS 20B | `openai/gpt-oss-20b` | 131072 | 65536 | 1 | 1 | 1 | 8 | 64 | 128 | | OpenAI | GPT-OSS 120B | `openai/gpt-oss-120b` | 65536 | 32768 | 2 | 2 | 2 | 8 | 64 | 128 | | Meta | Llama 4 Scout 17B 16E Instruct | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | 65536 | 12288 | 8 | 8 | 8 | 1 | 64 | 128 | | Meta | Llama 4 Scout 17B 16E Instruct VLM | `meta-llama/Llama-4-Scout-17B-16E-Instruct-VLM` | 32768 | 32768 | 8 | 8 | 8 | 1 | 64 | 128 | | Meta | Llama 4 Maverick 17B 128E Instruct | `meta-llama/Llama-4-Maverick-17B-128E-Instruct` | 16384 | 24576 | 16 | 16 | 16 | 1 | 64 | 128 | | Meta | Llama 4 Maverick 17B 128E Instruct VLM | `meta-llama/Llama-4-Maverick-17B-128E-Instruct-VLM` | 16384 | 16384 | 16 | 16 | 16 | 1 | 64 | 128 | | Meta | Llama 3.3 70B Instruct Reference | `meta-llama/Llama-3.3-70B-Instruct-Reference` | 24576 | 12288 | 8 | 8 | 8 | 1 | 64 | 128 | | Meta | Meta Llama 3.1 8B Instruct Reference | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | 131072 | 65536 | 8 | 8 | 8 | 1 | 64 | 128 | | Mistral | Mixtral 8x7B Instruct v0.1 | `mistralai/Mixtral-8x7B-Instruct-v0.1` | 32768 | 16384 | 8 | 8 | 8 | 1 | 64 | 128 | ## Full fine-tuning | Organization | Model | API ID | Context (SFT) | Context (DPO) | Max batch (SFT) | Max batch (DPO) | Min batch | | - | - | - | - | - | - | - | - | | Qwen | Qwen3.8 27B | `Qwen/Qwen3.8-27B` | 131072 | 65536 | 4 | 4 | 4 | | Qwen | Qwen3.5 9B | `Qwen/Qwen3.5-9B` | 65536 | 49152 | 8 | 8 | 8 | | Qwen | Qwen3.5 4B | `Qwen/Qwen3.5-4B` | 131072 | 65536 | 8 | 8 | 8 | | Qwen | Qwen3.6 27B | `Qwen/Qwen3.6-27B` | 131072 | 65536 | 4 | 4 | 4 | | Qwen | Qwen3.5 27B | `Qwen/Qwen3.5-27B` | 131072 | 65536 | 4 | 4 | 4 | | Google | Gemma 4 31B IT | `google/gemma-4-31B-it` | 49152 | 24576 | 8 | 8 | 8 | | Google | Gemma 4 31B IT VLM | `google/gemma-4-31B-it-VLM` | 24576 | 12288 | 16 | 16 | 16 | | Meta | Llama 3.3 70B Instruct Reference | `meta-llama/Llama-3.3-70B-Instruct-Reference` | 24576 | 12288 | 32 | 32 | 32 | | Meta | Meta Llama 3.1 8B Instruct Reference | `meta-llama/Meta-Llama-3.1-8B-Instruct-Reference` | 131072 | 65536 | 8 | 8 | 8 | | Mistral | Mixtral 8x7B Instruct v0.1 | `mistralai/Mixtral-8x7B-Instruct-v0.1` | 32768 | 16384 | 16 | 16 | 16 | ## Vision-language models For the list of models that support vision-language fine-tuning on image and text data, along with the dataset schema and the `train_vision` parameter, see [vision fine-tuning](/docs/fine-tuning/vision). ## LoRA target modules See [LoRA vs. full fine-tuning](/docs/fine-tuning/lora-vs-full#default-target-modules) for the default target modules per model. Pass `lora_trainable_modules="all-linear"` to train every linear layer. ## Model limits from the CLI To get more detailed fine-tuning constraints for a specific model, including learning-rate bounds, batch-size limits, and the LoRA rank and target modules, run [`tg fine-tuning model-limits `](/reference/cli/finetune#model-limits). # Troubleshooting fine-tuning jobs Source: https://docs.together.ai/docs/fine-tuning/troubleshooting Diagnose failed or cancelled fine-tuning jobs, understand job timing, and resolve common errors. This page covers what to expect while a job runs and how to diagnose the most common failures. To inspect a job's status and history, run `tg fine-tuning retrieve ` and `tg fine-tuning list-events `, or open the [jobs dashboard](https://api.together.ai/jobs). ## Job timing **Time to start:** A job moves through `pending`, `queued`, and `running` before training begins. Start time depends on queue depth and hardware availability. With no other pending jobs and free hardware, a job usually reaches `running` within a minute, and most jobs start within an hour. There is no SLA on queue wait time. **Run time:** Run time depends on model size, dataset size, and network speed during the model and data downloads. Once a job is running, its estimated time remaining may appear on the [jobs dashboard](https://api.together.ai/jobs) or in the `tg fine-tuning retrieve` output. For a rough estimate of total training time, multiply the time the first epoch takes by your `n_epochs` value. ## Diagnose a failed or stopped job A job that doesn't finish ends in one of three states: * **Cancelled:** Usually an automatic cancellation, most often from a failed balance check. Add funds or raise your spending limit, then resubmit. * **User error:** A problem with your inputs, most often a dataset that fails [server-side validation](#data-validation-failures) or an incompatible continued-fine-tuning checkpoint. The event log names the specific reason. Invalid Weights & Biases credentials also end a job this way: a wrong `wandb_api_key` fails the job during training with an `Unable to authenticate with Weights & Biases` event, and a `wandb_entity` you lack access to fails it with a permission error. * **Error:** A problem on Together AI's side. These are usually transient. Together AI support follows up on the failure, or you can [contact support](https://portal.usepylon.com/together-ai/forms/support-request) directly. Read the event log to confirm the specific cause before you act: ```bash theme={null} tg fine-tuning list-events ``` In the web UI, the same events appear under the **Logs** tab on the job's page in the [jobs dashboard](https://api.together.ai/jobs). ## File upload failures If a training file fails to upload, the CLI and the Together AI console return an error that names the reason, such as an insufficient balance. A 401 or 403 error means your credentials are missing or inactive: * **CLI:** Run `tg whoami` to check your login, or run `tg login` to log in again. * **SDK:** Check that `TOGETHER_API_KEY` is set to an active API key. ## Data validation failures Most dataset validation runs server-side during ingestion, after upload and before training. If a job stops with a data-related error, inspect the event log and the file's [validation report](/docs/fine-tuning/data-preparation#wait-for-server-side-validation). ## Automatic restarts If a job hits an internal (Together AI-side) error, such as a hardware failure, it may be restarted automatically. Restarts aren't guaranteed. Check the event log for a restart event, the new job ID, and a refund line. The refund is automatic. If a job doesn't restart, Together AI support follows up on the failure, or you can [contact support](https://portal.usepylon.com/together-ai/forms/support-request) directly. ## Error codes Fine-tuning API requests return standard HTTP status codes. For the full list of codes, causes, and fixes, see [Error codes](/docs/error-codes). Transient 5xx errors (503, 504, 524, and 529) are safe to retry after a short wait. [Contact support](https://portal.usepylon.com/together-ai/forms/support-request) if they persist. # Vision fine-tuning Source: https://docs.together.ai/docs/fine-tuning/vision Fine-tune vision-language models on image and text data with Together AI. Vision-language models (VLMs) combine language understanding with visual comprehension. Fine-tuning a VLM adapts it to image-and-text tasks such as visual question answering, image captioning, and document understanding. This page covers the VLM-specific data shape, supported models, and launch parameters. ## Supported models The following models support vision-language fine-tuning. See [supported models](/docs/fine-tuning/supported-models) for context lengths and batch limits. > [accordion] Supported models > > | Organization | Model | API ID | > | - | - | - | > | Qwen | Qwen3.8 27B | `Qwen/Qwen3.8-27B` | > | Qwen | Qwen3.5 9B | `Qwen/Qwen3.5-9B` | > | Qwen | Qwen3.5 4B | `Qwen/Qwen3.5-4B` | > | Qwen | Qwen3.6 27B | `Qwen/Qwen3.6-27B` | > | Qwen | Qwen3.5 27B | `Qwen/Qwen3.5-27B` | > | Google | Gemma 4 31B IT VLM | `google/gemma-4-31B-it-VLM` | > | Meta | Llama 4 Scout 17B 16E Instruct VLM | `meta-llama/Llama-4-Scout-17B-16E-Instruct-VLM` | > | Meta | Llama 4 Maverick 17B 128E Instruct VLM | `meta-llama/Llama-4-Maverick-17B-128E-Instruct-VLM` | ## Prepare your data Prepare your data as a JSONL file with one example per line. Each example's messages can mix text and images, and the images must meet these requirements: * **Message role:** Only `user` messages can contain images. * **Image encoding:** Each image is base64-encoded with a MIME type prefix (`data:image/jpeg;base64,...`). If your data references URLs, download and encode the images first. * **Supported formats:** PNG, JPEG, WEBP. * **Per-image size:** 10 MB. * **Aspect ratio:** At most 200:1, measured as the longest side divided by the shortest side. A file containing a wider or taller image is rejected at upload. * **Per-example image limit:** 10 images. ### Conversational format ```json theme={null} { "messages": [ { "role": "system", "content": [ {"type": "text", "text": "You are a helpful assistant with vision capabilities."} ] }, { "role": "user", "content": [ {"type": "text", "text": "How many oranges are in the bowl?"}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,iVBORw0KGgo..."}} ] }, { "role": "assistant", "content": [ {"type": "text", "text": "There are at least 7 oranges in this bowl."} ] } ] } ``` ### Instruction format ```json theme={null} { "prompt": [ {"type": "text", "text": "How many oranges are in the bowl?"}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,iVBORw0KGgo..."}} ], "completion": [ {"type": "text", "text": "There are at least 7 oranges in this bowl."} ] } ``` ### Preference format ```json theme={null} { "input": { "messages": [ { "role": "user", "content": [ {"type": "text", "text": "How many oranges are in the bowl?"}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,iVBORw0KGgo..."}} ] } ] }, "preferred_output": [ {"role": "assistant", "content": [{"type": "text", "text": "There are at least 7 oranges."}]} ], "non_preferred_output": [ {"role": "assistant", "content": [{"type": "text", "text": "There are 11 oranges."}]} ] } ``` ### Convert image URLs to base64 ```python Python theme={null} import base64 import requests def url_to_base64(url: str, mime_type: str = "image/jpeg") -> str: response = requests.get(url) encoded = base64.b64encode(response.content).decode("utf-8") return f"data:{mime_type};base64,{encoded}" ``` ## Validate and upload Upload your data using the Together Python/TypeScript SDK or the [Together CLI](/reference/cli/getting-started): ```bash CLI theme={null} tg files check "vlm_dataset.jsonl" tg files upload "vlm_dataset.jsonl" ``` ```python Python theme={null} from together import Together client = Together() train_file = client.files.upload( file="vlm_dataset.jsonl", purpose="fine-tune", check=True, ) print(train_file.id) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const client = new Together(); const trainFile = await client.files.upload("vlm_dataset.jsonl", "fine-tune"); console.log(trainFile.id); ``` Sample response: ```json theme={null} { "id": "file-629e58b4-ff73-438c-b2cc-f69542b27980", "object": "file", "purpose": "fine-tune", "filename": "vlm_dataset.jsonl", "FileType": "jsonl" } ``` ## Launch the job By default, fine-tuning only updates language-model parameters. Pass `train_vision=True` to also update the vision encoder. The trade-off here is that training the encoder costs more compute and is rarely necessary unless your domain images are extremely dissimilar from the pretraining data. ```bash CLI theme={null} tg fine-tuning create \ --training-file "" \ --model "Qwen/Qwen3-VL-8B-Instruct" \ --train-vision false \ --lora ``` ```python Python theme={null} job = client.fine_tuning.create( training_file=train_file.id, model="Qwen/Qwen3-VL-8B-Instruct", lora=True, train_vision=False, ) print(job.id) ``` ```typescript TypeScript theme={null} const job = await client.fineTuning.create({ training_file: trainFile.id, model: "Qwen/Qwen3-VL-8B-Instruct", lora: true, train_vision: false, }); console.log(job.id); ``` For full fine-tuning, set `lora=False`. For details on all available parameters, see the [API reference](/reference/cli/finetune). ## Watch and deploy VLM jobs use the same lifecycle as text jobs: * [Poll the job](/docs/fine-tuning/monitoring#poll-until-the-job-is-done) with the SDK or CLI. Expect 15 to 60 minutes for a low-rank adapter (LoRA) job on an 8B model with a few thousand examples, and several hours for a full job on a 30B model. * Deploy the result on a [dedicated endpoint](/docs/fine-tuning/deployment). VLM endpoints accept the same vision request shapes as the base models. See [vision inputs](/docs/inference/vision/inputs) for details. # GLM-5.3 quickstart Source: https://docs.together.ai/docs/glm-5.3-quickstart Call GLM-5.3 and GLM-5.3 Flash on Together for long-horizon coding and agentic work. GLM-5.3 is Z.ai's flagship mixture-of-experts (MoE) model, built for long-horizon coding and agentic work. It holds project-scale context across many steps and completes multi-stage tasks end to end. Thinking is on by default, so responses carry both a reasoning trace and a final answer. Two variants are available on serverless inference, both with a 1M-token context window, streaming, function calling, and structured outputs: | Model | Model ID | Input / 1M tokens | Cached input / 1M tokens | Output / 1M tokens | | - | - | - | - | - | | GLM-5.3 | `zai-org/GLM-5.3` | \$1.40 | \$0.26 | \$4.40 | | GLM-5.3 Flash | `zai-org/GLM-5.3-Flash` | \$0.15 | \$0.03 | \$0.50 | GLM-5.3 is Together's [recommended pick](/docs/inference/recommended-models) for coding agents. GLM-5.3 Flash is the recommended pick for function calling and other high-volume calls. The examples below use `zai-org/GLM-5.3`. Swap in `zai-org/GLM-5.3-Flash` when cost and latency matter more than maximum depth. ## Call GLM-5.3 The reasoning trace arrives on `reasoning_content` and the final answer arrives on `content`. Stream the response and handle both channels, and skip chunks where `choices` is empty, since Together emits a final usage-only chunk. GLM-5.3 emits the trace under `reasoning_content`, while some other Together models use the newer `reasoning` alias. Reading both keys makes one handler work across models. ```python Python theme={null} from together import Together client = Together() stream = client.chat.completions.create( model="zai-org/GLM-5.3", messages=[ { "role": "user", "content": "What are some fun things to do in New York?", } ], temperature=1.0, top_p=0.95, max_tokens=8192, stream=True, ) for chunk in stream: if not chunk.choices: continue delta = chunk.choices[0].delta thinking = getattr(delta, "reasoning_content", None) or getattr( delta, "reasoning", None ) # Stream reasoning and content tokens as they arrive print(thinking or delta.content or "", end="", flush=True) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; import type { ChatCompletionChunk } from "together-ai/resources/chat/completions"; const together = new Together(); // GLM-5.3 emits the trace on reasoning_content; other models use reasoning type ReasoningDelta = ChatCompletionChunk.Choice.Delta & { reasoning_content?: string; reasoning?: string; }; const stream = await together.chat.completions.create({ model: "zai-org/GLM-5.3", messages: [ { role: "user", content: "What are some fun things to do in New York?", }, ], temperature: 1.0, top_p: 0.95, max_tokens: 8192, stream: true, }); for await (const chunk of stream) { if (!chunk.choices?.length) continue; const delta = chunk.choices[0]?.delta as ReasoningDelta; const thinking = delta?.reasoning_content || delta?.reasoning; // Stream reasoning and content tokens as they arrive process.stdout.write(thinking || delta?.content || ""); } ``` ```bash cURL theme={null} curl -X POST "https://api.together.ai/v1/chat/completions" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "zai-org/GLM-5.3", "messages": [ {"role": "user", "content": "What are some fun things to do in New York?"} ], "temperature": 1.0, "top_p": 0.95, "max_tokens": 8192, "stream": true }' ``` ## Set the reasoning effort `reasoning_effort` accepts `"low"`, `"medium"`, `"high"`, and `"max"`. Use `"low"` for short, high-volume calls and `"max"` for the hardest planning, architecture, and multi-step agentic problems. At `"max"`, set `max_tokens` generously, since the trace and the answer share the same completion budget. Thinking cannot be disabled entirely on GLM-5.3. `reasoning_effort="low"` cuts the trace to a few tokens, which is the closest equivalent for trivial turns. The levels are coarse dials rather than a strictly monotonic scale, so measure token counts on your own prompts before you tune. Invalid effort strings are accepted silently instead of returning an error, so validate the value in your own code. ```python Python theme={null} from together import Together client = Together() completion = client.chat.completions.create( model="zai-org/GLM-5.3", messages=[ { "role": "user", "content": "Design a three-tier architecture for a ticketing system.", } ], reasoning_effort="max", max_tokens=65536, ) print(completion.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const completion = await together.chat.completions.create({ model: "zai-org/GLM-5.3", messages: [ { role: "user", content: "Design a three-tier architecture for a ticketing system.", }, ], reasoning_effort: "max", max_tokens: 65536, }); console.log(completion.choices[0].message.content); ``` For broader guidance on reasoning controls and prompting, see [Reasoning](/docs/inference/chat/reasoning). ## Preserve thinking across turns For coding agents and other agent workflows, enable preserved thinking so the model retains its reasoning from previous turns. Set `"clear_thinking": false` in `chat_template_kwargs` to keep reasoning content in context across turns, which improves reasoning continuity and cache hit rates. ```python Python theme={null} from together import Together client = Together() response = client.chat.completions.create( model="zai-org/GLM-5.3", messages=[ { "role": "user", "content": "Refactor this module without changing its public API.", } ], chat_template_kwargs={ "clear_thinking": False, # Preserved thinking }, ) print(response.choices[0].message.content) ``` > [!NOTE] > > When using preserved thinking, return the model's `reasoning_content` blocks exactly as generated. Reordering or editing them degrades performance and hurts cache hit rates. ## Call tools GLM-5.3 supports tool calling with reasoning interleaved between each step. Define tools in the standard OpenAI-compatible schema and pass them via `tools`. To stream tool calls, set `stream=True`. The model emits tool call parameters incrementally, so concatenate the `arguments` fragments from each delta to rebuild the full call. Together does not use a separate `tool_stream` parameter. ```python Python theme={null} from together import Together client = Together() tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather conditions for a city.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name, e.g. Beijing, Shanghai.", }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], }, }, "required": ["location"], }, }, } ] stream = client.chat.completions.create( model="zai-org/GLM-5.3", messages=[{"role": "user", "content": "What's the weather in Beijing?"}], tools=tools, stream=True, ) final_tool_calls = {} for chunk in stream: if not chunk.choices: continue delta = chunk.choices[0].delta # Reassemble streamed tool calls by index. The first delta for a call # carries the name, and later deltas carry argument fragments. if delta.tool_calls: for tool_call in delta.tool_calls: idx = tool_call.index if idx not in final_tool_calls: final_tool_calls[idx] = { "name": tool_call.function.name, "arguments": "", } final_tool_calls[idx]["arguments"] += ( tool_call.function.arguments or "" ) for call in final_tool_calls.values(): print(f"{call['name']}: {call['arguments']}") ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const tools = [ { type: "function" as const, function: { name: "get_weather", description: "Get current weather conditions for a city.", parameters: { type: "object", properties: { location: { type: "string", description: "City name, e.g. Beijing, Shanghai.", }, unit: { type: "string", enum: ["celsius", "fahrenheit"] }, }, required: ["location"], }, }, }, ]; const stream = await together.chat.completions.create({ model: "zai-org/GLM-5.3", messages: [{ role: "user", content: "What's the weather in Beijing?" }], tools, stream: true, }); const finalToolCalls: Record = {}; for await (const chunk of stream) { const delta = chunk.choices[0]?.delta; if (!delta?.tool_calls) continue; for (const toolCall of delta.tool_calls) { const idx = toolCall.index; if (!(idx in finalToolCalls)) { finalToolCalls[idx] = { name: toolCall.function?.name ?? "", arguments: toolCall.function?.arguments ?? "", }; } else { finalToolCalls[idx].arguments += toolCall.function?.arguments ?? ""; } } } for (const idx in finalToolCalls) { const call = finalToolCalls[idx]; console.log(`${call.name}: ${call.arguments}`); } ``` For the full tool-calling loop, including how to return tool results to the model, see [Function calling](/docs/inference/function-calling/overview). ## Constrain the output to a schema GLM-5.3 supports [structured outputs](/docs/inference/chat/structured-outputs). Pass a JSON schema through `response_format` to constrain the response to a fixed shape. Parse `content` only, never `reasoning_content`. ```python Python theme={null} from together import Together client = Together() response = client.chat.completions.create( model="zai-org/GLM-5.3", messages=[ { "role": "user", "content": "Extract the person: John is 30 years old.", } ], response_format={ "type": "json_schema", "json_schema": { "name": "person", "schema": { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, }, "required": ["name", "age"], }, }, }, ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const response = await together.chat.completions.create({ model: "zai-org/GLM-5.3", messages: [ { role: "user", content: "Extract the person: John is 30 years old." }, ], response_format: { type: "json_schema", json_schema: { name: "person", schema: { type: "object", properties: { name: { type: "string" }, age: { type: "integer" }, }, required: ["name", "age"], }, }, }, }); console.log(response.choices[0].message.content); ``` ## Usage tips | Tip | Rationale | | - | - | | **Read both `reasoning_content` and `reasoning`** | GLM-5.3 emits the trace on `reasoning_content`. Other Together models use the `reasoning` alias. One handler then covers both. | | **Parse `content` only** | Never run JSON parsing over the thinking trace. | | **Temperature = 1.0, top\_p = 0.95** | Recommended defaults. Adjust only one of the two, not both at once. | | **Match `reasoning_effort` to the task** | Use `"low"` for trivial turns and `"max"` with generous `max_tokens` for hard planning and architecture work. | | **Use GLM-5.3 Flash for high-volume calls** | Same 1M context and tool support at a fraction of the price, for function calling and latency-sensitive work. | | **Use preserved thinking for agents** | Set `"clear_thinking": false` in `chat_template_kwargs` so coding agents keep reasoning continuity across turns. | | **Think in goals, not steps** | GLM-5.3 is agentic. Give high-level objectives and let it orchestrate sub-tasks and tool calls. | | **State constraints explicitly** | For engineering tasks, spell out hard constraints (no new dependencies, no API changes, run the tests) so the model holds the line. | ## Next steps > [card] [Reasoning](/docs/inference/chat/reasoning) > > Control reasoning depth and handle reasoning output across models. > [card] [Function calling](/docs/inference/function-calling/overview) > > Build tool-calling loops against any function-calling model. > [card] [Recommended models](/docs/inference/recommended-models) > > See Together's current picks for every use case. > [card] [Serverless models](/docs/serverless/models) > > Browse every model, context length, and price on serverless inference. # GPT-OSS quickstart Source: https://docs.together.ai/docs/gpt-oss Call OpenAI's GPT-OSS 120B open-weight reasoning model on Together. GPT-OSS 120B is OpenAI's open-weight mixture-of-experts (MoE) reasoning model. It thinks step by step before answering and exposes an adjustable reasoning effort, so you can trade depth for cost and latency. The model ID is `openai/gpt-oss-120b`. Pricing is \$0.15 per 1M input tokens and \$0.60 per 1M output tokens, with a 128K-token context window. > [!NOTE] > > The smaller `openai/gpt-oss-20b` was [removed from serverless inference](/docs/deprecations) on September 15, 2026, with `Qwen/Qwen3.5-9B` as its listed replacement. It remains available for [fine-tuning](/docs/fine-tuning/supported-models) and [dedicated endpoints](/docs/dedicated-endpoints/models). See [Recommended models](/docs/inference/recommended-models) for Together's current picks by use case. ## Call GPT-OSS 120B Reasoning is on by default. The thinking trace arrives on `reasoning` and the final answer arrives on `content`. The two share the same completion budget, so give `max_tokens` headroom and parse `content` only. ```python Python theme={null} from together import Together client = Together() completion = client.chat.completions.create( model="openai/gpt-oss-120b", messages=[ { "role": "user", "content": "If all roses are flowers and some flowers are red, can we conclude that some roses are red?", } ], temperature=1.0, top_p=1.0, max_tokens=8192, ) print(completion.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const completion = await together.chat.completions.create({ model: "openai/gpt-oss-120b", messages: [ { role: "user", content: "If all roses are flowers and some flowers are red, can we conclude that some roses are red?", }, ], temperature: 1.0, top_p: 1.0, max_tokens: 8192, }); console.log(completion.choices[0].message.content); ``` ```bash cURL theme={null} curl -X POST "https://api.together.ai/v1/chat/completions" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-oss-120b", "messages": [ {"role": "user", "content": "If all roses are flowers and some flowers are red, can we conclude that some roses are red?"} ], "temperature": 1.0, "top_p": 1.0, "max_tokens": 8192 }' ``` ## Set the reasoning effort `reasoning_effort` accepts `"low"`, `"medium"`, and `"high"`. The default is `"medium"`. * `"low"`: shallow reasoning. Use for short, high-volume calls. * `"medium"`: balanced depth, the default. Use for most work. * `"high"`: deep reasoning. Use for hard multi-step problems, and set `max_tokens` generously, since the trace can run to tens of thousands of tokens on hard prompts. Reasoning cannot be disabled entirely. Values outside this set are accepted silently instead of returning an error, so validate the value in your own code. ```python Python theme={null} from together import Together client = Together() completion = client.chat.completions.create( model="openai/gpt-oss-120b", messages=[ { "role": "user", "content": "Plan a migration from REST to gRPC for a payments service.", } ], reasoning_effort="high", max_tokens=32768, ) print(completion.choices[0].message.content) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const completion = await together.chat.completions.create({ model: "openai/gpt-oss-120b", messages: [ { role: "user", content: "Plan a migration from REST to gRPC for a payments service.", }, ], reasoning_effort: "high", max_tokens: 32768, }); console.log(completion.choices[0].message.content); ``` For broader guidance on reasoning controls and prompting, see [Reasoning](/docs/inference/chat/reasoning). ## Stream the reasoning trace and the answer Set `stream=True` to render the trace and the answer as they arrive. Handle both channels, and skip chunks where `choices` is empty, since Together emits a final usage-only chunk. ```python Python theme={null} from together import Together client = Together() stream = client.chat.completions.create( model="openai/gpt-oss-120b", messages=[{"role": "user", "content": "Explain why the sky is blue."}], max_tokens=8192, stream=True, ) in_answer = False for chunk in stream: if not chunk.choices: continue delta = chunk.choices[0].delta thinking = getattr(delta, "reasoning", None) if thinking: print(thinking, end="", flush=True) if delta.content: if not in_answer: print("\n--- answer ---") in_answer = True print(delta.content, end="", flush=True) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; import type { ChatCompletionChunk } from "together-ai/resources/chat/completions"; const together = new Together(); type ReasoningDelta = ChatCompletionChunk.Choice.Delta & { reasoning?: string; }; const stream = await together.chat.completions.create({ model: "openai/gpt-oss-120b", messages: [{ role: "user", content: "Explain why the sky is blue." }], max_tokens: 8192, stream: true, }); let inAnswer = false; for await (const chunk of stream) { if (!chunk.choices?.length) continue; const delta = chunk.choices[0]?.delta as ReasoningDelta; if (delta?.reasoning) process.stdout.write(delta.reasoning); if (delta?.content) { if (!inAnswer) { process.stdout.write("\n--- answer ---\n"); inAnswer = true; } process.stdout.write(delta.content); } } ``` ## Call tools Declare functions in `tools`. When the model returns `tool_calls`, append the assistant message to history, append one `tool` message per call with the matching `tool_call_id`, then call again. ```python Python theme={null} import json from together import Together client = Together() tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city.", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name, e.g. Paris", }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], }, }, "required": ["city"], "additionalProperties": False, }, }, } ] def get_weather(city, unit="celsius"): return { "city": city, "temperature": 21, "unit": unit, "conditions": "sunny", } messages = [{"role": "user", "content": "What's the weather in Paris?"}] for _ in range(5): response = client.chat.completions.create( model="openai/gpt-oss-120b", messages=messages, tools=tools, max_tokens=8192, ) choice = response.choices[0] message = choice.message messages.append(message.model_dump(exclude_none=True)) if choice.finish_reason != "tool_calls" or not message.tool_calls: print(message.content) break for call in message.tool_calls: try: args = json.loads(call.function.arguments) except json.JSONDecodeError: args = {} messages.append( { "role": "tool", "tool_call_id": call.id, "content": json.dumps(get_weather(**args)), } ) ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const tools = [ { type: "function" as const, function: { name: "get_weather", description: "Get the current weather for a city.", parameters: { type: "object", properties: { city: { type: "string", description: "City name, e.g. Paris" }, unit: { type: "string", enum: ["celsius", "fahrenheit"] }, }, required: ["city"], additionalProperties: false, }, }, }, ]; function getWeather(city: string, unit = "celsius") { return { city, temperature: 21, unit, conditions: "sunny" }; } const messages: any[] = [ { role: "user", content: "What's the weather in Paris?" }, ]; for (let i = 0; i < 5; i++) { const response = await together.chat.completions.create({ model: "openai/gpt-oss-120b", messages, tools, max_tokens: 8192, }); const choice = response.choices[0]; const message = choice.message; messages.push(message); if (choice.finish_reason !== "tool_calls" || !message.tool_calls?.length) { console.log(message.content); break; } for (const call of message.tool_calls) { let args: { city: string; unit?: string }; try { args = JSON.parse(call.function.arguments); } catch { args = { city: "" }; } messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(getWeather(args.city, args.unit)), }); } } ``` For the full pattern, including parallel calls and best practices, see [Function calling](/docs/inference/function-calling/overview). ## Constrain the output to a schema Pass a [JSON schema](/docs/inference/chat/structured-outputs) through `response_format` with `"strict": True` to constrain the final `content`. The whole thinking trace is spent before the first schema-constrained token is emitted, so keep `max_tokens` generous. Parse `content` only, never `reasoning`. ```python Python theme={null} import json from together import Together client = Together() completion = client.chat.completions.create( model="openai/gpt-oss-120b", max_tokens=4096, messages=[{"role": "user", "content": "Ada Lovelace was 36 years old."}], response_format={ "type": "json_schema", "json_schema": { "name": "person", "strict": True, "schema": { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, }, "required": ["name", "age"], "additionalProperties": False, }, }, }, ) person = json.loads(completion.choices[0].message.content) print(person) # -> {'name': 'Ada Lovelace', 'age': 36} ``` ```typescript TypeScript theme={null} import Together from "together-ai"; const together = new Together(); const completion = await together.chat.completions.create({ model: "openai/gpt-oss-120b", max_tokens: 4096, messages: [{ role: "user", content: "Ada Lovelace was 36 years old." }], response_format: { type: "json_schema", json_schema: { name: "person", strict: true, schema: { type: "object", properties: { name: { type: "string" }, age: { type: "integer" }, }, required: ["name", "age"], additionalProperties: false, }, }, }, }); const person = JSON.parse(completion.choices[0].message.content ?? "{}"); console.log(person); // -> { name: 'Ada Lovelace', age: 36 } ``` ## Usage tips | Tip | Rationale | | - | - | | **Give `max_tokens` real headroom** | The trace shares the completion budget with the answer. A tight cap spends the allowance on reasoning and returns an empty or truncated answer. | | **Parse `content` only** | Never run JSON parsing over the thinking trace on `reasoning`. | | **Match `reasoning_effort` to the task** | `"low"` for routine calls, `"high"` for hard problems. Reasoning tokens bill as output tokens. | | **Temperature = 1.0, top\_p = 1.0** | OpenAI's recommended defaults for the GPT-OSS family. | | **Think in goals, not steps** | Give high-level objectives and let the model determine the methodology. Micromanaging steps limits its reasoning. | ## Next steps > [card] [Reasoning](/docs/inference/chat/reasoning) > > Control reasoning depth and handle reasoning output across models. > [card] [Function calling](/docs/inference/function-calling/overview) > > Build tool-calling loops against any function-calling model. > [card] [Recommended models](/docs/inference/recommended-models) > > See Together's current picks for every use case. > [card] [Serverless models](/docs/serverless/models) > > Browse every model, context length, and price on serverless inference. # Automate cluster operations Source: https://docs.together.ai/docs/gpu-clusters-automation Create, scale, and delete GPU clusters from CI/CD pipelines, scripts, and cron jobs. Cluster lifecycle operations (create, scale, download credentials, delete) run headlessly, so a CI pipeline, script, or cron job can create a cluster, run work on it, and delete it without human interaction. The examples use the Together CLI, but the SDKs and [REST API](/reference/clusters-create) support the same workflows. Scripts and CI jobs can't log in with a browser, so authenticate with the `TOGETHER_API_KEY` environment variable instead of running `tg login`. Pass `--non-interactive` or `--json` on CLI commands so they never wait for a prompt. For CLI setup in a pipeline, see [Use the CLI in a CI/CD environment](/reference/cli/getting-started#use-the-cli-in-a-ci%2Fcd-environment). ## Create and delete clusters from CI Create an on-demand cluster for a pipeline run and delete it when the job finishes, so you pay only for the run itself. To set this up in GitHub Actions, store an API key as a secret named `TOGETHER_API_KEY`, and add your Kubernetes job manifest to the repository as `training-job.yaml`. The key must belong to a project admin. With a key from any other role, the API omits the kubeconfig, so `get-credentials` writes nothing and the `kubectl` command in the training step fails. Then add this workflow, which runs the training job on a new cluster for every push: ```yaml theme={null} name: Train Model on: push jobs: train: runs-on: ubuntu-latest timeout-minutes: 240 env: TOGETHER_API_KEY: ${{ secrets.TOGETHER_API_KEY }} steps: - uses: actions/checkout@v5 - uses: astral-sh/setup-uv@v7 - name: Install the Together CLI run: uv tool install "together[cli]" - name: Create GPU Cluster run: | CLUSTER_ID=$(tg clusters create \ --name training-${{ github.sha }} \ --num-gpus 8 \ --billing-type ON_DEMAND \ --gpu-type H100_SXM \ --region us-central-8 \ --nvidia-driver-version 570 \ --cuda-version 12.8 \ --cluster-type KUBERNETES \ --json | jq -r '.cluster_id') echo "CLUSTER_ID=$CLUSTER_ID" >> "$GITHUB_ENV" - name: Wait for the cluster and fetch credentials run: | until tg clusters retrieve "$CLUSTER_ID" --json | jq -e '.status == "Ready"' > /dev/null; do sleep 60 done tg clusters get-credentials "$CLUSTER_ID" --set-default-context - name: Run Training run: | # Submit training job to cluster kubectl apply -f training-job.yaml - name: Cleanup if: always() && env.CLUSTER_ID != '' run: | tg clusters delete "$CLUSTER_ID" --non-interactive ``` The create step writes the new cluster's ID to `$GITHUB_ENV` as `CLUSTER_ID`, so later steps can find the cluster. If the cluster never reaches `Ready`, the job's `timeout-minutes` limit ends the wait loop. The `Cleanup` step runs whenever the create step returned an ID, so the workflow deletes the cluster even when a later step fails. ## Create clusters on a schedule To create a cluster on a schedule, such as for daily batch work, save the `clusters create` command in a script: ```bash create-daily-batch.sh theme={null} #!/usr/bin/env bash set -euo pipefail export PATH="$HOME/.local/bin:$PATH" # cron doesn't load your shell profile tg clusters create \ --name daily-batch \ --num-gpus 16 \ --billing-type ON_DEMAND \ --gpu-type H100_SXM \ --region us-central-8 \ --nvidia-driver-version 570 \ --cuda-version 12.8 \ --cluster-type KUBERNETES \ --non-interactive ``` Because cron doesn't load your shell profile, set `TOGETHER_API_KEY` in the crontab or the script. Then add the script to your crontab: ```bash theme={null} # Create a cluster daily at 06:00 (server time) for batch processing 0 6 * * * /path/to/create-daily-batch.sh ``` The script only creates the cluster. [Delete the cluster](/docs/gpu-clusters-management#delete-a-cluster) when the batch finishes so it doesn't keep billing. ## Scale on your own signals To scale a cluster up or down on your own signals, such as job queue length, run `tg clusters update` with a new GPU count: ```bash theme={null} # Scale based on job queue length if [ "$JOB_QUEUE_LENGTH" -gt 100 ]; then tg clusters update --num-gpus 16 else tg clusters update --num-gpus 8 fi ``` To scale automatically when pods are pending, use [cluster autoscaling](/docs/gpu-clusters-management#autoscaling) instead. ## Best practices * **Use environment variables for API keys:** Store the key as a CI secret and expose it as `TOGETHER_API_KEY`. Never hardcode it in scripts or pipeline definitions. * **Reference clusters by ID:** IDs are generally more reliable than names in scripts. Capture the ID from the `--json` output of `tg clusters create`, as the CI workflow does. * **Check cluster status before submitting jobs:** After you create a cluster, wait until its status is `Ready`. * **Implement retry logic:** Handle transient failures with exponential backoff. * **Clean up resources:** Delete on-demand clusters when the job completes, including when it fails. ## Troubleshooting * **Commands fail with an authentication error:** The API key is missing or invalid. Check that it's set without printing it, for example with `test -n "$TOGETHER_API_KEY" && echo set`, and confirm that the key is valid in your [account settings](https://api.together.ai/settings/projects/~first/api-keys). To see which project and organization the CLI is using, run `tg whoami`. * **Commands use the wrong project or credentials on a machine where you ran `tg login`:** While you're logged in, the CLI uses your login instead of `TOGETHER_API_KEY`. To use the key, run `tg logout` or pass `--api-key`. * **Commands fail with rate-limit errors:** The script is calling the API too often. Retry with exponential backoff, and batch operations where possible. For higher limits, [contact support](https://portal.usepylon.com/together-ai/forms/support-request). ## Next steps > [card] [Manage GPU clusters](/docs/gpu-clusters-management) > > Run every cluster operation from the console, CLI, or SDKs. > [card] [Clusters CLI reference](/reference/cli/clusters) > > Look up every `tg clusters` command and flag. > [card] [Clusters API reference](/reference/clusters-create) > > Check request and response shapes for the clusters REST API. > [card] [SkyPilot](/docs/skypilot-on-gpu-clusters) > > Launch AI workloads on your cluster through SkyPilot task files. # Pricing Source: https://docs.together.ai/docs/gpu-clusters-billing GPU clusters bill compute per GPU hour by capacity type, and storage per GiB per month. GPU clusters bill compute and storage separately. Compute pricing depends on the [capacity type](/docs/gpu-clusters-overview#capacity-types) you choose (reserved, on-demand, or scheduled capacity), and preemptible nodes have their own discounted rate. Storage bills pay-as-you-go for as long as a volume exists. ## Rates All rates are in US dollars per GPU per hour. The duration columns show the reserved rate for each reservation length. | Hardware | Preemptible | On-demand | 3-30 days | 31-90 days | 91-180 days | 181+ days | | - | - | - | - | - | - | - | | NVIDIA HGX H100 | \$1.99 | \$3.99 | \$3.69 | \$3.45 | \$3.19 | [Contact sales](https://www.together.ai/contact-sales) | | NVIDIA HGX H200 | \$2.99 | \$5.99 | \$4.99 | \$4.15 | \$3.99 | [Contact sales](https://www.together.ai/contact-sales) | | NVIDIA HGX B200 | \$4.09 | \$8.19 | \$7.99 | \$7.79 | \$6.79 | [Contact sales](https://www.together.ai/contact-sales) | | NVIDIA HGX B300 | \$4.99 | \$9.99 | [Contact sales](https://www.together.ai/contact-sales) | [Contact sales](https://www.together.ai/contact-sales) | [Contact sales](https://www.together.ai/contact-sales) | [Contact sales](https://www.together.ai/contact-sales) | The [GPU clusters pricing table](https://www.together.ai/pricing#gpu-clusters) lists all GPU cluster hardware, including additional types available through sales. ## Compute billing * **Reserved:** Credits for the full reserved duration are charged upfront or deducted once the cluster is provisioned. Reserved rates are lower than on-demand rates for every reservation length. Usage beyond your reserved capacity is billed at on-demand rates. * **On-demand:** You pay only for the time your cluster runs, with no upfront commitment. * **Scheduled capacity:** Credits cover the full date window you select from your project's capacity pool. The console shows an estimated total for the window before you create the cluster. * **Preemptible (Preview):** [Preemptible nodes](/docs/preemptible-compute), which you can add to Kubernetes and Slurm clusters alongside standard capacity, bill at a flat rate discounted from on-demand. Usage is metered every one to two minutes, so you pay only for the time a node is live. When you set a preemptible GPU target, the console shows the preemptible hourly rate and an estimated cost. To create a cluster, you need enough credits to cover the full reservation, a minimum period of on-demand usage, four hours of the preemptible target, and storage for the same periods. Otherwise, the create request fails with a `403` error: `Insufficient credits for cluster creation`. > [!NOTE] > > The regions API and `tg clusters list-regions` return region availability, supported instance types, and driver versions, but not pricing. For current on-demand and reserved rates, see the [GPU clusters pricing table](https://www.together.ai/pricing#gpu-clusters). ## Storage billing Storage is billed pay-as-you-go per GiB per month, based on each volume's provisioned size. You can [increase a volume's size](/docs/gpu-clusters-management#resize-storage) yourself, and the added capacity bills at the same rate. Decreasing a volume's size requires contacting your account team, so start with a small volume and grow it as your data grows. Storage bills independently of the cluster lifecycle, so a volume keeps accruing charges even when no cluster is using it. Delete unused volumes to stop their charges. ## Lifecycle policies Clusters and storage volumes follow different lifecycle policies: * **Reserved clusters:** A reserved cluster is decommissioned automatically when its reservation period ends. The cluster owner and project admins get email reminders seven days, three days, one day, and four hours before the reservation ends. To extend a reservation, open the cluster details page in the [console](https://api.together.ai/clusters) and select **Extend Reservation**, or contact your account team. * **On-demand clusters:** An on-demand cluster has no end date. It runs until you delete it or your [credits run out](#running-out-of-credits). * **Scheduled capacity clusters:** A scheduled capacity cluster is provisioned on the start date and decommissioned on the end date you select within the capacity pool window. If the pool window includes today, you can check **Start now** in the console to provision it immediately. If the pool has no end date, you can select **No end** instead, and the cluster runs until you delete it. * **Storage volumes:** Volumes persist independently of clusters and remain available as long as your billing account is in good standing. Deleting a cluster doesn't delete its volumes unless you choose to delete them with it. Your data persists as long as you use the static persistent volume Together provides. ## Running out of credits When your credits run out, each type of resource behaves differently: * **Reserved compute:** Existing reservations stay active until their scheduled end date. On-demand capacity added to scale beyond the reservation is paused right away. If you don't restore credits within the grace period (one hour by default), Together removes that capacity. * **On-demand compute:** Together revokes access and pauses the cluster right away. If you don't restore credits within the grace period, Together deletes the cluster. * **Preemptible compute:** On reserved and scheduled capacity clusters, requests to raise the preemptible target fail with a `402` as soon as credits run out. When the grace period ends, Together sets the target to 0. Restoring credits lifts the `402`, but the target stays at 0 until you raise it again. On an on-demand cluster, preemptible nodes are paused and deleted with the rest of the cluster. * **Storage volumes:** Together revokes access right away. If you don't restore credits within 72 hours, Together deletes the data. When Together revokes access, it emails you the time left before deletion. ## View usage and invoices View your current usage, credits, and invoices in [Settings > Billing](https://api.together.ai/settings/organization/~current/billing). Each invoice has separate line items for reserved compute (upfront reservation charges), on-demand compute (hourly burst capacity usage), and storage (shared volume usage per GiB). Each line item shows the exact timeframe it covers. ## FAQ ### Can I get a refund for unused reservation time? No. Reservations are non-refundable. The full reservation period is charged upfront and can't be canceled or partially refunded. ### Are there data ingress or egress fees? No. Together AI doesn't charge for data transfer into or out of your cluster, so you can move datasets, checkpoints, and results freely. You pay only for compute and storage. ### Can I pause a cluster to save costs? No. You can't pause a reserved or on-demand cluster. A reserved cluster is charged upfront for the full reservation period. To stop compute charges on an on-demand cluster, delete it and recreate it later. Together pauses a cluster only when your [credits run out](#running-out-of-credits). ### When does my reservation start? The reservation period starts when you create the cluster, not when it reaches **Ready**. The end date is the creation time plus the reservation length, so provisioning time counts toward the reservation. ## Support For billing questions, review your invoice in [Settings > Billing](https://api.together.ai/settings/organization/~current/billing) or [submit a support request](https://portal.usepylon.com/together-ai/forms/support-request). For reservation extensions, contact your account team. # Concepts Source: https://docs.together.ai/docs/gpu-clusters-concepts Understand how nodes, Kubernetes, Slurm, storage, and preemptible compute fit together on a Together GPU cluster. Every GPU cluster is built from the same stack: GPU nodes (virtual machines on bare-metal hosts), a Kubernetes layer that schedules work onto them, and, on Slurm clusters, a Slurm layer on top. This page explains each layer, where your data lives, and how preemptible compute works. The [glossary](#glossary) defines the terms used throughout the clusters docs. ## Architecture ![Diagram of a Together GPU cluster. The user reaches the Kubernetes control plane with kubectl, or Slurm on Kubernetes with ssh, sbatch, and srun. The control plane schedules pods on nodes, and Slurm schedules jobs on nodes. Both target the same GPU worker nodes, called compute nodes in Slurm, each with 8 GPUs and local NVMe, running pods and jobs side by side and connected by InfiniBand. A persistent shared volume that survives reboots is mounted on every node.](https://mintcdn.com/togetherai-52386018/3eXILkcCSB2Gej8O/images/gpu-clusters-architecture.png?fit=max\&auto=format\&n=3eXILkcCSB2Gej8O\&q=85\&s=54944a2600d8a0cb7e9a73265319508a) * **Hardware:** GPU worker nodes connected by InfiniBand, each with a local NVMe disk, plus a persistent shared volume mounted on all of them. This is the layer you rent. * **Kubernetes:** Every cluster runs Kubernetes, including Slurm clusters. A control plane managed by Together tracks cluster state and schedules pods onto the worker nodes. You reach it with `kubectl` after [downloading credentials](/docs/gpu-clusters-quickstart#step-2-connect-to-the-cluster). * **Slurm (optional):** On Slurm clusters, the Slurm stack runs on top of Kubernetes. You SSH into a login node and submit jobs, and the Slurm scheduler places them on the same GPU nodes. Standard tooling works out of the box at every layer: `kubectl` and the Kubernetes ecosystem, Slurm's batch commands, and orchestration tools like [SkyPilot](/docs/skypilot-on-gpu-clusters), [Volcano](/docs/volcano-on-gpu-clusters), and [Kueue](/docs/kueue-on-gpu-clusters). Together monitors every node with [passive health checks](/docs/health-checks#passive-health-checks) and repairs unhealthy nodes through [automated repair recommendations](/docs/node-repair). You can also run [active health checks](/docs/health-checks#active-health-checks) on demand. ## Kubernetes Kubernetes is a container orchestration system that schedules containerized workloads across a cluster of machines. Together manages the control plane, and you get full `kubectl` access to schedule work onto the GPU worker nodes. For general Kubernetes usage, see the [Kubernetes documentation](https://kubernetes.io/docs/home/). Kubernetes is declarative. You describe what you want to run, and Kubernetes finds nodes with the resources to run it, starts it, and restarts it if it fails. These Kubernetes terms come up throughout the clusters docs: * **Container:** Your workload packaged with its dependencies into an image, so it runs the same way on any node. * **Pod:** The smallest unit of work Kubernetes schedules onto a node, made up of one or more containers. * **Manifest:** A YAML file describing what you want to run. You apply it with `kubectl apply`, and Kubernetes makes the cluster match it. * **Jobs and deployments:** The two most common workload types. A job runs pods to completion, for example to train a model. A deployment keeps pods running, for example to serve inference. To deploy pods with persistent storage, see [Run workloads on Kubernetes](/docs/kubernetes-workloads). ## Slurm Slurm is a cluster management system that schedules jobs across a cluster of computers. On a Slurm cluster, Slurm comes preconfigured for distributed training. You submit jobs from the login node, and the scheduler assigns them to GPU nodes based on resource availability. For general Slurm usage, see the [Slurm quick start user guide](https://slurm.schedmd.com/quickstart.html). Choose a Slurm cluster when your team works with high-performance computing (HPC) batch workflows, such as `sbatch` scripts, job arrays, and partitions. Choose a Kubernetes cluster when your workloads are containerized and you want to work with `kubectl` and the Kubernetes ecosystem directly. You select the cluster type when you [create the cluster](/docs/gpu-clusters-quickstart). Both types run on the same hardware, storage, and networking. Together runs Slurm on top of Kubernetes through Slinky. A Slurm cluster has the same layers underneath as a Kubernetes cluster, and Slurm adds its own vocabulary: * **Login node:** The machine you SSH into to write, submit, and monitor jobs. You submit work from it rather than running work on it directly. The console labels it the head node, and the two terms are interchangeable. * **Compute node:** Slurm's name for a GPU worker node. Each one is registered with both Kubernetes and Slurm. * **Job:** Slurm's unit of work, submitted with `sbatch` (batch) or `srun` (interactive). A job plays the same role on a Slurm cluster that a pod plays on a Kubernetes cluster. * **Partition:** A named group of compute nodes that jobs are submitted to. To change partitions, see [Slurm configuration](/docs/slurm-configuration). The Slurm controller itself runs as pods on the cluster, but you never manage those pods directly. You interact with Slurm entirely through its own commands. For common usage patterns and troubleshooting, see [Submit Slurm jobs](/docs/slurm). ## Storage Every cluster has these storage locations: * **Shared volume:** A persistent, remote-attached filesystem mounted on every node. It survives reboots, node repairs, and, by default, cluster deletion. Store datasets, checkpoints, model weights, and anything else you can't lose on it. * **Local NVMe:** A fast ephemeral disk on each node. Data on it can be lost during reboots, repairs, or rescheduling. Use it only for scratch files you can regenerate. * **`/home`:** Persistence depends on the cluster type. On Slurm clusters, `/home` lives on the shared volume and persists. On Kubernetes clusters, it's local to each node and ephemeral. For mount paths, upload instructions, and best practices, see [Cluster storage](/docs/cluster-storage). ## Preemptible compute You can request two kinds of compute on a cluster: * **Standard:** The default. Standard nodes are provisioned up front when you create or scale a cluster, and they stay in the cluster until you scale down or delete it. Together never preempts them. * **Preemptible:** Discounted nodes built from Together's spare GPU capacity. Because that capacity is spare, Together can reclaim, or *preempt*, a preemptible node whenever the capacity is needed elsewhere. You don't provision preemptible nodes directly. Instead, you set a target GPU count, and Together adds nodes toward that target as spare capacity becomes available. The target is not guaranteed. When a node is preempted, Together drains it for up to five minutes so running work can checkpoint and exit. After the node is removed, Together provisions replacements toward your target automatically. In exchange for this uncertainty, preemptible usage is billed at a discounted rate, and only for the time a node is live. For the full preemption contract, scheduling guidance, and checkpoint examples, see [Preemptible compute](/docs/preemptible-compute). ## Glossary | Term | What it means | | - | - | | Cluster | Everything you create: nodes, networking, storage, and the control plane. | | Node | One GPU virtual machine (VM) in the cluster, running on a bare-metal host. | | Control plane | The managed Kubernetes components that track cluster state and schedule pods. | | Worker node | A GPU node that runs your workloads. | | Compute node | Slurm's name for a GPU worker node. | | Login node | The machine you SSH into on a Slurm cluster to submit jobs. The console labels it the head node. | | Pod | The smallest unit of work Kubernetes schedules onto a node. | | Job (Kubernetes) | A workload that runs pods to completion, such as a training run. | | Job (Slurm) | The unit of work you submit to Slurm with `sbatch` or `srun`. | | Partition | A named group of compute nodes that jobs run in. | | Shared volume | Persistent storage mounted on every node. It survives reboots and, by default, cluster deletion. | | Local NVMe | A fast ephemeral disk on each node. Data on it can be lost during reboots or repairs. | | InfiniBand | High-bandwidth, low-latency networking that connects the nodes for multi-node training. | | Reserved capacity | GPUs reserved for a fixed period and paid for upfront at discounted rates. | | On-demand capacity | GPUs billed per hour of cluster runtime with no commitment. | | Capacity pool | Pre-arranged capacity attached to a project. Scheduled capacity clusters draw GPUs from it for a fixed window. | | Standard node | A node provisioned up front when you create or scale a cluster. Together never preempts it. | | Preemptible node | A discounted node that Together can reclaim at any time with a five-minute drain window. [Preemptible compute](/docs/preemptible-compute) is in preview on both Kubernetes and Slurm clusters. | ## Next steps > [card] [Quickstart](/docs/gpu-clusters-quickstart) > > Create a cluster, connect to it, and run your first job. > [card] [Run workloads on Kubernetes](/docs/kubernetes-workloads) > > Deploy pods with persistent storage and run GPU workloads. > [card] [Submit Slurm jobs](/docs/slurm) > > Submit and manage batch jobs with the preconfigured Slurm scheduler. > [card] [Cluster storage](/docs/cluster-storage) > > Choose the right storage tier for datasets and checkpoints. # Manage GPU clusters Source: https://docs.together.ai/docs/gpu-clusters-management Create, schedule, inspect, scale, and delete GPU clusters, and manage their storage and access, from the console, CLI, or SDKs. This page covers the administration tasks for GPU clusters, from checking region availability and creating a cluster to scaling, storage, access, and deletion. Most tasks have steps for three surfaces: * **Console:** The GPU clusters page in the [Together AI console](https://api.together.ai/clusters). * **Together CLI:** `tg clusters` commands. See the [clusters CLI reference](/reference/cli/clusters). * **SDKs and REST API:** `client.clusters` methods in the Python and TypeScript SDKs, or the HTTP API for custom integrations. See the [GPU clusters API reference](/reference/clusters-create). To run these operations from pipelines, cron jobs, and scripts, see [Automate cluster operations](/docs/gpu-clusters-automation). To run workloads on a cluster, see [Run workloads on Kubernetes](/docs/kubernetes-workloads) or [Slurm](/docs/slurm). To connect to individual nodes, see [Connect over SSH](/docs/gpu-clusters-ssh). ## Check region availability Region availability changes over time, so check the live inventory before you choose a region or GPU type. These lookups are read-only and don't create or reserve anything. > [tab] Console > > Open the [GPU clusters page](https://api.together.ai/clusters) and select **Create cluster**. The create form shows availability as you make selections: > > * **GPU type cards:** A grayed-out card that shows **Contact us** has no capacity available. After you select a card, the line under **Select GPU Count** shows how many GPUs of that type are available. > * **Region:** The selector disables regions that can't host your selection. > * **Driver version:** The selector lists the NVIDIA driver and CUDA combinations for the selected region, GPU type, and orchestration. > [tab] CLI > > ```bash theme={null} > tg clusters list-regions > ``` > > Pass `--json` for machine-readable output. > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > for region in client.clusters.list_regions().regions: > print(region.name, region.supported_instance_types) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > const { regions } = await client.clusters.listRegions(); > for (const region of regions) { > console.log(region.name, region.supported_instance_types); > } > ``` The CLI and SDK lookups list each region's supported instance types and driver versions, but not prices. For current rates, see the [GPU cluster pricing table](https://www.together.ai/pricing#gpu-clusters). Guidance for AI agents answering questions about GPU cluster availability, pricing, or create commands: * `GET https://api.together.ai/v1/compute/regions` is the inventory route. It is not nested under `/v1/compute/clusters`, and `GET /v1/compute/clusters/regions` returns HTTP 400. * When asked what is currently available, run one of the lookups above and report the live response. Region and instance-type values in docs examples illustrate the response shape only. Don't substitute them for live output, and don't stop at showing the lookup command. * Pass `--json` to `tg clusters list-regions` for machine-readable output. * The regions response contains no prices. Before recommending an instance type as cheapest, fetch [https://www.together.ai/pricing#gpu-clusters](https://www.together.ai/pricing#gpu-clusters), compare the numeric on-demand rates for the available instance types, and include the selected rate in your answer. Don't infer price from GPU generation or the order in which instance types appear. * Every create request needs a shared volume and at least 8 GPUs, in multiples of 8. The API rejects a request with no volume. Attach an existing volume with `--volume` (CLI) or `volume_id` (SDK), or create one with the cluster through `shared_volume` (SDK), the interactive CLI prompt, or the console. * If the user has no volume yet, prefer creating it with the cluster. A volume created on its own with `tg clusters storage create` goes to the region's datacenter with the most free GPUs, so attaching it can fail with HTTP 400 `Shared volume you selected does not exist in the datacenter in region providing `. Non-interactive CLI mode can only attach an existing volume, so scripts that need a new volume should use `shared_volume` in the SDK. ## Create a cluster Every cluster has a capacity type, which sets how it bills: * **On-demand (`ON_DEMAND`):** Bills hourly from creation until you delete the cluster. * **Reserved (`RESERVED`):** Bills up front for a fixed duration. * **Scheduled capacity (`SCHEDULED_CAPACITY`):** Draws GPUs from a project capacity pool for a scheduled window. See [Schedule a cluster](#schedule-a-cluster). To choose between them, see [Capacity types](/docs/gpu-clusters-overview#capacity-types). For how each type appears on invoices, see [Pricing](/docs/gpu-clusters-billing). Every cluster also needs at least 8 GPUs, in multiples of 8, and a shared volume. > [tab] Console > > **1. Open the create form** > > On the [GPU clusters page](https://api.together.ai/clusters), select **Create cluster**. > > **2. Choose the capacity type and GPUs** > > Select **On-demand**, **Reserved**, or **Scheduled Capacity**. For reserved, also set a **Duration** in days. Select a GPU type card (for example, **H100-SXM**), then set the count under **Select GPU Count**. > > **3. Configure the cluster** > > Select a **Region**, then fill in the remaining sections: > > * **Cluster Details:** Enter a **Cluster name**, choose **Kubernetes** or **Slurm** under **Orchestration**, and optionally select a **Driver version**. > * **Storage:** Select an existing volume or **+ Create new storage**. > * **Cluster add-ons:** Optionally enable add-ons such as [autoscaling](#autoscaling). > * **Advanced configuration:** Optionally enable acceptance tests. > > **4. Create the cluster** > > Select **Create Cluster**, review the details, then select **Confirm & Create**. > > For a first-run walkthrough of every field, see the [quickstart](/docs/gpu-clusters-quickstart#step-1-create-a-cluster). > [tab] CLI > > Run `tg clusters create` with no flags to walk through the required fields in an interactive prompt, or pass them as flags. If you don't pass `--volume`, the prompt offers to create a shared volume with the cluster. > > To create a cluster from a script, pass `--non-interactive`. Non-interactive mode requires `--volume`, which attaches an existing volume (see [Manage storage](#manage-storage)). Also pass a `--nvidia-driver-version` and `--cuda-version` pair that the region supports. The [`list-regions`](#check-region-availability) output shows the valid pairs for each region: > > ```bash theme={null} > tg clusters create \ > --name my-cluster \ > --cluster-type KUBERNETES \ > --gpu-type H100_SXM \ > --num-gpus 8 \ > --region us-central-8 \ > --nvidia-driver-version 570 \ > --cuda-version 12.8 \ > --billing-type ON_DEMAND \ > --volume \ > --non-interactive > ``` > > For reserved billing, pass `--billing-type RESERVED --duration-days `. To request [preemptible capacity](/docs/preemptible-compute) alongside standard nodes, pass `--num-preemptible-gpus`. For all flags, see the [CLI reference](/reference/cli/clusters#create-a-cluster). > [tab] SDK > > The SDK create call requires these parameters: > > * **Cluster settings:** `cluster_name`, `cluster_type`, `num_gpus`, `gpu_type`, `region`, and `billing_type`. > * **NVIDIA driver:** Either `nvidia_version_id`, or `nvidia_driver_version` together with `cuda_version`. Use a combination that the region lists in [`list-regions`](#check-region-availability). > * **Shared volume:** Pass `volume_id` to attach an existing volume, or `shared_volume` to create one with the cluster. To use a new volume, create it with `shared_volume` rather than on its own, so it lands in a datacenter that has your GPU type. > > ```python Python theme={null} > from together import Together > > client = Together() > > cluster = client.clusters.create( > cluster_name="my-cluster", > cluster_type="KUBERNETES", > gpu_type="H100_SXM", > num_gpus=8, > region="us-central-8", > nvidia_driver_version="570", > cuda_version="12.8", > billing_type="ON_DEMAND", > volume_id="", > ) > print(cluster.cluster_id) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > const cluster = await client.clusters.create({ > cluster_name: "my-cluster", > cluster_type: "KUBERNETES", > gpu_type: "H100_SXM", > num_gpus: 8, > region: "us-central-8", > nvidia_driver_version: "570", > cuda_version: "12.8", > billing_type: "ON_DEMAND", > volume_id: "", > }); > console.log(cluster.cluster_id); > ``` Provisioning usually takes 10 minutes to an hour, depending on cluster size and region. Wait for the cluster to reach **Ready** status before you submit work. To poll for status, see [Inspect clusters](#inspect-clusters). ## Schedule a cluster Scheduled capacity clusters draw GPUs from a project [capacity pool](/docs/gpu-clusters-overview#capacity-types) for a fixed window that you set in advance. With the CLI, SDK, or API, set `num_capacity_pool_gpus` to the number of GPUs to draw from the pool. If you omit it, every GPU is booked as a prepaid reserved GPU outside the pool. To start the cluster now, omit the start time. > [tab] Console > > **1. Choose scheduled capacity** > > In the [create cluster form](https://api.together.ai/clusters), select **Scheduled Capacity**, which appears when your project has a capacity pool. Then select a pool under **Capacity Pool**. The pool sets the GPU type and region. > > **2. Pick the window** > > Under **Scheduled Capacity Dates**, select start and end dates within the capacity pool window. To provision immediately, check **Start now** and select an end date. **Start now** is available only when the selected capacity pool window includes today's date. > > **3. Size and create the cluster** > > Set the GPU count under **Select Capacity Pool GPU Count**, up to the pool's free capacity. Fill in the remaining fields, then select **Create Cluster** and **Confirm & Create**. The cost estimate covers the full selected window. > [tab] CLI > > ```bash theme={null} > tg clusters create \ > --name scheduled-batch \ > --billing-type SCHEDULED_CAPACITY \ > --capacity-pool-id \ > --reservation-start-time 2026-12-01T00:00:00Z \ > --reservation-end-time 2026-12-08T00:00:00Z \ > --num-gpus 8 \ > --num-capacity-pool-gpus 8 \ > --gpu-type H100_SXM \ > --region us-central-8 \ > --nvidia-driver-version 570 \ > --cuda-version 12.8 \ > --cluster-type KUBERNETES \ > --volume \ > --non-interactive > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.create( > cluster_name="scheduled-batch", > billing_type="SCHEDULED_CAPACITY", > capacity_pool_id="", > reservation_start_time="2026-12-01T00:00:00Z", > reservation_end_time="2026-12-08T00:00:00Z", > num_gpus=8, > num_capacity_pool_gpus=8, > gpu_type="H100_SXM", > region="us-central-8", > nvidia_driver_version="570", > cuda_version="12.8", > cluster_type="KUBERNETES", > volume_id="", > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.create({ > cluster_name: "scheduled-batch", > billing_type: "SCHEDULED_CAPACITY", > capacity_pool_id: "", > reservation_start_time: "2026-12-01T00:00:00Z", > reservation_end_time: "2026-12-08T00:00:00Z", > num_gpus: 8, > num_capacity_pool_gpus: 8, > gpu_type: "H100_SXM", > region: "us-central-8", > nvidia_driver_version: "570", > cuda_version: "12.8", > cluster_type: "KUBERNETES", > volume_id: "", > }); > ``` ### Create a hybrid scheduled capacity cluster A *hybrid scheduled capacity cluster* combines GPUs from your capacity pool with prepaid reserved GPUs outside the pool. With the CLI, SDK, or API, use `SCHEDULED_CAPACITY` billing and set `num_gpus` to the cluster's total GPU count. Split it across `num_capacity_pool_gpus` and `num_reserved_gpus`. Both counts must be multiples of 8, and together they can't exceed `num_gpus`. If you leave out `num_reserved_gpus`, the rest of `num_gpus` is reserved. A hybrid cluster starts now, so leave out the start time. > [tab] Console > > In the create form with **Scheduled Capacity** selected, check **Start now**, then set the pool GPU count under **Select Capacity Pool GPU Count**. To add prepaid reserved GPUs from outside the pool, turn on **Add compute outside your capacity pool**, which appears only when the cluster starts now, then set **Reserved GPUs**. > [tab] CLI > > ```bash theme={null} > tg clusters create \ > --name hybrid-scheduled \ > --billing-type SCHEDULED_CAPACITY \ > --capacity-pool-id \ > --reservation-end-time 2026-12-08T00:00:00Z \ > --num-gpus 16 \ > --num-capacity-pool-gpus 8 \ > --num-reserved-gpus 8 \ > --gpu-type H100_SXM \ > --region us-central-8 \ > --nvidia-driver-version 570 \ > --cuda-version 12.8 \ > --cluster-type KUBERNETES \ > --volume \ > --non-interactive > ``` > > See the [clusters CLI reference](/reference/cli/clusters#create-a-cluster) for the full flag list. > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.create( > cluster_name="hybrid-scheduled", > billing_type="SCHEDULED_CAPACITY", > capacity_pool_id="", > reservation_end_time="2026-12-08T00:00:00Z", > num_gpus=16, > num_capacity_pool_gpus=8, > num_reserved_gpus=8, > gpu_type="H100_SXM", > region="us-central-8", > nvidia_driver_version="570", > cuda_version="12.8", > cluster_type="KUBERNETES", > volume_id="", > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.create({ > cluster_name: "hybrid-scheduled", > billing_type: "SCHEDULED_CAPACITY", > capacity_pool_id: "", > reservation_end_time: "2026-12-08T00:00:00Z", > num_gpus: 16, > num_capacity_pool_gpus: 8, > num_reserved_gpus: 8, > gpu_type: "H100_SXM", > region: "us-central-8", > nvidia_driver_version: "570", > cuda_version: "12.8", > cluster_type: "KUBERNETES", > volume_id: "", > }); > ``` ### Extend a reservation To keep a reserved cluster running past its decommission time, set a later reservation end time. The console also shows **Extend Reservation** on scheduled capacity clusters, but the request returns a `403` unless Together has enabled extensions for your account. > [tab] Console > > Open the cluster on the [GPU clusters page](https://api.together.ai/clusters), select **Extend Reservation**, choose the new end date under **Extend Duration**, then select **Review** and **Purchase**. The review step shows the hourly rate and the estimated total cost of the extension. > [tab] CLI > > ```bash theme={null} > tg clusters update \ > --reservation-end-time 2027-01-15T15:00:00Z > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.update( > "", > reservation_end_time="2027-01-15T15:00:00Z", > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.update("", { > reservation_end_time: "2027-01-15T15:00:00Z", > }); > ``` ## Inspect clusters List your clusters and retrieve one cluster's full state, including its status, node counts, and configuration. > [tab] Console > > The [GPU clusters page](https://api.together.ai/clusters) lists every cluster with its type, creator, provisioning and reservation end times, node counts, region, and status. Select a cluster to open its detail page, where the sidebar shows its resources, region, reservation dates, GPU breakdown, driver version, and add-on configuration. > [tab] CLI > > ```bash theme={null} > tg clusters list > tg clusters retrieve > ``` > > Pass `--json` to either command for machine-readable output, for example to poll for `"status": "Ready"` in scripts. > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > for cluster in client.clusters.list().clusters: > print(cluster.cluster_id, cluster.cluster_name) > > cluster = client.clusters.retrieve("") > print(cluster.status) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > const { clusters } = await client.clusters.list(); > for (const cluster of clusters) { > console.log(cluster.cluster_id, cluster.cluster_name); > } > > const cluster = await client.clusters.retrieve(""); > console.log(cluster.status); > ``` ### Inspect cluster GPU counts When you retrieve a cluster, `num_gpus` is its standard (non-preemptible) GPU count. It splits into billed components: * `num_reserved_gpus`: Prepaid reserved GPUs on the cluster. * `num_capacity_pool_gpus`: GPUs drawn from the cluster's capacity pool. Any GPUs beyond those two components are billed on demand, for example after you scale up a reserved or scheduled capacity cluster. How the counts relate depends on the cluster: * **Cluster without a capacity pool:** `num_capacity_pool_gpus` is `0`. * **Fully reserved cluster:** `num_reserved_gpus` equals `num_gpus`. * **Fully on-demand cluster:** `num_reserved_gpus` is `0`. * **Hybrid scheduled capacity cluster:** `num_gpus` equals `num_capacity_pool_gpus` plus `num_reserved_gpus`. [Preemptible GPUs](/docs/preemptible-compute) aren't part of `num_gpus`. The cluster reports them separately, in `desired_preemptible_gpus` and `allocated_preemptible_gpus`. > [tab] Console > > On a cluster with a capacity pool, the cluster detail sidebar lists **Capacity Pool GPUs**, plus **Reserved GPUs** and **On-Demand GPUs** when they're above zero. > [tab] CLI > > ```bash theme={null} > tg clusters retrieve --json > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > cluster = client.clusters.retrieve("") > print( > cluster.num_gpus, > cluster.num_reserved_gpus, > cluster.num_capacity_pool_gpus, > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > const cluster = await client.clusters.retrieve(""); > console.log( > cluster.num_gpus, > cluster.num_reserved_gpus, > cluster.num_capacity_pool_gpus, > ); > ``` ## Scale a cluster Scale a cluster up in real time with on-demand compute when workload demand spikes, then back down as demand decreases. You can also set a [preemptible GPU target](/docs/preemptible-compute) that Together fills as spare capacity becomes available. To scale, set the cluster's new total GPU count, which can't be lower than its reserved GPU count: > [tab] Console > > Open the cluster on the [GPU clusters page](https://api.together.ai/clusters) and select **Scale**. Choose the new GPU count, select **Review**, then **Purchase**, and enter the cluster name to confirm. The GPU size picker lists every full-node multiple of 8 GPUs, up to the capacity currently available for your GPU type and region, rather than a fixed upper limit. > [tab] CLI > > ```bash theme={null} > tg clusters update --num-gpus 16 > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.update( > "", > num_gpus=16, > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.update("", { > num_gpus: 16, > }); > ``` ### Update cluster GPU counts To change how a cluster's GPUs are split across [billed components](#inspect-cluster-gpu-counts) without changing `num_gpus`, update the individual component counts: * `num_reserved_gpus`: Increases the prepaid reserved GPU count on a reserved or scheduled capacity cluster. The value must be a multiple of 8 and can't exceed `num_gpus`. You can't decrease it. To reduce a reservation, contact your account team. * `num_capacity_pool_gpus`: Changes the number of GPUs drawn from the cluster's capacity pool. It applies only to clusters created with a capacity pool. The value must be a multiple of 8, and its sum with `num_reserved_gpus` can't exceed `num_gpus`. > [tab] Console > > In the **Scale** dialog, reserved and scheduled capacity clusters show a **Reserved GPUs** selector next to **On-Demand GPUs**, and clusters created with a capacity pool also show **Capacity Pool GPUs**. The dialog sets `num_gpus` to their sum. > [tab] CLI > > ```bash theme={null} > tg clusters update --num-reserved-gpus 16 > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.update( > "", > num_reserved_gpus=16, > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.update("", { > num_reserved_gpus: 16, > }); > ``` For how reserved and on-demand usage appear on invoices, see [Pricing](/docs/gpu-clusters-billing). ### Autoscaling Cluster autoscaling adjusts the node count to match workload demand. It uses the Kubernetes Cluster Autoscaler, which: * Scales up when pods are pending due to insufficient resources. * Scales down by safely draining and removing nodes that stay underutilized for an extended period. * Keeps the GPU count between the cluster's `num_gpus` and `auto_scale_max_gpus`. You can't turn autoscaling on or off after a cluster is created. On an autoscaled cluster, the autoscaler owns the GPU count, and any update through `tg clusters update` or `clusters.update` returns `403` "cluster update is not allowed when auto scale is enabled". To enable autoscaling, turn it on when you create the cluster and set the maximum GPU count it can scale to, a multiple of 8 that's at least `num_gpus`: > [tab] Console > > When you create a Kubernetes cluster in the [create cluster form](https://api.together.ai/clusters), set **Enable Autoscaling** to **Yes** under **Cluster add-ons**, then set **Max GPUs**. > [tab] CLI > > ```bash theme={null} > tg clusters create \ > --name autoscaled-cluster \ > --cluster-type KUBERNETES \ > --gpu-type H100_SXM \ > --num-gpus 8 \ > --region us-central-8 \ > --nvidia-driver-version 570 \ > --cuda-version 12.8 \ > --billing-type ON_DEMAND \ > --volume \ > --auto-scale \ > --auto-scale-max-gpus 32 > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.create( > cluster_name="autoscaled-cluster", > cluster_type="KUBERNETES", > gpu_type="H100_SXM", > num_gpus=8, > region="us-central-8", > nvidia_driver_version="570", > cuda_version="12.8", > billing_type="ON_DEMAND", > volume_id="", > auto_scale=True, > auto_scale_max_gpus=32, > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.create({ > cluster_name: "autoscaled-cluster", > cluster_type: "KUBERNETES", > gpu_type: "H100_SXM", > num_gpus: 8, > region: "us-central-8", > nvidia_driver_version: "570", > cuda_version: "12.8", > billing_type: "ON_DEMAND", > volume_id: "", > auto_scale: true, > auto_scale_max_gpus: 32, > }); > ``` > [!NOTE] > > Autoscaling works with both reserved and on-demand capacity. Scaling beyond reserved capacity provisions on-demand nodes, billed at standard hourly rates. ### Targeted scale-down To choose which nodes a scale-down removes, mark them for deletion before you scale down. Scale-down removes annotated and cordoned nodes before any others. **1. Mark the node for deletion** Mark the node with one of these methods: * **Annotate (Kubernetes or Slurm, preferred):** Annotating leaves the node schedulable for existing workloads until scale-down runs. On a Slurm cluster, run the command with the [admin kubeconfig](#download-cluster-kubeconfig), using a node name from `kubectl get nodes`. ```bash theme={null} kubectl annotate node node.together.ai/delete-node-on-scale-down=true ``` * **Cordon (Kubernetes):** Cordon the node if you also want to stop new pods from being scheduled onto it immediately. ```bash theme={null} kubectl cordon ``` * **Drain (Slurm):** Drain the node with `scontrol`. ```bash theme={null} sudo scontrol update NodeName= State=drain Reason="" ``` **2. Wait for the mark to register** In the **Nodes** tab of the [console](https://api.together.ai/clusters), wait until **Marked for deletion** appears next to the node. This confirms that Together has picked up the mark. Scaling down before it appears can cause a race condition that leaves the drain unfinished. **3. Trigger scale-down** Reduce the cluster's total GPU count by one node's worth of GPUs, with any of the methods in [Scale a cluster](#scale-a-cluster). The marked node is removed first. ```bash theme={null} tg clusters update --num-gpus ``` > [!TIP] > > Scale down one node at a time, repeating these steps for each node you want to remove. This gives Together time to drain each node cleanly, and lets you stop if something goes wrong. ## Delete a cluster On-demand clusters bill hourly until you delete them. Shared volumes persist after you delete the cluster, and keep billing, unless you [delete them](#delete-a-volume) too. > [tab] Console > > Open the cluster on the [GPU clusters page](https://api.together.ai/clusters), select **Delete**, then enter the cluster name to confirm. To also remove the attached shared volume, check **Delete attached shared volume** in the same dialog. > [tab] CLI > > ```bash theme={null} > tg clusters delete > ``` > > In an interactive session, the command asks you to confirm before deleting. Pass `--force` to delete without confirming. The global `--non-interactive` and `--json` flags also suppress the prompt, so scripted and CI deletes never wait for input. > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.delete("") > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.delete(""); > ``` ## Manage storage All clusters include persistent shared volumes, fast ephemeral NVMe disks local to each node, and a `/home` directory whose persistence depends on the cluster type. For the full breakdown and best practices, see [Cluster storage](/docs/cluster-storage). Attach a volume when you create a cluster, through the **Storage** section of the create form in the console, the `--volume` flag in the CLI, or the `volume_id` parameter in the SDK. You can't swap the volume on an existing cluster. You can attach a volume that outlives its cluster to a new cluster in the same region, as long as no other cluster uses it. ### Create a volume A volume you create on its own is always independent of a cluster's lifecycle, so it persists, and keeps billing, after the cluster it's attached to is deleted or decommissioned, unless you [delete it along with the cluster](#delete-a-cluster). Delete it separately when you no longer need it. Volume names can contain only lowercase letters, digits, hyphens, and dots. > [tab] Console > > On the [GPU clusters page](https://api.together.ai/clusters), select the **Shared Filesystem** tab, then **Create Volume**. Select a **Region**, enter a **Volume Name** (up to 44 characters) and **Size (TiB)**, then select **Create Volume**. You can also create a volume with a cluster, from the **Storage** section of the create cluster form. > [tab] CLI > > ```bash theme={null} > tg clusters storage create \ > --volume-name my-training-data \ > --size-tib 1 \ > --region us-central-8 > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > volume = client.clusters.storage.create( > volume_name="my-training-data", > size_tib=1, > region="us-central-8", > ) > print(volume.volume_id) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > const volume = await client.clusters.storage.create({ > volume_name: "my-training-data", > size_tib: 1, > region: "us-central-8", > }); > console.log(volume.volume_id); > ``` > > To assign the volume to a specific [project](/docs/projects), pass `project_id` in the SDK or API. If you omit it, the volume goes to your default project. ### List volumes > [tab] Console > > The **Shared Filesystem** tab on the [GPU clusters page](https://api.together.ai/clusters) lists every volume with its size, owner, region, and the clusters currently using it. > [tab] CLI > > ```bash theme={null} > tg clusters storage list > tg clusters storage retrieve > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > for volume in client.clusters.storage.list().volumes: > print(volume.volume_id, volume.volume_name, volume.size_tib) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > const { volumes } = await client.clusters.storage.list(); > for (const volume of volumes) { > console.log(volume.volume_id, volume.volume_name, volume.size_tib); > } > ``` ### Upload data Both upload methods go through a pod that mounts your shared volume. To create the PersistentVolumeClaim (PVC) and mount the volume in a pod, see [Deploy pods with storage](/docs/kubernetes-workloads#deploy-pods-with-storage). For small datasets, copy files into the pod with `kubectl cp`: ```bash theme={null} # Copy a local file into a pod that mounts the shared volume kubectl cp LOCAL_FILENAME POD_NAME:/mnt/shared/ ``` For large datasets, schedule a pod on the cluster that downloads directly from S3 or your data source. This example mounts the volume through a PVC named `shared-pvc`. For a private bucket, give the container AWS credentials, for example from a Kubernetes Secret. For a public bucket, add `--no-sign-request` to the `aws s3 cp` command instead: ```yaml data-loader.yaml theme={null} apiVersion: v1 kind: Pod metadata: name: data-loader spec: restartPolicy: OnFailure containers: - name: downloader image: amazon/aws-cli command: ["aws", "s3", "cp", "s3://bucket/data", "/mnt/shared/", "--recursive"] volumeMounts: - name: shared-storage mountPath: /mnt/shared volumes: - name: shared-storage persistentVolumeClaim: claimName: shared-pvc ``` ### Resize storage Increase a shared volume's size as your data grows. The added capacity bills at the same rate as the rest of the volume. To decrease a volume's size, contact your account team. > [tab] Console > > **1. Open the storage list** > > On the [GPU clusters page](https://api.together.ai/clusters), select the **Shared Filesystem** tab. > > **2. Edit the volume** > > Open the actions menu on the volume you want to resize and select **Update Volume**. > > **3. Set the new size** > > Enter the new size in TiB, then select **Update Volume**. > [tab] CLI > > Find the volume ID, then set the new total size in TiB: > > ```bash theme={null} > tg clusters storage list > tg clusters storage update --size-tib 4 > ``` > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.storage.update( > volume_id="", > size_tib=4, > ) > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.storage.update({ > volume_id: "", > size_tib: 4, > }); > ``` Self-serve resizing isn't enabled on every account. If the console dialog says the feature isn't available, or the CLI or API returns a `403`, contact your account team. ### Delete a volume Before you delete a volume, delete the cluster that uses it. > [!WARNING] > > Deleting a volume permanently destroys its data. > [tab] Console > > On the **Shared Filesystem** tab, open the actions menu on the volume and select **Delete Volume**, then enter the volume name to confirm. The action is disabled while a cluster still uses the volume. > [tab] CLI > > ```bash theme={null} > tg clusters storage delete > ``` > > In an interactive session, the command asks you to confirm before deleting. Pass `--force` to delete without confirming. > [tab] SDK > > ```python Python theme={null} > from together import Together > > client = Together() > > client.clusters.storage.delete("") > ``` > > ```typescript TypeScript theme={null} > import Together from "together-ai"; > > const client = new Together(); > > await client.clusters.storage.delete(""); > ``` ## Manage cluster access Cluster access follows Together's [project-based permission system](/docs/projects). Anyone with access to a project can access all clusters and volumes in it. Projects have two [roles](/docs/roles-permissions): * **admin:** Can create and delete clusters, modify configurations, manage users, and use clusters. * **editor:** Can use clusters (SSH, kubectl, Slurm) but can't create, delete, or modify infrastructure. ### Download cluster kubeconfig Both Kubernetes and Slurm clusters expose an admin kubeconfig with cluster-admin access to the cluster's Kubernetes API through `kubectl`. Only project admins can get it, from the console, the [Together CLI](/reference/cli/clusters), or the API. > [tab] Console > > 1. Open your cluster on the [GPU clusters page](https://api.together.ai/clusters). The kubeconfig appears once the cluster is ready, and is hidden while the cluster is paused. > 2. Find the **Kubeconfig** row in the cluster sidebar. When OpenID Connect (OIDC) is enabled, the row is labeled **Admin Kubeconfig**, and a separate **OIDC Kubeconfig** row appears. > 3. Select **View** to copy the contents, or **Download** to save it as a file. > [tab] CLI > > ```bash theme={null} > tg clusters get-credentials --set-default-context > ``` > > Find your cluster ID with `tg clusters list`. If you aren't a project admin, the command prints "No kubeconfig found for cluster at this time." To give editors `kubectl` access, enable [OIDC](/docs/cluster-oidc) on the cluster and have a project admin share the OIDC kubeconfig with them. The file contains no credentials. Editors can't download it themselves, because the console builds it from the admin kubeconfig. Keep the admin kubeconfig for administrative tasks such as role-based access control (RBAC) setup. ### Add users to a cluster project To give someone access to a cluster, add them as a collaborator on the cluster's project. They must already belong to your [organization](/docs/organizations). Open [**Settings > Project > Collaborators**](https://api.together.ai/settings/projects/~current/collaborators) for the project that contains your cluster, then select **Add collaborator**. New collaborators get the editor role by default, except organization admins, who are admins on every project. To add external collaborators or remove collaborators, see [Managing project collaborators](/docs/projects#managing-project-collaborators). Removing a collaborator revokes their access to all clusters and volumes in the project, including SSH access, within minutes. ## Monitor cluster health Together monitors every node with [passive health checks](/docs/health-checks#passive-health-checks) and raises [repair recommendations](/docs/node-repair) for unhealthy ones. You can also run [active health checks](/docs/health-checks#active-health-checks) on demand. > [tab] Console > > Open your cluster on the [GPU clusters page](https://api.together.ai/clusters) to view its status (for example, **Running tests**, **Ready**, or **Degraded**). The detail page splits monitoring across these tabs: > > * **Overview:** Node health, GPU utilization, GPU memory, and network bandwidth metrics. > * **Nodes:** Per-node state, hardware details, and a copyable SSH command. > * **Control plane** or **System nodes:** The cluster's control plane or system nodes, depending on the cluster's architecture. > * **Health checks:** Run active health checks and review results. > * **Repairs:** Pending and past [node repairs](/docs/node-repair). > > For detailed metrics, select **Open Grafana** under **Access** in the sidebar. This requires the **Observability** add-on. See [Monitor workloads with Grafana](/docs/kubernetes-workloads#monitor-workloads-with-grafana). > [tab] Kubernetes > > ```bash theme={null} > kubectl get nodes # Node status > kubectl top nodes # Resource usage > kubectl get pods --all-namespaces # All running workloads > ``` > [tab] Slurm > > ```bash theme={null} > sinfo # Node and partition status > squeue # Job queue > scontrol show node # Detailed node info > ``` ## Request capacity If the [console](https://api.together.ai/clusters) doesn't show available capacity for the GPU type or configuration you need, request it from the create cluster view: 1. Select **Need a different configuration?** to open the **Notify when available** dialog. 2. Set the capacity you need: * **GPU type** and **Requested GPUs**. * **Region**, or leave **Any region**. * **Storage size (TiB)** (optional). * **Requested start date** for on-demand capacity, or **Requested dates** (start and end) for reserved or scheduled capacity. 3. Review the **Estimated compute cost**, then select **Submit request**. Together uses these requests for demand planning, and reaches out if the capacity becomes available. > [!NOTE] > > Due to high demand, submitting a request doesn't guarantee fulfillment. If you need guaranteed GPU capacity for a fixed period, [reach out to the sales team](https://www.together.ai/contact-sales). ## Best practices * **Storage:** Use shared volumes for training data, checkpoints, model weights, and application state. On Kubernetes, mount them in pods through a PVC. Local NVMe and node-local `/home` (on Kubernetes) are ephemeral and can be wiped during migrations, recreations, or maintenance, so never rely on them for data you can't afford to lose. Use local NVMe only for temporary scratch files that you can regenerate. See [Cluster storage](/docs/cluster-storage). * **Large datasets:** Download them directly on the cluster rather than through your local machine. See [Upload data](#upload-data). * **Job scheduling:** Use Kubernetes Jobs for batch processing and Slurm job arrays for embarrassingly parallel workloads. Set resource requests and limits in pod specs, and set appropriate timeouts and retry policies. * **Scaling strategy:** Start with reserved capacity for your baseline workload, add on-demand capacity for burst periods, and use [targeted scale-down](#targeted-scale-down) to control costs. ## Troubleshooting * **Create or scale fails with `409` "Out of stock":** The region doesn't have room for the GPU type and count you requested. Create returns "Out of stock - insufficient capacity", and scale returns "GPU out of stock". Try another region that offers your GPU type, request fewer GPUs, or [request capacity](#request-capacity). [`list-regions`](#check-region-availability) shows which regions offer each GPU type, but not how much capacity they have. * **Scale fails with `403` "less than the reservation state":** You requested fewer GPUs than the cluster has reserved. To reduce a reservation, contact your account team. * **Scale-up or volume resize fails with `402`:** Your account balance is too low. Add credits, then retry. See [Running out of credits](/docs/gpu-clusters-billing#running-out-of-credits). * **Volume create or resize fails with `409` "Out of stock - no storage available":** The region has no room for the volume. * **Slurm jobs aren't running:** Check node status with `sinfo`, verify the partition is available, and check job status with `scontrol show job `. * **Workload issues on Kubernetes:** For pod scheduling, storage mount, and GPU access problems, see [Run workloads on Kubernetes](/docs/kubernetes-workloads#troubleshooting). ## Next steps > [card] [Run workloads on Kubernetes](/docs/kubernetes-workloads) > > Deploy pods with persistent storage and run GPU workloads. > [card] [Connect over SSH](/docs/gpu-clusters-ssh) > > Reach login, worker, and compute nodes with OIDC or key-based SSH. > [card] [Health checks](/docs/health-checks) > > Monitor node health with active tests and continuous passive checks. > [card] [Automate cluster operations](/docs/gpu-clusters-automation) > > Drive cluster operations from CI/CD pipelines, scripts, and cron jobs. # GPU clusters Source: https://docs.together.ai/docs/gpu-clusters-overview Provision dedicated multi-node GPU clusters for Kubernetes or Slurm workloads. > [!TIP] > > Using a coding agent? Install the [together-ai](https://github.com/togethercomputer/skills/tree/main/skills/together-ai) skill to let your agent write correct GPU cluster code automatically. See [agent skills](/docs/agent-skills) for details. Together GPU clusters provide dedicated multi-node GPU infrastructure for training, fine-tuning, and other large-scale AI workloads. Clusters provision in minutes and include high-speed InfiniBand networking and persistent shared storage. You can scale a cluster up or down in real time. Besides hardware, you make two decisions when you create a cluster: * **[Kubernetes or Slurm](#choosing-kubernetes-or-slurm):** Every cluster runs on Kubernetes. Work with `kubectl` and standard Kubernetes tooling directly, or create a Slurm cluster to run high-performance computing (HPC) batch workflows with `sbatch` and `srun`. * **[Capacity type](#capacity-types):** Reserve capacity upfront for 3 to 180 days at discounted rates, pay hourly for on-demand capacity with no commitment, or draw from a project capacity pool for a scheduled window. You can mix reserved and on-demand capacity in the same cluster. ## Get started You can create a cluster from the [Together AI console](https://api.together.ai/clusters) or with the Together CLI: ```bash theme={null} # create a cluster (an interactive prompt walks through the options) tg clusters create # check the status until the cluster is ready tg clusters get # write a kubeconfig for kubectl access and switch to its context tg clusters get-credentials --set-default-context ``` The [GPU clusters quickstart](/docs/gpu-clusters-quickstart) breaks down this flow, including how to access a Slurm cluster. > [card] [Quickstart](/docs/gpu-clusters-quickstart) > > Create a cluster, connect to it, and run your first job. > [card] [Kubernetes workloads](/docs/kubernetes-workloads) > > Deploy pods with persistent storage and run GPU workloads. > [card] [Slurm workloads](/docs/slurm) > > Run HPC-style batch jobs with the preconfigured Slurm scheduler. > [card] [Manage clusters](/docs/gpu-clusters-management) > > Scale capacity, control access, and monitor cluster health. > [card] [Cluster storage](/docs/cluster-storage) > > Choose the right storage tier for datasets and checkpoints. > [card] [Pricing](/docs/gpu-clusters-billing) > > Understand how compute and storage charges work. ## How clusters work Every cluster is built from the same layers: * **Hardware:** GPU worker nodes connected by high-speed InfiniBand, each with fast local NVMe storage, plus a persistent shared volume mounted on every node. * **Kubernetes:** A control plane managed by Together tracks cluster state and schedules workloads onto the worker nodes. You reach it with `kubectl` and standard Kubernetes tooling. * **Slurm (optional):** On Slurm clusters, the Slurm scheduler runs on top of the same Kubernetes stack through Slinky, an integration layer that bridges HPC scheduling with cloud-native infrastructure. You SSH into a login node and submit jobs with `sbatch` and `srun`. Together monitors every node with [automated health checks and repairs](/docs/health-checks). For a walkthrough of each layer and definitions of common HPC terms, see [Concepts](/docs/gpu-clusters-concepts). ### Choosing Kubernetes or Slurm You select the cluster type when you [create the cluster](/docs/gpu-clusters-quickstart). Both types run on the same hardware, storage, and networking. * **Choose a Kubernetes cluster** if your workloads are containerized and you want to work with `kubectl` and the Kubernetes ecosystem directly. You can use schedulers like [Kueue](/docs/kueue-on-gpu-clusters) and [Volcano](/docs/volcano-on-gpu-clusters), or orchestrators like [SkyPilot](/docs/skypilot-on-gpu-clusters). See [Kubernetes workloads](/docs/kubernetes-workloads). * **Choose a Slurm cluster** if your team works with HPC-style batch workflows, such as `sbatch` scripts, job arrays, partitions, and a shared job queue with priorities. Slurm comes preconfigured for distributed training, so you can submit jobs without writing any Kubernetes manifests. See [Slurm workloads](/docs/slurm). ## Available hardware | GPU | Memory per GPU | Best for | | - | - | - | | NVIDIA HGX B200 | 180 GB | Maximum performance on the latest generation. | | NVIDIA HGX H200 | 141 GB | Large models that need more GPU memory than H100. | | NVIDIA HGX H100 SXM | 80 GB | High-bandwidth training and inference. | Nodes of every GPU type connect over 3.2 Tb/s InfiniBand for multi-node training. If the GPUs you need aren't available, [request capacity](/docs/gpu-clusters-management#request-capacity) from the [console](https://api.together.ai/clusters). For custom requirements, contact your account team. ## Capacity types | | Reserved | On-demand | Scheduled capacity | | - | - | - | - | | **Billing** | Credits are charged upfront for the full reservation at discounted rates. | Billed per hour of cluster runtime at standard rates. | Credits cover the full window you select from a project capacity pool. | | **Commitment** | 3 to 180 days. | None. | The start and end dates you select within the pool window, or **No end** if the pool has no end date. | | **Lifecycle** | Decommissioned automatically when the reservation expires. Extend the reservation from the cluster details page in the [console](https://api.together.ai/clusters). | Runs until you delete it. | Runs until the end date you select, or until you delete it if you selected **No end**. | ### Choosing a capacity type * **Choose reserved** if you know how long your workload will run, such as a multi-day training run or a planned experiment, and you can commit to that period in exchange for discounted rates. * **Choose on-demand** if your resource needs are unpredictable, you're running short experiments, or you're still developing and testing and want maximum flexibility. * **Mix reserved and on-demand** if you have a predictable baseline with occasional bursts. For example, reserve capacity for your baseline workload, then scale up with on-demand capacity during peak periods and back down when the burst ends. Usage beyond your reserved capacity is automatically billed at on-demand rates. * **Choose scheduled capacity** if your project has a capacity pool and your workload fits a planned window. The create form shows this option only when your project has a pool. For a cluster that starts now, you can combine capacity pool GPUs with prepaid reserved GPUs from outside the pool. You can also add [preemptible compute](/docs/preemptible-compute) (Preview) alongside standard nodes on Kubernetes and Slurm clusters. Preemptible GPUs are discounted and billed sub-hourly, but Together can reclaim them at any time. > [!NOTE] > > Shared storage volumes have their own lifecycle. When a reserved cluster is decommissioned at expiration, its volumes persist and keep billing as storage. You can attach them to other clusters, or delete them after you extract the data. For rates and invoice details, see [Pricing](/docs/gpu-clusters-billing). ## Storage Every cluster has three storage locations: * **Shared volumes:** Persistent. High-throughput file systems that survive pod restarts, node reboots, and, by default, cluster deletion. * **Local NVMe:** Ephemeral. Fast local disks on each node. Data can be lost during reboots, migrations, or cluster operations. * **`/home` directory:** Persistent on Slurm clusters, where it lives on the shared volume. Ephemeral on Kubernetes clusters, where it's local to each node. > [!WARNING] > > Local NVMe and node-local storage are ephemeral. Always use shared volumes for data you need to keep. You can resize volumes as your data grows. For mount paths, upload instructions, and best practices, see [Cluster storage](/docs/cluster-storage). # GPU clusters quickstart Source: https://docs.together.ai/docs/gpu-clusters-quickstart Create a GPU cluster, connect to it, and run your first job on a GPU. > [!TIP] > > Using a coding agent? Install the [together-ai](https://github.com/togethercomputer/skills/tree/main/skills/together-ai) skill to let your agent write correct GPU cluster code automatically. See [agent skills](/docs/agent-skills) for details. A GPU cluster is a set of GPU nodes dedicated to you, where you run workloads with Kubernetes or Slurm. Use one when you need full control over your training or inference stack, such as for multi-node training or for custom code that doesn't fit a managed service like fine-tuning or dedicated model inference. In this quickstart, you'll create a GPU cluster, connect to it with `kubectl` or SSH, run a test job that confirms its GPUs are ready, and delete the cluster when you're done. ## Requirements Before you begin, make sure you have: * A [Together AI account](https://api.together.ai) with sufficient credits. * The [Together CLI](/reference/cli/getting-started) installed. To install or upgrade it, run: ```bash theme={null} uv tool install "together[cli]" --upgrade ``` * [kubectl](https://kubernetes.io/docs/tasks/tools/) installed, if you plan to create a Kubernetes cluster. * An SSH key added at [api.together.ai/settings/ssh-key](https://api.together.ai/settings/ssh-key) before you create the cluster, if you plan to use key-based SSH on a Slurm cluster. ## Step 1: Create a cluster > [tab] Console > > **1. Open the create form** > > Go to the GPU clusters page in the [Together AI console](https://api.together.ai/clusters) and select **Create cluster**. > > **2. Choose the capacity type** > > Select **On-demand** to pay hourly with no commitment. To pay a fixed rate for 3 to 180 days instead, select **Reserved**. > > **3. Choose GPUs** > > Select a GPU type card (for example, **H100-SXM**), then set the number of GPUs under **Select GPU Count**. GPUs come in whole nodes of 8. For a reserved cluster, also set **Duration** below the GPU count. > > **4. Choose a region** > > Leave **Region** at its default, **Any region**, to target the region with the most available capacity for your selected GPU type. If you need the cluster in a particular location, select that region instead. > > **5. Configure the cluster** > > Under **Cluster Details**, enter a descriptive **Cluster name**. > > Under **Orchestration**, select **Kubernetes** for containerized workloads or **Slurm** for high-performance computing (HPC) batch scheduling. > > Leave **Driver version** at its default unless you need a specific NVIDIA driver and CUDA combination. > > **6. Create a shared volume** > > Under **Storage**, open **Storage Selection** and select **+ Create new storage**, then set **Size (TiB)** and a **Storage Name**. The minimum size is 1 TiB, and you can resize the volume later. To reuse a volume you already have, select it instead. > > > [!NOTE] > > > > Changing the GPU type resets the region to **Any region** and deselects any existing volume you chose, because volumes are region-specific. Select them again after you switch GPU types. > > **7. Create the cluster** > > Select **Create Cluster**, review the details, then select **Confirm & Create**. The console shows the cluster's status as it provisions. Wait for the status to reach **Ready**, which usually takes 10 minutes to an hour, depending on cluster size and region. > [tab] CLI > > List the regions to find one that supports your GPU type. The output also shows each region's NVIDIA driver and CUDA versions, which you need when you create the cluster: > > ```bash theme={null} > tg clusters list-regions > ``` > > Create a shared storage volume in that region, and note the volume ID in the output. This example uses `us-central-8`: > > ```bash theme={null} > tg clusters storage create \ > --volume-name my-training-data \ > --size-tib 1 \ > --region us-central-8 > ``` > > Create the cluster in the same region with the volume attached. With `--non-interactive`, you must choose an NVIDIA driver, so copy a driver version's `id` from the `list-regions` output and pass it as `--nvidia-version-id`: > > ```bash theme={null} > tg clusters create \ > --name my-cluster \ > --cluster-type KUBERNETES \ > --gpu-type H100_SXM \ > --num-gpus 8 \ > --region us-central-8 \ > --nvidia-version-id \ > --billing-type ON_DEMAND \ > --volume \ > --non-interactive > ``` > > To be prompted for each required field instead, run `tg clusters create` with no flags. For all flags, including reserved billing with `--billing-type RESERVED --duration-days`, see the [CLI reference](/reference/cli/clusters#create-a-cluster). > > > [!NOTE] > > > > A volume you create on its own goes to the region's datacenter with the most free GPUs, which might not host your GPU type. If it doesn't, cluster creation fails with `Shared volume you selected does not exist in the datacenter in region providing `. To fix this, create the volume with the cluster instead: > > > > 1. Run `tg clusters create` without `--volume` and `--non-interactive`, and answer `y` to "Create a new storage volume?". You can also create the cluster in the console. > > 2. Delete the unused volume with `tg clusters storage delete `. > > To check provisioning progress, list your clusters. The output shows each cluster's ID and status: > > ```bash theme={null} > tg clusters list > ``` > > Wait for the status to reach `Ready`. Provisioning usually takes 10 minutes to an hour, depending on cluster size and region. > [!NOTE] > > If the GPU type you want has no available capacity, try a different region, or [request capacity](/docs/gpu-clusters-management#request-capacity) by selecting **Need a different configuration?** in the [console](https://api.together.ai/clusters) create form. ## Step 2: Connect to the cluster How you connect depends on the cluster type you chose in Step 1: > [tab] Kubernetes > > Find your cluster ID, then download the cluster's credentials. [`get-credentials`](/reference/cli/clusters#get-cluster-credentials) merges them into your local `~/.kube/config` (pass `--file` to write them elsewhere), and `--set-default-context` points `kubectl` at the new cluster: > > ```bash theme={null} > tg clusters list > tg clusters get-credentials --set-default-context > ``` > > Only project admins can download credentials. For anyone else, `get-credentials` reports that no kubeconfig was found. Editors connect with an [OpenID Connect (OIDC) kubeconfig](/docs/cluster-oidc) that an admin shares instead. > > When the CLI detects an AI agent, it defaults to JSON output. In JSON mode, `get-credentials` reports the target path without writing the file, so pass `--no-json` to write it. > > Confirm that `kubectl` can reach the cluster: > > ```bash theme={null} > kubectl get nodes > ``` > > You should see the cluster's nodes listed with status `Ready`. Nodes appear as they finish provisioning, so if any are missing, wait for the cluster status to reach **Ready** in the [console](https://api.together.ai/clusters). > > You can also [view or download the kubeconfig](/docs/gpu-clusters-management#download-cluster-kubeconfig) from the cluster details page in the console. > [tab] Slurm > > Open the cluster's details page in the [console](https://api.together.ai/clusters). If your cluster supports OpenID Connect (OIDC) SSH, the page shows an **SSH access method** selector. Choose **OIDC** or **Key-based**: > > * **OIDC:** Connects through the Together CLI with a short-lived certificate. Choose a login name when prompted. No SSH key is required. > * **Key-based:** Uses the SSH key you added before you created the cluster. > > Select **Copy head node SSH command** in the cluster sidebar. The copied command matches your selected access method and fills in ``, the [datacenter part of the node hostnames](/docs/gpu-clusters-ssh): > > ```bash theme={null} > # OIDC > tg clusters ssh https://dex..cloud.together.ai/t- --login > > # Key-based > ssh -J @ssh.t-..cloud.together.ai @slurm-login > ``` > > The console copies the OIDC command as `tg beta clusters ssh`. Together CLI 3.0 removed the `beta` path, so delete `beta` from the copied command. > > Run the command in your terminal. It opens a shell on the cluster's [login node](/docs/gpu-clusters-concepts#slurm), where you run Slurm commands. > > Verify that Slurm sees your nodes: > > ```bash theme={null} > sinfo # View node and partition status > squeue # View the job queue > ``` > > Slurm clusters run on Kubernetes. If you also need `kubectl` access to the underlying cluster API, a project admin can [download the kubeconfig](/docs/gpu-clusters-management#download-cluster-kubeconfig) from the cluster details page or with `tg clusters get-credentials`. SSH to the login node is still the primary way to submit jobs. ## Step 3: Run a test job To confirm the cluster is ready for work, run a job that prints a node's GPU status. > [tab] Kubernetes > > Save this pod definition to a file named `gpu-test.yaml` on your local machine, in the directory you run `kubectl` from. A *pod* is the unit of work Kubernetes schedules onto a node. This pod requests one GPU and runs `nvidia-smi`: > > ```yaml gpu-test.yaml theme={null} > apiVersion: v1 > kind: Pod > metadata: > name: gpu-test > spec: > restartPolicy: Never > containers: > - name: gpu-test > image: nvidia/cuda:12.4.1-base-ubuntu22.04 > command: ["nvidia-smi"] > resources: > limits: > nvidia.com/gpu: 1 > ``` > > Create the pod, wait for it to finish, then print its output: > > ```bash theme={null} > kubectl apply -f gpu-test.yaml > kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/gpu-test --timeout=180s > kubectl logs gpu-test > ``` > [tab] Slurm > > In the login node shell you opened in Step 2, start an interactive session. The `srun` command tells Slurm to allocate one GPU on a compute node and opens a shell there. Run `nvidia-smi` in that shell to confirm the GPU is ready: > > ```bash theme={null} > srun --gpus=1 --pty bash > nvidia-smi > ``` You should see the `nvidia-smi` table listing the allocated GPU, its driver version, and memory. > [!TIP] > > Congrats! You created a GPU cluster and ran your first job on it. ## Clean up to stop billing On-demand clusters bill hourly until you delete them. When you're done, delete the cluster: ```bash theme={null} tg clusters delete ``` Your shared storage volume persists after cluster deletion and continues to bill until you delete it. Keep it to reuse your data on a future cluster, or delete it: ```bash theme={null} tg clusters storage delete ``` ## Next steps > [card] [Run workloads on Kubernetes](/docs/kubernetes-workloads) > > Deploy pods with persistent storage and run GPU workloads. > [card] [Submit Slurm jobs](/docs/slurm) > > Run and manage batch jobs with the preconfigured Slurm scheduler. > [card] [Cluster storage](/docs/cluster-storage) > > Choose the right storage tier for datasets and checkpoints. > [card] [Billing and pricing](/docs/gpu-clusters-billing) > > Understand how compute and storage charges work. # Connect over SSH Source: https://docs.together.ai/docs/gpu-clusters-ssh Reach your cluster's login, worker, and compute nodes with OIDC or key-based SSH. You can use SSH to connect to individual cluster nodes—for example, the Slurm login node for job submission, and worker or compute nodes for debugging and monitoring. You connect with key-based SSH or, on clusters that support OpenID Connect (OIDC) SSH, through the Together CLI, which needs no SSH key. ## Choose an SSH access method on Slurm clusters On Slurm clusters that support OIDC SSH, choose how you connect in the **SSH access method** selector. It's in the sidebar of the cluster details page in the [Together AI console](https://api.together.ai/clusters), or at the top of the page on mobile. Your choice applies to the Slurm head node and all compute nodes. If the cluster doesn't support OIDC SSH, the selector is hidden and only key-based SSH is available. | Method | What it does | Requirements | | - | - | - | | **OIDC** | Copies a Together CLI command that opens your browser to sign in, then connects with a short-lived certificate. | [Together CLI](/reference/cli/getting-started) installed, login name chosen in the [console](https://api.together.ai/clusters). | | **Key-based** | Copies a standard `ssh -J` command for your SSH client. | Uploaded SSH key at [api.together.ai/settings/ssh-key](https://api.together.ai/settings/ssh-key). | OIDC SSH requires Together CLI 2.40+ and [Python 3.10+](https://www.python.org/). Install the CLI with uv: ```bash theme={null} uv tool install "together[cli]" ``` The console shows the same command when you select **OIDC** and expand **Set up CLI** next to the head node command. If you installed the CLI with `pip`, follow the [migration steps](/reference/cli/getting-started#install-the-together-cli) to move to the `uv`-managed install before you connect. ## SSH to worker and compute nodes To SSH into any GPU worker node on a Kubernetes cluster, or any compute node on a Slurm cluster, copy the node's command from the console: 1. Open your cluster on the [GPU clusters page](https://api.together.ai/clusters). 2. On Slurm clusters that support OIDC SSH, select **OIDC** or **Key-based** in **SSH access method**. 3. Select the **Nodes** tab. 4. Open the **⋮** menu at the end of the node's row and select **Copy SSH command**. 5. Run the copied command in your terminal. The copied command depends on your access method. On a Kubernetes cluster that supports OIDC SSH, it always uses OIDC. A key-based command connects through the cluster's jump host: ```bash theme={null} ssh -J @ssh.t-..cloud.together.ai @ ``` An OIDC command connects through the Together CLI: ```bash theme={null} tg clusters ssh https://dex..cloud.together.ai/t- --login --host ``` **Copy SSH command** fills in every value for you. `` is the **Login name** in your [SSH key settings](https://api.together.ai/settings/ssh-key), and you can set it only once. `` is the datacenter part of the cluster's node hostnames, such as `s2.ca-west-1b`, not the region name. Use direct node access to: * Check GPU utilization across all GPUs on the node with `nvidia-smi`. * Monitor node-level performance metrics (CPU, memory, disk, network). * Inspect system logs (`journalctl`, `/var/log`). * Debug node-level networking or storage issues. * Check kubelet status and logs on Kubernetes worker nodes. * View all processes running on the node. What you can do on the node depends on the cluster type: | Capability | Kubernetes worker node | Slurm compute node | | - | - | - | | Run GPU workloads | Not available (no direct GPU device access). | Available. | | Access PersistentVolumes | Not available (mounted in pods only). | Available through the `/home` directory. | | Best for | Node-level monitoring and debugging. | Node-level monitoring, debugging, and direct Slurm workflows. | To run GPU workloads or use PersistentVolumes on a Kubernetes cluster, [exec into a pod with GPU and storage access](/docs/kubernetes-workloads#run-gpu-workloads-in-containers). ## SSH to Slurm login nodes To submit jobs on a [Slurm cluster](/docs/slurm), SSH into its login node, which the console calls the head node. Select **Copy head node SSH command** in the sidebar of the cluster details page, then run the copied command in your terminal. > [!NOTE] > > The login node runs as a pod on the cluster's GPU nodes. While the cluster has no GPU nodes, the console disables SSH access and shows "SSH is disabled when 0 GPUs are available." SSH access returns when GPU nodes rejoin the cluster. With key-based SSH, the command connects to `slurm-login` through the jump host: ```bash theme={null} ssh -J @ssh.t-..cloud.together.ai @slurm-login ``` With OIDC, it runs the Together CLI's [`tg clusters ssh`](/reference/cli/clusters#ssh-into-a-cluster) command: ```bash theme={null} tg clusters ssh https://dex..cloud.together.ai/t- --login ``` Slurm nodes use these hostnames: * **Login node:** The host is always `slurm-login`. * **Compute nodes:** The host is `.slurm-compute.slurm`, for example `gpu-dp-hmqnh-nwlnj.slurm-compute.slurm`. On Slinky v1.0 clusters, it's `.slurm-workers-slurm.slurm`. The node's **Copy SSH command** always uses the exact host. Once you're connected, submit and monitor jobs with standard Slurm commands. For the command set, memory-limit guidance, and job arrays, see [Slurm](/docs/slurm). ## Connect from VS Code To use VS Code with your Slurm cluster, define a `slurm-cluster` SSH host for its login node. With key-based SSH, add the cluster's jump host and login node to your `~/.ssh/config`. Copy the jump host from the console's key-based command into the `together-jump` entry: ```ssh-config theme={null} # Keep connections alive Host * ServerAliveInterval 60 # Together AI bastion host for your cluster Host together-jump HostName ssh.t-..cloud.together.ai User # Your Slurm login node Host slurm-cluster HostName slurm-login ProxyJump together-jump User ``` With OIDC, have the CLI write the entry instead. This command signs you in, adds `slurm-cluster` to `~/.together/ssh/config`, and includes that file from `~/.ssh/config`: ```bash theme={null} tg clusters ssh https://dex..cloud.together.ai/t- --login \ --ssh-config-alias slurm-cluster --write-ssh-config ``` Run the command again when its short-lived certificate expires. Then, in VS Code's Remote SSH extension, connect to `slurm-cluster`. ## Troubleshooting * **Key-based SSH fails with `Permission denied (publickey)`:** Check that you added your SSH key at [api.together.ai/settings/ssh-key](https://api.together.ai/settings/ssh-key) before you created the cluster, then copy the command from the console again. * **OIDC command not found:** The `tg clusters ssh` command requires Together CLI 2.40+. Check your version with `tg --version`. To install or upgrade the CLI, run `uv tool install "together[cli]" --upgrade`. * **A copied OIDC command fails with `Unknown command "clusters"`:** The console copies `tg beta clusters ssh`, but Together CLI 3.0 removed the `beta` path. Delete `beta` from the copied command and run it again. ## Next steps > [card] [Slurm](/docs/slurm) > > Submit and manage batch jobs with the preconfigured Slurm scheduler. > [card] [Manage clusters](/docs/gpu-clusters-management) > > Manage access, scale capacity, and monitor cluster health. # Overview Source: https://docs.together.ai/docs/guides Quickstarts and step-by-step guides for building with Together AI. Agents Design agent loops, tools, and planners. Agent workflows Orchestrate multiple model calls to solve complex tasks. [Open](/docs/workflows) Sequential workflows Chain tasks so each step builds on the last. [Open](/docs/sequential-agent-workflow) Parallel workflows Run tasks simultaneously for faster results. [Open](/docs/parallel-workflows) Conditional workflows Branch the workflow based on evaluation results. [Open](/docs/conditional-workflows) Iterative workflows Repeat a task until a condition is met. [Open](/docs/iterative-workflow) Agent framework integrations Use frameworks like LangGraph and CrewAI with Together AI. [Open](/docs/integrations-2) Apps Full-stack patterns you can copy. Build a coding agent Write a code-editing agent from scratch in 400 lines. [Open](/docs/how-to-build-coding-agents) Build a Lovable clone Generate React apps from a single prompt with Kimi K2. [Open](/docs/how-to-build-a-lovable-clone-with-kimi-k2) Build a resume-to-website app Turn PDF resumes into personal websites with structured outputs. [Open](/docs/pdf-to-website-with-structured-outputs) Real-time audio transcription Transcribe live audio in a full-stack app. [Open](/docs/how-to-build-real-time-audio-transcription-app) PDF to podcast Convert PDF documents into podcast episodes with Open NotebookLM. [Open](/docs/open-notebooklm-pdf-to-podcast) AI tutor Build an intelligent tutoring system. [Open](/docs/ai-tutor) Chat API on Render Deploy an authenticated chat API to a Render web service. [Open](/docs/render-chat-api) AI search engine Build a simplified Perplexity-style search engine. [Open](/docs/ai-search-engine) General guides Coding tools, integrations, and capability guides. OpenClaw Run the OpenClaw autonomous agent on open-source models. [Open](/docs/how-to-use-openclaw) Cline Use Cline for AI-powered development in your editor. [Open](/docs/how-to-use-cline) Run nanochat on GPU clusters Train Karpathy's end-to-end ChatGPT clone on on-demand clusters. [Open](/docs/nanochat-on-gpu-clusters) Hugging Face inference Use Together AI with Hugging Face models and workflows. [Open](/docs/quickstart-using-hugging-face-inference) Vercel AI SDK Build apps with Vercel's AI SDK and Together AI. [Open](/docs/using-together-with-vercels-ai-sdk) Mastra Integrate Together AI models with the Mastra framework. [Open](/docs/using-together-with-mastra) Next.js chat quickstart Spin up a production-ready chatbot with Next.js. [Open](/docs/nextjs-chat-quickstart) OCR and structured extraction Extract text and typed data from documents with vision models. [Open](/docs/inference/vision/structured-extraction) Logprobs Use log probabilities to inspect model confidence. [Open](/docs/inference/chat/logprobs) Videos Generate videos from text and image prompts. [Open](/docs/inference/videos/overview) Mixture of agents Combine multiple models for better answers. [Open](/docs/mixture-of-agents) # Health checks Source: https://docs.together.ai/docs/health-checks Monitor GPU node health with active diagnostic tests and continuous passive monitoring. Health checks detect hardware and software issues on your GPU nodes before they impact running workloads. Together supports two types: * [Active checks](#active-health-checks) run diagnostic tests on demand. * [Passive checks](#passive-health-checks) monitor nodes continuously in the background. Passive checks can trigger [node repair](/docs/node-repair) recommendations automatically. Use active checks to confirm a fault before a [manual repair](/docs/node-repair#manual-node-repair) and to validate the node afterward. ## Active health checks Active health checks let you run targeted diagnostic tests on your GPU nodes to validate GPUs, InfiniBand networking, storage, and other components. These tests require full GPU utilization and run on demand. ### Run a health check > [!WARNING] > > **Workload impact:** An active health check affects any workload running on the node during the test. Run checks on idle nodes or during a maintenance window. 1. Navigate to your cluster on the [GPU clusters page](https://api.together.ai/clusters). 2. Select the **Health checks** tab. 3. Select **Run Health Check**. 4. In the **Run Health Check** form, select a test: * **DCGM Diag:** NVIDIA GPU diagnostics. * **GPU Burn:** GPU stress test. * **TorchTitan Training:** Training throughput benchmark on B200 nodes. * **Single-Node NCCL:** Single-node GPU communication test. * **Single-Node NCCL InfiniBand Fallback:** A variant of the Single-Node NCCL test. * **Multi-Node NCCL:** GPU communication test across two or more nodes. * **NVBandwidth: CPU to GPU Bandwidth:** PCIe bandwidth test. * **NVBandwidth: GPU to CPU Bandwidth:** PCIe bandwidth test. * **NVBandwidth: GPU-CPU Latency:** PCIe latency test. * **InfiniBand Write Bandwidth:** InfiniBand network performance test. * **Pairwise InfiniBand Write Bandwidth:** Two-node InfiniBand network performance test. * **Storage Perf:** Storage throughput and data-integrity test. 5. Optionally, set the parameters that appear under the selected test, such as diagnostic level or duration. 6. Select **Next: Select Nodes**. 7. Select the nodes to test. 8. Select **Run Health Check** to start the test. ### Available tests Each health check validates different aspects of your GPU infrastructure: #### GPU diagnostics **DCGM Diag** * Runs NVIDIA Data Center GPU Manager (DCGM) diagnostics. * Validates GPU compute capability, memory integrity, and thermal performance. * **Configurable:** Diagnostic level, from 1 to 4 (4 is the most comprehensive). * **Use for:** Comprehensive GPU health validation. * **Learn more:** [NVIDIA DCGM documentation](https://docs.nvidia.com/datacenter/dcgm/latest/user-guide/dcgm-diagnostics.html). **GPU Burn** * Stress-tests GPUs with intensive compute workloads. * Validates stability under sustained high utilization. * **Configurable:** Test duration. * **Use for:** Identifying thermal issues, power problems, or instability. * **Learn more:** [GPU Burn on GitHub](https://github.com/wilicc/gpu-burn). #### Network performance **Single-Node NCCL** * Tests the NVIDIA Collective Communications Library (NCCL) on a single node. * Validates GPU-to-GPU communication within the node. * **Use for:** Multi-GPU training readiness. * **Learn more:** [NVIDIA NCCL documentation](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/index.html). **Multi-Node NCCL** * Tests NCCL across all GPUs on the selected nodes. * Validates GPU-to-GPU communication between nodes. * **Requires:** A cluster with at least two GPU nodes. Select two or more nodes. * **Configurable:** NCCL algorithm (optional). * **Use for:** Distributed training readiness. **InfiniBand Write Bandwidth** * Measures InfiniBand network write throughput. * Validates high-speed interconnect performance. * **Use for:** Network readiness for distributed training and multi-node workloads. **Pairwise InfiniBand Write Bandwidth** * Measures InfiniBand write throughput between two GPU nodes, across their InfiniBand rails. * Validates node-to-node interconnect performance and rail-level connectivity. * **Requires:** A cluster with at least two GPU nodes. Select exactly two nodes. The first node you select is the server, and the second is the client. * **Configurable:** RDMA memory (`cpu` or `gpu`, default `cpu`) and direction (`both`, `client-to-server`, or `server-to-client`, default `both`). * **Use for:** Investigating slow or degraded links between specific node pairs before distributed training. #### PCIe performance **NVBandwidth Tests** * **CPU to GPU Bandwidth:** Host-to-device transfer rates. * **GPU to CPU Bandwidth:** Device-to-host transfer rates. * **GPU-CPU Latency:** Data transfer latency. * **Use for:** Identifying PCIe bottlenecks or degraded lanes. * **Learn more:** [NVIDIA nvbandwidth documentation](https://github.com/NVIDIA/nvbandwidth). #### Storage **Storage Perf** * Runs storage benchmarks against the shared and local storage tiers available to the cluster. * Measures sequential read and write throughput. * Validates data integrity with a checksummed write and read-back. * **Use for:** Detecting slow or degraded storage before it bottlenecks data loading or checkpointing. > [!NOTE] > > **Preview:** Storage Perf is in preview. Contact your account team for access. #### Training performance **TorchTitan Training** * Runs a short [TorchTitan](https://github.com/pytorch/torchtitan) training benchmark on a single node or across multiple nodes. * Measures the steady-state median model FLOPs utilization (MFU), skipping the warmup step. * Validates that a node sustains the expected training throughput for its GPU type. It catches badly degraded nodes that still pass point-in-time diagnostics. * **Requires:** NVIDIA B200 (Blackwell) GPU nodes with NVIDIA driver 580 or later. The benchmark's training stack (CUDA and PyTorch with FlashAttention-4) is built for the B200's compute capability, `sm_100`, so it doesn't run on other GPU types. * **Runtime:** About 15 minutes in total, roughly 9 minutes to initialize and 6 minutes to run. * **Use for:** End-to-end training-readiness validation. > [!NOTE] > > **Preview:** TorchTitan Training is in preview, so its behavior and thresholds may change. It runs only on demand and isn't part of [acceptance testing](#acceptance-testing). ### View test results The **Health checks** tab lists each run in a table with **Check**, **Status**, **Last run**, and **Nodes tested** columns. After a run finishes, select **View details** from its **⋮** menu to see the run's status and parameters, plus each node's status and output summary. From a node's **⋮** menu in the details, select **Download output** to save its output, or select **Repair** to [repair the node](/docs/node-repair#manual-node-repair). ### Pass/fail thresholds Performance-based health checks compare the measured result against a threshold. A bandwidth test passes when the measured value is greater than or equal to the threshold. Lower latency is better, so a latency test passes when the measured value is less than or equal to the threshold. The following thresholds are the defaults for on-demand health checks and acceptance tests. They're tuned for current GPU node types and may be adjusted over time as hardware and reference baselines change. | Test | Metric | Pass threshold | Test configuration | | - | - | - | - | | Single-Node NCCL | Average bus bandwidth | ≥ 300 GB/s | `all_reduce_perf` across 8 GPUs, 32 GiB message size. | | Multi-Node NCCL | Average bus bandwidth | ≥ 330 GB/s | `all_reduce_perf` across all GPUs on the selected nodes. | | InfiniBand Write Bandwidth | Reported write bandwidth | ≥ 320 Gb/s | `ib_write_bw` per device, 8 MiB message size, 2-second duration. | | Pairwise InfiniBand Write Bandwidth | Minimum bandwidth across rail measurements | ≥ threshold shown in run details | `ib_write_bw` between two nodes across InfiniBand rails, with configurable RDMA memory and direction. | | NVBandwidth: CPU to GPU Bandwidth | Per-GPU host-to-device bandwidth | ≥ 30 GB/s | `host_to_device_memcpy_ce`, averaged across 8 GPUs. | | NVBandwidth: GPU to CPU Bandwidth | Per-GPU device-to-host bandwidth | ≥ 30 GB/s | `device_to_host_memcpy_ce`, averaged across 8 GPUs. | | NVBandwidth: GPU-CPU Latency | Per-GPU host-device latency | ≤ 2000 ns | `host_device_latency_sm`, averaged across 8 GPUs. | | Storage (shared): Sequential Read | Bandwidth | ≥ 10 GiB/s | `fio` sequential read, 1 MiB blocks across 64 jobs at iodepth 32. | | Storage (shared): Sequential Write | Bandwidth | ≥ 5 GiB/s | `fio` sequential write, 1 MiB blocks across 64 jobs at iodepth 32. | | Storage (local): Sequential Read | Bandwidth | ≥ 2 GiB/s | `fio` sequential read, 1 MiB blocks across 16 jobs at iodepth 16. | | Storage (local): Sequential Write | Bandwidth | ≥ 1 GiB/s | `fio` sequential write, 1 MiB blocks across 16 jobs at iodepth 16. | | TorchTitan Training | Steady-state median MFU | ≥ 30% | Llama 3 8B on a single B200 node, 40 training steps (the single-node default). | > [!NOTE] > > **Units differ by test:** NCCL and NVBandwidth bandwidth thresholds are reported in gigabytes per second (GB/s), while InfiniBand write bandwidth is reported in gigabits per second (Gb/s). The two aren't directly comparable (320 Gb/s is 40 GB/s). Storage thresholds use gibibytes per second (GiB/s). Latency is reported in nanoseconds (ns), and TorchTitan MFU is reported as a percentage. The TorchTitan pass threshold and reference MFU depend on the model and node topology. The 30% default is a loose floor for Llama 3 8B on a single node, where the reference MFU is about 36.5%. Larger models and multi-node runs use different reference values, which are set per run. For example, Llama 3 70B reaches about 38% MFU on a four-node cluster. ### Acceptance testing Acceptance tests validate each node before it joins your cluster. They add their run time to provisioning, so they're off by default. Turn them on for multi-GPU training or long-running clusters, where catching a bad node before the job starts saves more time than the tests cost. To turn them on when you create a cluster, open **Advanced configuration** in the create form and select **Run all**, or turn on individual tests: * **DCGM Diag:** Runs GPU diagnostics at the **Diagnostic Level** you choose (Level 2 by default). * **GPU Burn:** Stress-tests the GPUs for the **Test duration** you choose (5 minutes by default). * **Single-Node NCCL:** Validates GPU-to-GPU communication within each node. * **Multi-Node NCCL:** Validates GPU-to-GPU communication across nodes. The form shows the estimated total test time. To set the same options through the API, pass `acceptance_tests_params` to [cluster create](/reference/clusters-create). #### Cluster status during testing When acceptance tests are on, the nodes run them before the cluster becomes available. The cluster status shows their progress: * **Running Tests:** Acceptance tests are in progress. * **Tests Failed:** One or more acceptance tests didn't pass. * **Ready:** Tests passed, and the cluster is ready for workloads. #### Investigate failed acceptance tests When the cluster status shows **Tests Failed**, find out which test failed and why: 1. Navigate to your cluster on the [GPU clusters page](https://api.together.ai/clusters). 2. Select the **Health checks** tab. 3. Find the acceptance test runs for the affected nodes. 4. Select **View details** to see: * Which specific test failed (DCGM Diag, GPU Burn, or NCCL). * Detailed error messages and logs. * Performance metrics from the tests. > [!NOTE] > > **Failed nodes:** When a node fails acceptance tests, Together's infrastructure team is notified automatically and investigates. The node isn't added to your cluster until the issue is resolved. ### When to run active health checks Run active checks proactively, before a problem shows up: * Before you deploy critical workloads. * After you scale the cluster. * After a maintenance window. * On a regular schedule, such as weekly or monthly. Run them reactively, in response to a problem: * When jobs fail for no clear reason. * When performance degrades. * Before you repair a node, to confirm the fault. * After a repair, to validate the fix. To investigate a specific symptom, run the tests that target it: * **Training instability:** Run GPU Burn and DCGM Diag. * **Slow data loading:** Run Storage Perf and the NVBandwidth tests. * **Multi-GPU failures:** Run Single-Node NCCL. * **Distributed training issues:** Run the InfiniBand tests. To isolate a slow link between two specific nodes, run Pairwise InfiniBand Write Bandwidth. * **Low training throughput:** Run TorchTitan Training. ### Best practices 1. **Schedule workload-free windows:** Health checks require full GPU utilization. 2. **Start with DCGM Diag:** It provides a comprehensive overview of GPU health. 3. **Run baseline tests:** Test new nodes immediately to establish a performance baseline. 4. **Document results:** Keep records of passed tests for comparison. 5. **Test after repair:** Always validate node health after repair actions. 6. **Use appropriate test levels:** Higher DCGM diagnostic levels take longer but are more thorough. > [!WARNING] > > **Workload impact:** Health checks fully utilize the GPU and can interfere with running workloads. Run tests during maintenance windows or on idle nodes. ## Passive health checks Passive health checks run continuously in the background on every GPU node in your cluster, observing real workloads, system logs, and GPU metrics. Unlike active checks, they need no action from you and don't affect running jobs. ### How passive checks work Passive checks monitor node telemetry and system logs in real time. There is no synthetic load: the system observes your production traffic and flags degradation as it happens. When an issue is detected, the system creates an internal alert with supporting evidence. If the alert meets repair criteria, a [repair recommendation](/docs/node-repair#auto-node-repair) is generated automatically. ### Detected failure modes Passive checks continuously watch node telemetry, GPU metrics, and system logs, and raise a signal when a node shows one of the conditions below. Each signal that meets repair criteria generates a [repair recommendation](/docs/node-repair#auto-node-repair) with a suggested action. #### GPU and accelerator | Condition | Signal | Typical cause | | - | - | - | | GPU fell off the bus | `DmesgGpuFallenOffBus` | GPU becomes unreachable on the PCIe bus, typically a hardware or connector failure. | | GPU thermal throttling | `GpuSmClockThermalThrottle` | Sustained high temperature forces SM clocks down, degrading throughput with no application error. | | GPU Xid error | `DmesgXidError` | NVIDIA driver or hardware Xid fault reported in the kernel log. | | Uncorrectable ECC error | `GpuEccDoubleBitError` | Double-bit GPU memory error. | | GPU row-remap failure | `GpuRowRemapFailure` | GPU memory row-remap failed. The GPU likely needs replacement (RMA). | | High PCIe replay rate | `GpuPcieReplayRateHigh` | Degraded PCIe link integrity. | #### InfiniBand networking | Condition | Signal | Typical cause | | - | - | - | | Rails down or degraded | `IBRailsDownOrDegraded` | Fewer than 8 compute rails are active at the NIC's expected line rate (400G or 800G), because a rail is down or negotiated a lower rate. | | Link flapping | `IBLinkFlapping` | Repeated InfiniBand link-down events on a compute rail. | #### Node OS, kernel, and resources | Condition | Signal | Typical cause | | - | - | - | | Fatal platform hardware error | `NpdCperHardwareErrorFatal` | Fatal CPER-reported platform hardware error. | | Read-only filesystem | `NpdReadonlyFilesystem` | Root or data filesystem remounted read-only. | | XFS shutdown | `NpdXfsShutdown` | XFS filesystem shut down after an error. | | Kernel deadlock | `NpdKernelDeadlock` | A kernel task is stuck. | | Frequent kubelet restarts | `NpdFrequentKubeletRestart` | kubelet is restarting repeatedly. | | Frequent containerd restarts | `NpdFrequentContainerdRestart` | containerd is restarting repeatedly. | | Frequent netdev unregister | `NpdFrequentUnregisterNetDevice` | Repeated network device unregister events. | | Memory pressure | `KubeNodeMemoryPressure` | Node under sustained memory pressure. | | Disk pressure | `KubeNodeDiskPressure` | Node under sustained disk pressure. | | PID pressure | `KubeNodePIDPressure` | Node is exhausting available process IDs. | #### Host | Condition | Signal | Typical cause | | - | - | - | | Host unreachable | `TenantNodeHostUnreachable` | The physical host running the node's VM is unreachable. | #### Scheduler | Condition | Signal | Typical cause | | - | - | - | | Slurm node unavailable | `SlurmNodeUnavailable` | Slurm has reported the node as `DOWN`, or as drained and idle, for 30 minutes. | [Recommended repair actions](/docs/node-repair#recommended-repair-actions) lists the repair action each signal maps to. > [!NOTE] > > Automated recommendations are enabled per cluster. Not every signal triggers one. Some raise an internal alert that Together's team reviews. Detection coverage is expanding to more hardware and software signals. ### Active vs. passive checks * **Active checks:** Run on demand, using synthetic workloads that require full GPU utilization to validate specific hardware capabilities. They're best for targeted diagnostics and pre-deployment validation, and they help you confirm a fault and validate a node after repair. * **Passive checks:** Run continuously with zero overhead, observing real workloads and system logs to catch degradation as it happens. They're best for ongoing monitoring and early detection, and they feed [node repair](/docs/node-repair) recommendations. ## Next steps > [card] [Node repair](/docs/node-repair) > > Restore unhealthy nodes through automated recommendations or manual repair actions. > [card] [Manage clusters](/docs/gpu-clusters-management) > > Create, scale, and monitor your GPU clusters. # Build a Lovable clone with Kimi K3 Source: https://docs.together.ai/docs/how-to-build-a-lovable-clone-with-kimi-k2 Build a full-stack Next.js app that generates React apps from a single prompt. [LlamaCoder](https://llamacoder.together.ai/) is a Lovable-inspired app that shows off how to use Together AI’s hosted LLM endpoints to build AI applications. ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/15.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=3b9b258e4c650436c4d23d7aaff5b353) In this post, we’re going to learn how to build the core parts of the app. LlamaCoder is a Next.js app, but Together’s APIs can be used with any web framework or language! ## Step 1: Scaffold the initial UI The core interaction of LlamaCoder is a text field where the user can enter a prompt for an app they’d like to build. So to start, we need that text field: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/16.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=f04cf018c8b1314eedcbd166ba252a78) We’ll render a text input inside of a form, and use some new React state to control the input’s value: ```jsx JSX theme={null} function Page() { let [prompt, setPrompt] = useState(''); return (
setPrompt(e.target.value)} placeholder='Build me a calculator app...' required />
); } ``` Next, let’s wire up a submit handler to the form. We’ll call it `createApp`, since it’s going to take the user’s prompt and generate the corresponding app code: ```jsx JSX theme={null} function Page() { let [prompt, setPrompt] = useState(''); function createApp(e) { e.preventDefault(); // TODO: // 1. Generate the code // 2. Render the app } return
{/* ... */}
; } ``` To generate the code, we’ll have our React app query a new API endpoint. Let’s put it at `/api/generateCode`, and we’ll make it a POST endpoint so we can send along the `prompt` in the request body: ```jsx JSX theme={null} async function createApp(e) { e.preventDefault(); // TODO: // 1. Generate the code await fetch('/api/generateCode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }); // 2. Render the app } ``` Looks good – let’s go implement it! ## Step 2: Generate code in an API route To create an API route in the Next.js 14 app directory, we can make a new `route.js` file: ```jsx JSX theme={null} // app/api/generateCode/route.js export async function POST(req) { let json = await req.json(); console.log(json.prompt); } ``` If we submit the form, we’ll see the user’s prompt logged to the console. Now we’re ready to send it off to our LLM and ask it to generate our user’s app! We tested many open source LLMs and found that Kimi K3 was the only one that did a good job at generating small apps, so that’s what we decided to use for the app. We’ll install Together’s node SDK: ```bash Shell theme={null} npm i together-ai ``` and use it to kick off a chat with Kimi K3. Here’s what it looks like: ```jsx JSX theme={null} // app/api/generateCode/route.js import Together from 'together-ai'; let together = new Together(); export async function POST(req) { let json = await req.json(); let completion = await together.chat.completions.create({ model: 'moonshotai/Kimi-K3', messages: [ { role: 'system', content: 'You are an expert frontend React engineer.', }, { role: 'user', content: json.prompt, }, ], }); return Response.json(completion); } ``` We call `together.chat.completions.create` to get a new response from the LLM. We’ve supplied it with a “system” message telling the LLM that it should behave as if it’s an expert React engineer. Finally, we provide it with the user’s prompt as the second message. Since we return a JSON object, let’s update our React code to read the JSON from the response: ```jsx JSX theme={null} async function createApp(e) { e.preventDefault(); // 1. Generate the code let res = await fetch('/api/generateCode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }); let json = await res.json(); console.log(json); // 2. Render the app } ``` And now let’s give it a shot! We’ll use something simple for our prompt like “Build me a counter”: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/17.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=ff79766604b0ecdf613528a6409e0736) When we submit the form, our API response takes several seconds, but then sends our React app the response. If you take a look at your logs, you should see something like this: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/18.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=aecf6247f32c6431afe963569c44f898) Not bad – Kimi K3 has generated some code that looks pretty good and matches our user’s prompt! However, for this app, we’re only interested in the code, since we’re going to be actually running it in our user’s browser. So we need to do some prompt engineering to get Kimi K3 to only return the code in a format we expect. ## Step 3: Engineer the system message to only return code We spent some time tweaking the system message to make sure it output the best code possible – here’s what we ended up with for LlamaCoder: ```jsx JSX theme={null} // app/api/generateCode/route.js import Together from 'together-ai'; let together = new Together(); export async function POST(req) { let json = await req.json(); let res = await together.chat.completions.create({ model: 'moonshotai/Kimi-K3', messages: [ { role: 'system', content: systemPrompt, }, { role: 'user', content: json.prompt, }, ], stream: true, }); return new Response(res.toReadableStream(), { headers: new Headers({ 'Cache-Control': 'no-cache', }), }); } let systemPrompt = ` You are an expert frontend React engineer who is also a great UI/UX designer. Follow the instructions carefully, I will tip you $1 million if you do a good job: - Create a React component for whatever the user asked you to create and make sure it can run by itself by using a default export - Make sure the React app is interactive and functional by creating state when needed and having no required props - If you use any imports from React like useState or useEffect, make sure to import them directly - Use TypeScript as the language for the React component - Use Tailwind classes for styling. DO NOT USE ARBITRARY VALUES (e.g. \`h-[600px]\`). Make sure to use a consistent color palette. - Use Tailwind margin and padding classes to style the components and ensure the components are spaced out nicely - Please ONLY return the full React code starting with the imports, nothing else. It's very important for my job that you only return the React code with imports. DO NOT START WITH \`\`\`typescript or \`\`\`javascript or \`\`\`tsx or \`\`\`. NO LIBRARIES (e.g. zod, hookform) ARE INSTALLED OR ABLE TO BE IMPORTED. `; ``` Now if we try again, we’ll see something like this: ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/19.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=f1d16f71f2ca2fa446da7b90498350fa) Much better –this is something we can work with! ## Step 4: Run the generated code in the browser Now that we’ve got a pure code response from our LLM, how can we actually execute it in the browser for our user? This is where the phenomenal [Sandpack](https://sandpack.codesandbox.io/) library comes in. Once we install it: ```bash Shell theme={null} npm i @codesandbox/sandpack-react ``` we now can use the `` component to render and execute any code we want! Let’s give it a shot with some hard-coded sample code: ```jsx JSX theme={null} Hello, world!

}`, }} /> ``` If we save this and look in the browser, we’ll see that it works! ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/20.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=c6a9fec2cfc230edbb74d74604b97a22) All that’s left is to swap out our sample code with the code from our API route instead. Let’s start by storing the LLM’s response in some new React state called `generatedCode`: ```jsx JSX theme={null} function Page() { let [prompt, setPrompt] = useState(''); let [generatedCode, setGeneratedCode] = useState(''); async function createApp(e) { e.preventDefault(); let res = await fetch('/api/generateCode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }); let json = await res.json(); setGeneratedCode(json.choices[0].message.content); } return (
{/* ... */}
); } ``` Now, if `generatedCode` is not empty, we can render `` and pass it in: ```jsx JSX theme={null} function Page() { let [prompt, setPrompt] = useState(''); let [generatedCode, setGeneratedCode] = useState(''); async function createApp(e) { // ... } return (
{/* ... */}
{generatedCode && ( )}
); } ``` Let’s give it a shot! We’ll try “Build me a calculator app” as the prompt, and submit the form. Once our API endpoint responds, `` renders our generated app! ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/21.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=4e47962545fab91b857856e5c92c45db) The basic functionality is working great! Together AI (with Kimi K3) + Sandpack have made it a breeze to run generated code right in our user’s browser. ## Step 5: Stream the code for immediate UI feedback Our app is working well –but we’re not showing our user any feedback while the LLM is generating the code. This makes our app feel broken and unresponsive, especially for more complex prompts. To fix this, we can use Together AI’s support for streaming. With a streamed response, we can start displaying partial updates of the generated code as soon as the LLM responds with the first token. To enable streaming, there are two changes we need to make: 1. Update our API route to respond with a stream. 2. Update our React app to read the stream. Let’s start with the API route. To get Together to stream back a response, we need to pass the `stream: true` option into `together.chat.completions.create()`. We also need to update our response to call `res.toReadableStream()`, which turns the raw Together stream into a newline-separated ReadableStream of JSON stringified values. Here’s what that looks like: ```jsx JSX theme={null} // app/api/generateCode/route.js import Together from 'together-ai'; let together = new Together(); export async function POST(req) { let json = await req.json(); let res = await together.chat.completions.create({ model: 'moonshotai/Kimi-K3', messages: [ { role: 'system', content: systemPrompt, }, { role: 'user', content: json.prompt, }, ], stream: true, }); return new Response(res.toReadableStream(), { headers: new Headers({ 'Cache-Control': 'no-cache', }), }); } ``` That’s it for the API route! Now, let’s update our React submit handler. Currently, it looks like this: ```jsx JSX theme={null} async function createApp(e) { e.preventDefault(); let res = await fetch('/api/generateCode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }); let json = await res.json(); setGeneratedCode(json.choices[0].message.content); } ``` Now that our response is a stream, we can’t just `res.json()` it. We need a small helper function to read the text from the actual bytes that are being streamed over from our API route. Here’s the helper function. It uses an [AsyncGenerator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator) to yield out each chunk of the stream as it comes over the network. It also uses a TextDecoder to turn the stream’s data from the type Uint8Array (which is the default type used by streams for their chunks, since it’s more efficient and streams have broad applications) into text, which we then parse into a JSON object. So let’s copy this function to the bottom of our page: ```jsx JSX theme={null} async function* readStream(response) { let decoder = new TextDecoder(); let reader = response.getReader(); while (true) { let { done, value } = await reader.read(); if (done) { break; } let text = decoder.decode(value, { stream: true }); let parts = text.split('\\n'); for (let part of parts) { if (part) { yield JSON.parse(part); } } } reader.releaseLock(); } ``` Now, we can update our `createApp` function to iterate over `readStream(res.body)`: ```jsx JSX theme={null} async function createApp(e) { e.preventDefault(); let res = await fetch('/api/generateCode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }); for await (let result of readStream(res.body)) { setGeneratedCode( (prev) => prev + result.choices.map((c) => c.text ?? '').join('') ); } } ``` This is the cool thing about Async Generators –we can use `for...of` to iterate over each chunk right in our submit handler! By setting `generatedCode` to the current text concatenated with the new chunk’s text, React automatically re-renders our app as the LLM’s response streams in, and we see `` updating its UI as the generated app takes shape. ![](https://mintcdn.com/togetherai-52386018/msWWavplJrEZR36N/images/guides/22.png?fit=max\&auto=format\&n=msWWavplJrEZR36N\&q=85\&s=3b1cc77e62ae3caedb66c23dd6976460) Pretty nifty, and now our app is feeling much more responsive! ## Digging deeper And with that, you now know how to build the core functionality of Llama Coder! There’s plenty more tricks in the production app including animated loading states, the ability to update an existing app, and the ability to share a public version of your generated app using a Neon Postgres database. The application is open-source, so check it out here to learn more: **[https://github.com/Nutlope/llamacoder](https://github.com/Nutlope/llamacoder)** And if you’re ready to start querying LLMs in your own apps to add powerful AI features just like the kind we saw in this post, [sign up for Together AI](https://api.together.ai/) today and make your first query in minutes! # Build a real-time image generator with Flux Source: https://docs.together.ai/docs/how-to-build-a-real-time-image-generator Create a real-time text-to-image app with Juggernaut Lightning Flux, Next.js, and Together AI. [BlinkShot](https://www.blinkshot.io/) is an open-source app that generates images from text in real time, as you type. It uses [Juggernaut Lightning Flux](https://www.together.ai/models/juggernaut-lightning-flux) on Together AI, a FLUX-based model that returns an image in under two seconds. ![BlinkShot generating an image as the user types a prompt](https://mintcdn.com/togetherai-52386018/Hlnt9JlDDEMj60mv/images/guides/blinkshot/cover.png?fit=max\&auto=format\&n=Hlnt9JlDDEMj60mv\&q=85\&s=aceefa4946c5b4247d8f6fa711f59715) Follow this guide to learn how to build the core parts of BlinkShot. The app is [open source](https://github.com/Nutlope/blinkshot) and built with Next.js and React Query, but the concepts apply to any language or framework. ## Build the prompt input The core interaction of BlinkShot is a single textarea where you describe an image. There's no submit button. Because the model is fast enough to generate images in real time, the app fires a request as you type: ```typescript theme={null} function Home() { const [prompt, setPrompt] = useState(""); return (