# Best Practices Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/best-practice ## Common strategy on setting up deployment * **GPU type + GPU count** = performance per replica * **Replicas** = traffic capacity and availability Start with the smallest setup that reliably meets baseline needs, then scale deliberately based on real traffic and observability: **1. 1 replica set up: Choose a GPU type and gpu\_count that meets single-replica performance goals** **2. Autoscaling set up: Use replicas to absorb traffic spikes and concurrency** *** ## Choosing performance setup: GPU types & GPUs per replica Choosing the right dedicated endpoint configuration depends on your workload’s priorities: latency, throughput, model size, and cost efficiency. ### GPU type GPU type determines the performance profile of each replica, including memory capacity, throughput, and cost. In general: | Higher-end GPUs | Mid-range GPUs | | - | - | | | | > [!TIP] > > **Rule of thumb:** Choose the smallest GPU type that supports your model and region. If performance is insufficient, first scale GPU type or GPUs per replica before aggressively increasing replicas. ### GPUs per replica (`gpu_count`) `gpu_count` defines how many GPUs power a single replica. This primarily affects: * Per-request latency * Maximum throughput per replica * Ability to serve larger or more demanding workloads | Lower GPU count per replica | Higher GPU count per replica | | - | - | | | | > [!TIP] > > **Rule of thumb:** Start small when you are testing traffic, usage is uncertain, internal deployment, cost control matters. Scale up when requests are latency-sensitive, individual replicas saturate, you need stronger single-endpoint performance > > Avoid Over-relying on replicas to solve underpowered replicas. More replicas help concurrency, but they do not fix poor per-request latency caused by insufficient GPU resources. *** ## Choosing number of replicas Replicas determine how much baseline and burst traffic your deployment can handle. ### Min replicas: guaranteed baseline capacity Minimum replicas are always allocated while the endpoint is active. Use higher `min_replicas` when: * You need predictable low latency * Traffic is steady * Cold starts are unacceptable * Capacity predictability matters Use lower `min_replicas` when: * Traffic is irregular * You optimize for cost * Batch or internal workloads * Occasional warm-up is acceptable ### Max replicas: burst scaling ceiling Maximum replicas define how far autoscaling can expand if capacity is available. Use higher `max_replicas` when: * Traffic spikes significantly * Usage is unpredictable * You need burst headroom Use lower `max_replicas` when: * Workload is stable * Budget control matters * Capacity is predictable > [!TIP] > > **Rule of thumb:** > > * min\_replicas - what you always need > * max\_replicas - what you may need during peaks > [!NOTE] > > **Note that:** > > * Min replicas are guaranteed while active. If you stop the endpoint the reservation will be freed up. > * Max replicas scaling depends on available capacity and may not always be continuously available after scale-down. [Read more in Capacity section](/ai-models-inference/dedicated-endpoints/capacity-and-scaling) # Billing Policy Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/billing-policy ### Billing while active * A dedicated endpoint is considered **active, accessible, and billable** when **at least one replica is running** * When **one or more replicas are running**, the endpoint is available to serve traffic and billing charges apply. * When **zero replicas are running**, the endpoint is not accessible and billing charges do not apply. * Charges may vary depending on your custom contract or work order. ### Autoscaling costs Scaling above or below minimum replicas adjusts billing dynamically on a PAYG basis. ### Capacity retention As long as your endpoint remains active, minimum replicas remain allocated to you. Once capacity is released, it may be reassigned and may not be immediately available again. ### Specific cases | Lifecycle step | Billing | | - | - | | Capacity provisioning, `not ready` , `partially ready` | Not billed | | Capacity provisioned to the endpoint,`ready` status | Billed | | Replica restarts | Not billied | | Graceful shutdown for rolling update, endpoint stop | Not billed | # Capacity, availability, and service guarantees Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/capacity-and-scaling ### Capacity availability Dedicated endpoint deployment depends on available capacity across different regions. Not all listed GPU types may be available at all times. Availability depends on current regional capacity. ### Capacity after stops, incidents, and maintenance Self-service dedicated endpoints are provisioned on Nebius AI Cloud on-demand (pay-as-you-go) capacity. This capacity is drawn from a shared pool and is allocated to your endpoint only while it is active — **it is not a long-term reservation, and the minimum replicas guarantee applies only while the endpoint is running.** **When an endpoint stops, its GPU capacity is released back to the shared pool. This applies regardless of why the endpoint stopped**: * You stop the endpoint manually * The endpoint is interrupted by an incident * The endpoint is stopped for scheduled or emergency maintenance When the endpoint starts again, capacity is requested from the pool anew and allocated based on availability at that moment. There is no mechanism that holds your previous GPUs for the endpoint or returns them after an interruption. As a result: * After a restart, the endpoint may stay in **Starting / Not ready**, or reach only **Partially ready**, until sufficient capacity becomes available. See [Lifecycle & Readiness Status](/ai-models-inference/dedicated-endpoints/lifecycle-and-status). * During periods of high demand, or for scarce GPU types, restarting may take significantly longer than the initial deployment, and capacity may be temporarily unavailable. This is the standard behavior of on-demand capacity in Nebius AI Cloud, on which self-service dedicated endpoints run: without a reservation, GPU resources are taken from a shared pool and returned to it when they stop — whether stopped by you or by a maintenance event — and recovery after maintenance or an incident does not restore the capacity your endpoint used before. For details on how on-demand and reserved capacity work, see [Capacity reservations for Compute virtual machines](https://docs.nebius.com/compute/virtual-machines/reservations) in the Nebius AI Cloud documentation. > [!NOTE] > > If your workload requires guaranteed capacity across restarts, incidents, and maintenance windows, [contact our Sales team to reserve dedicated GPU capacity](https://nebius.com/services/token-factory/enterprise-grade-inference#token-factory-enterprise-sales-form) ### Minimum replicas guarantee Minimum replicas are reserved and non-preemptible and remain allocated to your deployment for as long as the endpoint is active. If the endpoint stops for any reason, this allocation is released — see the section above. ### Maximum replicas scaling Scaling above minimum replicas depends on available burst capacity and is not guaranteed indefinitely. Additional replicas may be reclaimed after scale-down and may not always be available again without sufficient capacity. ### SLA Self-service dedicated endpoints do not include a formal SLA unless covered by contract. > [!NOTE] > > If you encounter capacity errors or are unable to scale beyond the minimum number of replicas, [contact our Sales team to reserve dedicated GPU capacity](https://nebius.com/services/token-factory/enterprise-grade-inference?_gl=1*b0acui*_gcl_au*MTAwNTQwNDk0NC4xNzcwMjkyMzc3LjExODU3MTgzMTAuMTc3NjA5NDQ4Ni4xNzc2MDk0NDg1#token-factory-enterprise-sales-form) # Control & Data Plane Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/control-data-plane ## Terminology | **Term** | **Description** | | :- | :- | | **Template** | A deployable performance “blueprint” for a model. Templates define which `flavor_name`, `gpu_type`, and regions are supported. | | **Flavor** | A template's sub-option (e.g. `base`, `fast`) with different performance/throughput/costs characteristics. | | **Endpoint** | Dedicated deployment with API access | | **endpoint\_id** | Identifier used for update/delete operations. | | **routing\_key** | The model identifier you pass to inference calls. Returned when you create an endpoint. | | **Control plane** | Sets up the configuration and settings of your endpoints. Has common base URL API. | | **Data plane** | Processes model inference requests. Has regional base URL API. | ## Control plane Dedicated Endpoints Control Plane is a managedment layer for all configurations operations: * Creating & updating endpoints * Uploading models / weights * Scaling configs (min/max replicas) * Monitoring setup Use common base URL API for all dedicated endpoint management operations: ```text theme={null} https://api.tokenfactory.nebius.com ``` ## Data plane Dedicated Endpoints Data Plane processes model inference requests. It has regional base URL API. Region impacts latency, data locality, and regulatory compliance. Use a region-appropriate base URL for your inference calls: | Endpoint region | Inference base URL | | :- | :- | | `eu-north1` | `https://api.tokenfactory.nebius.com` | | `eu-west1` | `https://api.tokenfactory.eu-west1.nebius.com` | | `us-central1` | `https://api.tokenfactory.us-central1.nebius.com` | > [!NOTE] > > Using the respective inference base URL avoids unnecessary global routing and reduces round-trip latency. ## Endpoint Observability > [card] [Observability](https://docs.tokenfactory.nebius.com/ai-models-inference/observability) > > Check out Observability Documentation section here # Custom model weights Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/custom-weights **Working with custom model weights** is currently in beta and available on request. If you’d like to deploy or work with custom fine-tuned model weights, [please contact our Support team to enable access](https://tokenfactory.nebius.com/?modals=contact-us) and guide you through the current setup process. Availability, supported configurations, and onboarding steps may vary during the beta period. # Quickstart: Deploy via API Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/deploy-api ## Overview Deploying a dedicated endpoint via API takes three steps: 1. List available model templates 2. Create a dedicated endpoint 3. Send inference requests For updating, listing, and deleting endpoints, see **Operating dedicated endpoints**. ## List model templates List model templates that can be used to create a dedicated endpoint. ```http theme={null} GET /v0/dedicated_endpoints/templates ``` ```python Python theme={null} import os, json, requests CONTROL_PLANE_BASE_URL = "https://api.tokenfactory.nebius.com" API_TOKEN = os.environ["API_TOKEN"] r = requests.get( f"{CONTROL_PLANE_BASE_URL}/v0/dedicated_endpoints/templates", headers={"Authorization": f"Bearer {API_TOKEN}"}, ) r.raise_for_status() print(json.dumps(r.json(), indent=2)) ``` ```shellscript cURL theme={null} curl -sS \ -H "Authorization: Bearer $API_TOKEN" \ "https://api.tokenfactory.nebius.com/v0/dedicated_endpoints/templates" ``` > [!TIP] > > Use the template response as the source of truth for valid combinations of `model_name`, `flavor_name`, `gpu_type`, `gpu_count` and `region`. ## Create dedicated endpoint Create a dedicated endpoint from one of the available model templates. ```http theme={null} POST /v0/dedicated_endpoints ``` ```python Python theme={null} import os, json, requests CONTROL_PLANE_BASE_URL = "https://api.tokenfactory.nebius.com" API_TOKEN = os.environ["API_TOKEN"] payload = { "name": "GPT-20B Endpoint", "description": "Dedicated GPT-20B for internal apps", "model_name": "openai/gpt-oss-20b", "flavor_name": "base", "gpu_type": "gpu-h100-sxm", "gpu_count": 1, "region": "eu-north1", "scaling": {"min_replicas": 1, "max_replicas": 2}, } r = requests.post( f"{CONTROL_PLANE_BASE_URL}/v0/dedicated_endpoints", headers={"Authorization": f"Bearer {API_TOKEN}"}, json=payload, ) r.raise_for_status() print(json.dumps(r.json(), indent=2)) ``` ```shellscript cURL theme={null} curl -sS -X POST \ "https://api.tokenfactory.nebius.com/v0/dedicated_endpoints" \ -H "Authorization: Bearer $API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "GPT-20B Endpoint", "description": "Dedicated GPT-20B for internal apps", "model_name": "openai/gpt-oss-20b", "flavor_name": "base", "gpu_type": "gpu-h100-sxm", "gpu_count": 1, "region": "eu-north1", "scaling": { "min_replicas": 1, "max_replicas": 2 } }' ``` The response includes endpoint metadata, including: * `endpoint_id` * `routing_key` Use `endpoint_id` to manage the endpoint through the control plane. Use `routing_key` as the model identifier when sending inference requests to the data plane. > [!NOTE] > > Initial deployment can take several minutes. While provisioning, inference may fail (often `404`) until the endpoint is routable. ## Send inference requests Once the endpoint is ready, send requests to the OpenAI-compatible data plane under `/v1`. Use the `routing_key` returned by the control plane as the `model` value in inference requests: ```text theme={null} model = "" ``` Use a region-appropriate base URL for your inference calls. Example request URL: ```text theme={null} https://api.tokenfactory.us-central1.nebius.com/v1/chat/completions ``` ```python Python (OpenAI SDK) theme={null} import os from openai import OpenAI API_TOKEN = os.environ["API_TOKEN"] # Choose based on the endpoint region INFERENCE_BASE_URL = "https://api.tokenfactory.us-central1.nebius.com/v1" client = OpenAI( base_url=INFERENCE_BASE_URL, api_key=API_TOKEN, ) routing_key = "" # use exactly what the API returned response = client.chat.completions.create( model=routing_key, messages=[{"role": "user", "content": "Explain the difference between LLM fine-tuning and RAG."}], ) print(response.choices[0].message.content) ``` ```shellscript cURL theme={null} curl -sS "https://api.tokenfactory.us-central1.nebius.com/v1/chat/completions" \ -H "Authorization: Bearer $API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "model": "", "messages": [ { "role": "user", "content": "Hello from my dedicated endpoint!" } ] }' ``` > [!NOTE] > > We expose OpenAI-compatible inference routes under `/v1`. Template availability determines what kinds of models you can deploy (today, publicly available templates are primarily chat-capable). # Quickstart: Deploy in UI Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/deploy-ui Dedicated endpoints can be deployed and managed through the Token Factory UI, with API workflows also available for automation. You can create a dedicated endpoint from either of these UI locations: * Explore page: [https://tokenfactory.nebius.com/](https://tokenfactory.nebius.com/) * Inference → Model Endpoints: [https://tokenfactory.nebius.com/endpoints](https://tokenfactory.nebius.com/endpoints) ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-1.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=8f9656a919778aac506cc9e9c8ee0736) ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-3.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=9ce0245a0c399c5455969148d0121600) 1. Explore page [https://tokenfactory.nebius.com/](https://tokenfactory.nebius.com/) 2. Inference/Model Endpoints [https://tokenfactory.nebius.com/endpoints](https://tokenfactory.nebius.com/endpoints) From there, select a supported model template and complete the deployment configuration, including region, GPU configuration, and autoscaling settings. ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-6.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=0a3555f01f8c22d3d349919602faa3df) ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-5.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=a23be242beb64cb05335f47eae9f4fbc) ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-4.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=f9e9d9e94b8041d2cb5e4b319864c276) ## Walkthrough on UI deployment [YouTube video player](https://www.youtube.com/embed/5NsvfFjShaY) > [!NOTE] > > **Prefere automation?**\ > For API-based deployment, see [Deploy in API ](/ai-models-inference/dedicated-endpoints/deploy-api)section ## Using endpoint Go to **Inference → Model Endpoints** and open your private endpoint card. ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-7.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=42fe1d3386a6cf29363f2eef7106b2bd) There, you can view key deployment details, including: * Endpoint ID * Routing key * Model * GPUs per replica * Minimum and maximum replicas * Deployment status * Ready-to-use code snippets To update configuration, click **Edit Endpoint**. ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-9.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=ab6e4a5e931ce471c5041355d2fb3a68) ![Image](https://mintcdn.com/nebius-723e8b65/o-_JxcbZvL-sB_4h/images/image-10.png?fit=max\&auto=format\&n=o-_JxcbZvL-sB_4h\&q=85\&s=28ac3a5f043aa64a666af3ba998b02dd) To check observability metrics you can either: 1. Open dedicated endpoints model card and click Observability button below 2. Go to observability section and set filters to your enpoint: [https://tokenfactory.nebius.com/observability](https://tokenfactory.nebius.com/observability?monitoring_model=all\&monitoring_cloud_account_id=all\&monitoring_region=all) Read more at [Observability section](/ai-models-inference/observability) ## Walkthrough on Operating Dedicated Endpoints See **Walkthrough on Operating Dedicated Endpoints** for deployment management, scaling, and operational best practices [YouTube video player](https://www.youtube.com/embed/4RlTHxu-CXo) # FAQ & Troubleshooting Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/faq ## Troubleshooting common errors | Status | Typical cause | Fix | | -: | :- | :- | | `401 Unauthorized` | Missing/invalid token | Ensure `Authorization: Bearer ...` is set and token is active | | `403 Forbidden` | Token lacks permission | Use a token with dedicated endpoint permissions | | `404 Not Found` | Endpoint not ready, wrong inference domain, or wrong `routing_key` | Wait for readiness; use correct inference base URL for the endpoint region; pass `routing_key` exactly as returned | | `409 Conflict` | Capacity or config conflict | Choose a supported GPU/region combo from templates or reduce max replicas | | `422 Unprocessable Entity` | Invalid payload values | Validate fields against templates (gpu types, flavors, regions, counts) | ## I finetuned a model and want to deploy it via Dedicated endpoint **Working with custom model weights** is currently in beta and available on request. If you’d like to deploy or work with custom fine-tuned model weights, [please contact our Support team to enable access](https://tokenfactory.nebius.com/?modals=contact-us) and guide you through the current setup process. Availability, supported configurations, and onboarding steps may vary during the beta period. ## Base model is not available in the list We strive to support the most popular model balancing variety and performance excellence. If the model you're looking for is absent in the list - [please contact our Support team](https://tokenfactory.nebius.com/?modals=contact-us) mentioning: * Exact model you're looking for with Hugging Face weights link * Your project and traffic details Our team will review your case and make a decision on model support ## Region is not available in the list We support several datacenters worldwide and the deployment options depends on capacity available. Sometimes the region and GPU type combination you're looking for may not be available. Still you can [contact our Sales team](https://nebius.com/services/token-factory/enterprise-grade-inference?_gl=1*mezsjw*_gcl_au*MTAwNTQwNDk0NC4xNzcwMjkyMzc3Ljk4MTA4NzYzMy4xNzc3NTM3MTg5LjE3Nzc1MzgzMzM.#token-factory-enterprise-sales-form) to plan a capacity reserve in a specific region. ### Can I bring down my Dedicated Endpoint when I don't have traffic so I don't overpay? Yes, use `enabled` parameter in request to enable/disable the endpoint. [Read more on this in Operations section.](/ai-models-inference/dedicated-endpoints/operating)\ Note that stopping the endpoint releases the capacity and you may not start it again if the capacity is taken by the other user and there are no free capacity at the moment. # Lifecycle & Readiness Status Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/lifecycle-and-status Dedicated Endpoints expose **two separate status types**: 1. **Lifecycle - What stage the deployment is in** 2. **Readiness - Whether the endpoint can currently serve traffic** This distinction helps separate deployment progress from actual availability. *** ## Lifecycle Status ### Starting Endpoint is being created or started.\ Provisioning is in progress, and traffic may not be available yet. ### Updating Endpoint is applying configuration changes.\ Traffic may continue, but capacity can temporarily degrade. ### Running Endpoint is deployed and expected to operate normally. ### Warning A deployment issue requires attention.\ The endpoint may still serve traffic depending on readiness. > [!NOTE] > > **If unresolved for more than 3 hours, contact support.** ### Stopping Stop was requested, but shutdown is still in progress. ### Stopped Endpoint is intentionally disabled. *** ## Readiness Status ### Not ready Endpoint cannot reliably serve requests. **Expected during:** Starting, Stopping, or Stopped ### Partially ready Endpoint can serve traffic, but below expected capacity.\ Some replicas are still starting, updating, or unavailable. > [!NOTE] > > **If unresolved for more than 3 hours, contact support.** ### Ready Endpoint is fully provisioned and ready for expected traffic. *** ## Common Status Examples | Lifecycle | Readiness | Meaning | | :- | :- | :- | | Starting | Not ready | Provisioning | | Starting | Partially ready | Serving, still scaling | | Updating | Ready | Serving normally during update | | Running | Ready | Fully operational | | Running | Partially ready | Degraded capacity | | Running | Not ready | Unexpected outage | | Error | Ready | Serving, but deployment issue exists | | Error | Not ready | Deployment failure | | Stopping | Partially ready | Shutting down | | Stopped | Not ready | Fully stopped | > [!NOTE] > > **Key Principle** > > Lifecycle is deployment state. Readiness is traffic-serving capability. > > **Use Readiness to decide whether to send traffic.** # Operating Dedicated Endpoint Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/operating ## Parameters Description | Field | Type | Required | Description | | :- | :- | :- | :- | | `name` | string | yes | Display name for the endpoint | | `description` | string | no | Optional description | | `model_name` | string | yes | Template model name (e.g. `openai/gpt-oss-120b`) | | `flavor_name` | string | yes | Template flavor (e.g. `base`, `fast`) | | `gpu_type` | string | yes | GPU type supported by the chosen template + flavor | | `gpu_count` | integer | yes | `gpu_count` per replica. Total maximum GPUs = `gpu_count × scaling.max_replicas` | | `region` | string | yes | `eu-north1`, `eu-west1`, `us-central1` | | `scaling.min_replicas` | integer | yes | Minimum replicas | | `scaling.max_replicas` | integer | yes | Maximum replicas | | `enabled` | boolean | no | Enable / Disable the endpoint. Stops the endpoint with freeing up replicas, or starts the endpoint. | ## Update Endpoint Configuration `PATCH` updates only the provided fields. ```http theme={null} PATCH /v0/dedicated_endpoints/{endpoint_id} ``` > [!NOTE] > > Endpoint's region config `region` cannot be updated after dedicated endpoint creation. ```python Python theme={null} import os, json, requests CONTROL_PLANE_BASE_URL = "https://api.tokenfactory.nebius.com" API_TOKEN = os.environ["API_TOKEN"] endpoint_id = "" payload = { "name": "GPT-20B Endpoint (updated)", "scaling": {"min_replicas": 2, "max_replicas": 4}, "enabled": True } r = requests.patch( f"{CONTROL_PLANE_BASE_URL}/v0/dedicated_endpoints/{endpoint_id}", headers={"Authorization": f"Bearer {API_TOKEN}"}, json=payload, ) r.raise_for_status() print(json.dumps(r.json(), indent=2)) ``` ```shellscript cURL theme={null} curl -sS -X PATCH \ "https://api.tokenfactory.nebius.com/v0/dedicated_endpoints/" \ -H "Authorization: Bearer $API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "scaling": { "min_replicas": 2, "max_replicas": 4 } }' ``` > [!TIP] > > Scaling changes may trigger provisioning of additional replicas. Plan for a short warm-up period where new replicas come online. ## List dedicated endpoints ```http theme={null} GET /v0/dedicated_endpoints ``` ```python Python theme={null} import os, json, requests CONTROL_PLANE_BASE_URL = "https://api.tokenfactory.nebius.com" API_TOKEN = os.environ["API_TOKEN"] r = requests.get( f"{CONTROL_PLANE_BASE_URL}/v0/dedicated_endpoints", headers={"Authorization": f"Bearer {API_TOKEN}"}, ) r.raise_for_status() print(json.dumps(r.json(), indent=2)) ``` ```shellscript cURL theme={null} curl -sS \ -H "Authorization: Bearer $API_TOKEN" \ "https://api.tokenfactory.nebius.com/v0/dedicated_endpoints" ``` ## Delete endpoint Deletes an endpoint permanently. ```http theme={null} DELETE /v0/dedicated_endpoints/{endpoint_id} ``` > [!WARNING] > > This is a permanent action. The GPUs associated with min\_replicas are released for other users. ```python Python theme={null} import os, requests CONTROL_PLANE_BASE_URL = "https://api.tokenfactory.nebius.com" API_TOKEN = os.environ["API_TOKEN"] endpoint_id = "" r = requests.delete( f"{CONTROL_PLANE_BASE_URL}/v0/dedicated_endpoints/{endpoint_id}", headers={"Authorization": f"Bearer {API_TOKEN}"}, ) print(r.status_code) r.raise_for_status() ``` ```shellscript cURL theme={null} curl -sS -X DELETE \ -H "Authorization: Bearer $API_TOKEN" \ "https://api.tokenfactory.nebius.com/v0/dedicated_endpoints/" ``` # Overview Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/overview **Dedicated endpoints provide isolated, configurable deployments** of supported models and their performance templates. Use the control plane to create and manage deployments, and the data plane to run inference through OpenAI-compatible APIs. With dedicated endpoints, you control: > [card] Region > > Choose where your deployment runs to optimize latency and meet data residency requirements. > [card] GPU configuration > > Select GPU type and GPUs per replica to match your performance and throughput needs. > [card] Autoscaling > > Set minimum and maximum replicas to automatically scale capacity with traffic. > [card] Lifecycle management > > Create, update, stop, and delete deployments as your workloads evolve. ## Key use cases: * predictable capacity * finetuned base model with custom weights * compliance / private infra * bigger control over deployment ## Dedicated vs Public Endpoints Comparison | Feature | Dedicated Endpoints | Public Serverless Endpoints | | :- | :- | :- | | Capacity | Capacity reserved for your organization | Shared multi-tenant capacity | | Rate limits | No standard rate limits; throughput depends on your deployed capacity | Dynamic rate limits apply | | Data residency | Deployment region is fixed and user-selected | Region may change based on available capacity | | Autoscaling | You control minimum and maximum replicas | Platform-managed with predefined limits | | Custom weights support | Supported for eligible models | Base models only | | Pricing | Per GPU/hour, billed with per-minute granularity | Per token | ## Learn more > [card] [Deploy via API](/ai-models-inference/dedicated-endpoints/deploy-api) > [card] [Deploy in UI](/ai-models-inference/dedicated-endpoints/deploy-ui) > [card] [FAQ & Troubleshooting](/ai-models-inference/dedicated-endpoints/faq) # Quickstart Source: https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/quickstart Dedicated endpoints can be deployed either: * **Through the UI** — best for first-time users and exploration * **Through the API** — best for automation, infrastructure-as-code, and repeatable workflows ### Before you begin: * Make sure billing enabled and you have enough balance * You have API key * Supported model choosen ### Choose your path: > [card] [Deploy in UI](https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/deploy-ui) > [card] [Deploy in API](https://docs.tokenfactory.nebius.com/ai-models-inference/dedicated-endpoints/deploy-api) # Function calling & Tools Source: https://docs.tokenfactory.nebius.com/ai-models-inference/function-calling Learn how to make models select functions to extend their capabilities Function calling allows you to enhance a model's capabilities by integrating it with external code, services, or APIs. You can define a set of functions—also referred to as tools—that the model can call. Based on the context provided in the conversation, the model can intelligently decide which functions to invoke and suggest appropriate arguments. This capability enables you to build more powerful agents that can: * Run custom code * Retrieve real-time data * Interact with third-party services * Connect to MCP servers * And perform other dynamic actions > [!NOTE] > > **Important:** The model **does not execute** the functions itself. Instead, it outputs tool invocation instructions in an [OpenAI-compatible function calling format](https://platform.openai.com/docs/guides/function-calling). You are responsible for parsing these outputs and executing the corresponding functions on your backend or client side. **1. Define Available Tools** Start by specifying the tools (functions) the model can use. Each tool is described using a JSON Schema that defines its name, input parameters, and expected data types. This schema informs the model how each tool should be invoked. **2. Model Determines Intent** When the model receives a user query, it analyzes the intent and decides how to respond. Based on the context and the tools available, it may: * Respond conversationally, or * Propose a function call by selecting a relevant tool and filling in the required arguments according to the schema. **3. Execute and Iterate** If a function call is proposed, your system is responsible for executing the function with the provided arguments. You then pass the function’s output back to the model as part of the next prompt. This allows the conversation to continue seamlessly, with the model incorporating the function result into its response or triggering further tool use. ## Limitations The `tool_choice` parameter controls how the model selects which function (tool) to use. It determines whether the model should choose a tool automatically or follow an explicit instruction. Supported values include: * `"auto"`\ The model automatically selects the most appropriate function based on the context of the prompt. This is the default behavior and is useful for most use cases. * **Explicit Function Call**\ You can instruct the model to call a specific function using the following structure: ```json theme={null} { "type": "function", "function": { "name": "read_file" } } ``` This forces the model to call the `read_file` function regardless of context, overriding its own tool selection logic. ## API Example ```python Python expandable theme={null} import json import os from pydantic import BaseModel, Field from typing import Literal from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.getenv("NEBIUS_API_KEY") ) model = "meta-llama/Meta-Llama-3.1-8B-Instruct-fast" class GetCurrentWeatherParams(BaseModel): city: str = Field( ..., description="The city to find the weather for, e.g. 'San Francisco'" ) state: str = Field( ..., description=( "The two-letter abbreviation for the state that the city is in, " "e.g. 'CA' for California" ) ) unit: Literal['celsius', 'fahrenheit'] = Field( ..., description="The unit to fetch the temperature in" ) tools = [{ "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": GetCurrentWeatherParams.model_json_schema() } }] messages = [ { "role": "user", "content": "Hi! How are you doing today?" }, { "role": "assistant", "content": "I'm doing well! How can I help you?" }, { "role": "user", "content": ( "Can you tell me what the temperature will be in Dallas, " "in Fahrenheit?" ) } ] chat_completion = client.chat.completions.create( messages=messages, model=model, tools=tools, tool_choice={ "type": "function", "function": { "name": "get_current_weather" } } ) messages.append({ "role": "assistant", "tool_calls": chat_completion.choices[0].message.tool_calls }) # Simulate a tool call def get_current_weather(city: str, state: str, unit: 'str'): return ( "The weather in Dallas, Texas is 85 degrees Fahrenheit. " "It is partly cloudy, with highs in the 90's." ) available_tools = {"get_current_weather": get_current_weather} completion_tool_calls = chat_completion.choices[0].message.tool_calls for call in completion_tool_calls: tool_to_call = available_tools[call.function.name] args = json.loads(call.function.arguments) result = tool_to_call(**args) print(result) messages.append({ "role": "tool", "content": result, "tool_call_id": call.id, "name": call.function.name }) ``` ```javascript JavaScript expandable theme={null} import OpenAI from 'openai'; import { z } from 'zod'; import { zodResponseFormat } from 'openai/helpers/zod'; // 1. Define a schema using Zod. You can also define a JSON Schema directly; // see details after this code example const Weather = z.object({ city: z.string(), state: z.string(), temperature: z.enum(["celsius", "fahrenheit"]), }); // 2. Add the schema to your request const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1/", apiKey: process.env.NEBIUS_API_KEY, }); const tools = [ { type: "function", function: { name: "get_weather", parameters: zodResponseFormat(Weather, "weather").json_schema.schema, }, } ]; const response = await client.chat.completions.create({ model: "meta-llama/Meta-Llama-3.1-8B-Instruct-fast", messages: [{"role": "user", "content": "Can you tell me what the temperature will be in Dallas, in Fahrenheit?"}], tools, }); // 3. Work with the JSON output console.log(response.choices[0].message.tool_calls); ``` Messages array with response: ```json expandable theme={null} [ { "role": "user", "content": "Hi! How are you doing today?" }, { "role": "assistant", "content": "I'm doing well! How can I help you?" }, { "role": "user", "content": "Can you tell me what the temperature will be in Dallas, in Fahrenheit?" }, { "role": "assistant", "tool_calls": [ { "id": "chatcmpl-tool-99a7259c139e4aa986549d07cde8df8f", "type": "function", "function": { "name": "get_current_weather", "arguments": "{ \"city\" : \"Dallas\" , \"state\": \"Texas\", \"unit\": \"fahrenheit\" }" } } ] }, { "role": "tool", "content": "The weather in Dallas, Texas is 85 degrees fahrenheit. It is partly cloudy, with highs in the 90's.", "tool_call_id": "chatcmpl-tool-99a7259c139e4aa986549d07cde8df8f", "name": "get_current_weather" } ] ``` ## Try it in our Cookbook > [card] [Function & Tool Calling Cookbook](https://github.com/nebius/token-factory-cookbook/tree/main/tool-calling) ## **Function calling** in Playground You can explore Function Calling capabilities of models directly in the Playground: 1. **Go to the "Model Parameters" section.** 2. In the **"Function calling" section add function description** 3. **Enter your prompt and run it** to test whether the model returns the expected function selection for your use case. # Structured output & JSON Source: https://docs.tokenfactory.nebius.com/ai-models-inference/json Learn how to get structured output from our text models ## Overview By default, a text generation model responds to your requests with a text in natural language. You can also force the model to respond with JSON instead, which makes it easier to work with outputs programmatically in your application. For example, you can tell a model the name of an actor or actress and get a response with details of a film they have starred in, in a format like this: ```json theme={null} { "title": "The Shining", "year": 1980, "director": "Stanley Kubrick", "cast": ["Jack Nicholson", "Shelley Duvall", "Danny Lloyd"], } ``` Use `response_format`parameter to get JSON output. Depending on the settings in your request, the response can be: * **JSON schema following.** Follows the specific schema you provide - `{"type": "json_schema"}` in `response_format `parameter. * **Arbitrary JSON object.** Forces arbitrary JSON output, the model will decide on the schema by itself `{"type": "json_object"}` in `response_format `parameter. > [!NOTE] > > **Supported models**\ > Some models are better in providing JSON due to their training data or our inference engine limitations. Use `JSON mode` tag in on a model card to find a model with structured output supported. **1. Choose response format type** Select between strict `"json_schema"` and arbitrary `"json_object"` **2. Optionally: provide JSON schema** Provide the schema in a [JSON Schema Specification](https://json-schema.org/specification) compliant format. **3. Add instructions to the system or user prompt** It's always better to provide the instruction to follow JSON output and the schema to your model's system or user prompt to increase output quality and consistency **4. Test several models** Different models has different structured output capabilities. Always test and compare a few to obtain the best result ## JSON Schema following JSON that follows a schema provided in your request. Make a request to the Nebius Token Factory API with `{"type": "json_schema"}` in `response_format `and provide desirable schema in a [JSON Schema Specification](https://json-schema.org/specification) compliant format. > [!TIP] > > Many practical tests show that it's always better to provide the schema both in text prompt for the model and`"json_schema"`**parameter** ```python Python expandable theme={null} import os import json from openai import OpenAI from typing import List, Literal from pydantic import BaseModel # 1. Define a schema using Pydantic's `BaseModel`. You can also define # a JSON Schema directly; see details after this code example class Film(BaseModel): title: str year: int director: str cast: List[str] genre: Literal[ "drama", "thriller", "sci-fi", "comedy", "horror", "fantasy" ] # 2. Add the schema to your request client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) completion = client.chat.completions.create( model="Qwen/Qwen3-235B-A22B", response_format={ "type": "json_schema" "json_schema": Film.model_json_schema() } messages=[ { "role": "system", "content": ( "I will give you an actor or actress, and you will respond " "with details of a real film they have starred in, according " "to the provided structure." ) }, { "role": "user", "content": "Jack Nicholson" } ], ) # 3. Work with the JSON output or a refusal output = completion.choices[0].message if output.refusal: # Handle refusal print(output.refusal) elif output.content: try: output_json = json.loads(output.content) print(output_json) print("Film: {} ({})".format(output_json['title'], output_json['year'])) # etc. except Exception as e: # Handle possible exceptions, e.g. invalid JSON print(e) pass ``` ```bash cURL expandable theme={null} # 1. Define a JSON Schema export SCHEMA=' { "type": "object", "properties": { "title": {"type": "string"}, "year": {"type": "integer"}, "director": {"type": "string"}, "cast": { "type": "array", "items": {"type": "string"} }, "genre": { "enum": [ "drama", "thriller", "sci-fi", "comedy", "horror", "fantasy" ] } }, "required": ["title", "year", "director", "cast", "genre"] } ' # 2. Add the schema to your request export OUTPUT=$(curl 'https://api.tokenfactory.nebius.com/v1/chat/completions' \ -X 'POST' \ -H 'Content-Type: application/json' \ -H 'Accept: */*' \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ --data-binary ' { "model": "mistralai/Mistral-Nemo-Instruct-2407", "messages": [ { "role": "system", "content": "I will give you an actor or actress, and you will respond with details of a real film they have starred in, according to the provided structure." }, { "role": "user", "content": "Jack Nicholson" } ], "response format": { "type": "json_schema" "json_schema": '"$SCHEMA"' } } ' ) # 3. Work with the JSON output or a refusal echo $OUTPUT | jq ' .choices[0].message.refusal // (.choices[0].message.content | fromjson | .title) ' ``` ```javascript JavaScript expandable theme={null} import OpenAI from "openai"; import { z } from "zod"; import { zodResponseFormat } from "openai/helpers/zod"; // 1. Define a schema using Zod. You can also define a JSON Schema directly; // see details after this code example const Film = z.object({ title: z.string(), year: z.number(), director: z.string(), cast: z.array(z.string()), genre: z.enum(["drama", "thriller", "sci-fi", "comedy", "horror", "fantasy"]), }); // 2. Add the schema to your request const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1/", apiKey: process.env.NEBIUS_API_KEY, }); client.chat.completions.create({ model: "openai/gpt-oss-120b", messages: [ { role: "system", content: "I will give you an actor or actress, and you will respond with details of a real film they have starred in, according to the provided structure.", }, { role: "user", content: "Jack Nicholson", }, ], response_format: zodResponseFormat(Film, "film") }) // 3. Work with the JSON output or a refusal .then((completion) => { const output = completion.choices[0].message; if (output.refusal) { // Handle refusal console.log(output.refusal); } else if (output.content) { try { const output_json = JSON.parse(output.content); console.log(`Film: ${output_json.title} (${output_json.year})`); // etc. } catch (e) { // Handle possible exceptions, e.g. invalid JSON console.log("An error occurred: ", e.message); } } }); ``` Example of a valid JSON schema: ```json expandable theme={null} { "name": "meal_nutrition", "schema": { "type": "object", "properties": { "meal_name": { "type": "string", "description": "Name or description of the meal", "minLength": 1 }, "serving_size_g": { "type": "number", "description": "Serving size in grams", "minimum": 1 }, "nutrients": { "type": "object", "description": "Macronutrient and micronutrient content per serving", "properties": { "calories": { "type": "number", "description": "Energy in kilocalories (kcal)", "minimum": 0 }, "protein_g": { "type": "number", "description": "Protein in grams", "minimum": 0 }, "carbohydrates_g": { "type": "number", "description": "Carbohydrates in grams", "minimum": 0 }, "fat_g": { "type": "number", "description": "Total fat in grams", "minimum": 0 }, "fiber_g": { "type": "number", "description": "Dietary fiber in grams", "minimum": 0 }, "sugars_g": { "type": "number", "description": "Sugars in grams", "minimum": 0 }, "sodium_mg": { "type": "number", "description": "Sodium in milligrams", "minimum": 0 } }, "required": [ "calories", "protein_g", "carbohydrates_g", "fat_g", "fiber_g", "sugars_g", "sodium_mg" ], "additionalProperties": false } }, "required": [ "meal_name", "serving_size_g", "nutrients" ], "additionalProperties": false }, "strict": true } ``` ## Arbitrary JSON object The model will produce a valid JSON object without following any specific schema.\ Make a request to the Nebius Token Factory API with `{"type": "json_object"}` in `response_format`: ```python Python expandable theme={null} import os import json from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) completion = client.chat.completions.create( model="openai/gpt-oss-120b", # 1. Instruct the model to produce JSON. In this example, we do it # in the system prompt; you can do it in a user message instead messages=[ { "role": "system", "content": ( "I will give you an actor or actress, and you will respond " "with details of a real film they have starred in, using JSON " "as the format." ) }, { "role": "user", "content": "Jack Nicholson" } ], # 2. Set the response format to `json_object` response_format={ "type": "json_object" } ) # 3. Work with the JSON output (it should be valid but is not guaranteed # to have any predetermined fields) or a refusal output = completion.choices[0].message if output.refusal: # Handle refusal print(output.refusal) elif output.content: try: output_json = json.loads(output.content) print(output_json) except Exception as e: # Handle possible exceptions, e.g. invalid JSON print(e) pass ``` ```bash cURL expandable theme={null} # 1. Instruct the model to produce JSON. In this example, we do it in the system prompt; # you can do it in a user message instead # 2. Set the response format to `json_object` export OUTPUT=$(curl 'https://api.tokenfactory.nebius.com/v1/chat/completions' \ -X 'POST' \ -H 'Content-Type: application/json' \ -H 'Accept: */*' \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ --data-binary ' { "model": "mistralai/Mistral-Nemo-Instruct-2407", "messages": [ { "role": "system", "content": "I will give you an actor or actress, and you will respond with details of a real film they have starred in, using JSON as the format." }, { "role": "user", "content": "Jack Nicholson" } ], "response_format": { "type": "json_object" } } ' ) # 3. Work with the JSON output (it should be valid but is not guaranteed # to have any predetermined fields) or a refusal echo $OUTPUT | jq ' .choices[0].message.refusal // (.choices[0].message.content | fromjson) ' ``` ```javascript JavaScript expandable theme={null} import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https://api.tokenfactory.nebius.com/v1/', apiKey: process.env.NEBIUS_API_KEY, }); client.chat.completions.create({ model: "mistralai/Mistral-Nemo-Instruct-2407", // 1. Instruct the model to produce JSON. In this example, we do it in the system prompt; // you can do it in a user message instead messages: [ { role: "system", content: "I will give you an actor or actress, and you will respond with details of a real film they have starred in, using JSON as the format.", }, { role: "user", content: "Jack Nicholson", }, ], // 2. Set the response format to `json_object` response_format: { type: "json_object", }, }) // 3. Work with the JSON output (it should be valid but is not guaranteed // to have any predetermined fields) or a refusal .then((completion) => { const output = completion.choices[0].message; if (output.refusal) { // Handle refusal console.log(output.refusal); } else if (output.content) { try { const output_json = JSON.parse(output.content); console.log(output_json); } catch (e) { // Handle possible exceptions, e.g. invalid JSON console.log("An error occurred: ", e.message); } } }); ``` > [!TIP] > > Use **JSON schema instead of JSON objects** whenever you need **strict JSON structure** ## Try it in our Cookbook > [card] [Strucrured output - Cookbook](https://github.com/nebius/token-factory-cookbook/blob/main/guided_json.ipynb) ## Structured output in Playground You can explore the structured output capabilities of models directly in the Playground: 1. **Go to the "Model Parameters" section.** 2. ****`In the "Response format" dropdown, select JSON object/schema.`**** 3. *(Optional)* **Provide a strict JSON schema** if you want the model to follow a specific structure. 4. **Enter your prompt and run it** to test whether the model returns the expected JSON output for your use case. # Inference Observability Source: https://docs.tokenfactory.nebius.com/ai-models-inference/observability Inference Observability provides real-time and historical metrics for your inference workloads, including latency, throughput, scaling, and error rates. It helps you debug performance issues, benchmark models, and understand capacity behavior of dedicated or public endpoints. You can access Observability from: **Navigation Bar → Inference → Observability** > [!NOTE] > > Observability Metrics are **only accessible for Dedicated Endpoints inference** ## What you can do with Observability Inference Observability is designed to help you answer practical engineering questions - debug, optimise and operate: * When and why did latency increase? * Are errors coming from my requests or infrastructure? * Compare performance across endpoints * Understand token throughput and response times * Monitor scaling behavior and capacity ## Metrics available ### Traffic These metrics describe how much load your endpoint is handling and understand traffic spikes, prompt size trends, throughput limits | Metric | Description | | :- | :- | | Requests per minute | Number of requests sent to the API | | Input tokens per minute | Incoming tokens processed | | Output tokens per minute | Tokens generated by models | | Input tokens per request | Distribution of prompt sizes | | Output tokens per request | Distribution of response sizes | | KV-cache hit rate | Percentage of prefix cache lookups that were served from cache. Includes both local and external cache hits. | ### Latency Latency metrics describe how long requests take at different stages. This helps identify model warmup effects, queueing or scaling delays, slow generation behavior. Latency charts display percentiles: `p50`, `p90`, `p99` > [!NOTE] > > TTFT (Time to First Token) metric is measured across **streaming requests only** | Metric | Description | | :- | :- | | End-to-end latency | Time from request sent to full response received | | TTFT (Time to First Token) | Time until the first token is generated. Measured across streaming requests only. | | Output speed (TPS) | Tokens generated per second | ### Autoscaling and Capacity These metrics help explain why latency increases under load and whether scaling is working as expected, as well as if replicas are well utilized with the workload. Some capacity metrics may be hidden depending on your pricing model. | Metric | Description | | :- | :- | | Active replicas | Currently running replicas | | Active GPUs | Number of active GPUs at the moment | | GPU utilisation, avg | This metric represents the fraction of time the GPU was active. Average across all replicas. | | GPU utilisation, busiest | This metric represents the fraction of time the GPU was active. Value for the busiest replica. | ### Errors and success rate | Metric | Description | | :- | :- | | Error rate by status code | Percentage of failed requests grouped by HTTP status | Typical error classes: * 4xx — invalid requests or limits * 429 — rate limiting or capacity limits * 5xx — internal errors This helps you quickly see: * Whether failures come from traffic patterns * Whether rate limits are reached * Whether infrastructure issues occurred > [!NOTE] > > Looking for an incident history or having a down time? You can also check Token Factory section at [Nebius Cloud status page](https://status.nebius.com) *** ## Filters and dimensions You can filter metrics to narrow down specific traffic patterns. This makes it possible to compare regions, projects and benchmark endpoints. Filters apply to all charts simultaneously. | Filter | Purpose | | :- | :- | | Time range | Analyze recent or historical traffic | | Model endpoint | Compare endpoints | | Project | Analyze per-project usage | | API key | Identify individual clients | | Region | Compare cross-region performance | | Error code | Debug failures | | Prompt length | Compare short vs long prompts | | Latency range | Focus on slow requests | *** ## Exporting metrics and API access The Monitoring service provides metrics in Nebius Token Factory in two forms: * Preconfigured [dashboards](https://tokenfactory.nebius.com/observability) in the web UI show key metrics for each resource. * The API to metrics is available via [Prometheus](https://docs.nebius.com/observability/metrics/prometheus) and [Grafana®](https://docs.nebius.com/observability/metrics/grafana) integrations. You can filter and visualize the metrics the way you want with API integration. > [card] [Observability API integrations](https://docs.tokenfactory.nebius.com/ai-models-inference/observability-api-integrations) > > Go to Observability API access to learn more how to integrate with Prometheus and Grafana *** ## How metrics are calculated Metrics are aggregated in short windows and refreshed continuously. The aggregation window depends on the timeline choosen. Typical characteristics: * Near-real-time updates (usually within tens of seconds) * Percentile-based latency statistics * Rolling aggregation windows depending on the time scale choosen > [!NOTE] > > Observability dashboards are intended for operational debugging and performance analysis, not billing reconciliation. *** ## Access control Observability is a project-nested entity and follows project permissions. | Role | Access | | :- | :- | | Organization Admin | View all projects and their observability | | Organisation Billing Manager | No access to observability | | Project Admin | View project observability | | Project Member | View project observability | *** ## FAQ ### Data retention and deletion Observability data is tied to the project lifecycle. When a project is deleted associated observability data is automatically removed. ### Regions and data locality Projects may contain endpoints in multiple regions. Metrics are collected in the region where inference runs, but eventually stored at `eu-north`region. Filters allow you to compare endpoints data in different regions # Observability API integrations Source: https://docs.tokenfactory.nebius.com/ai-models-inference/observability-api-integrations ## How to connect Prometheus > [!NOTE] > > Prometheus can only show a limited amount of monitoring data. If you have a large infrastructure, consider connecting a data source in Grafana® instead 1. Issue a [static API key in Nebius Token Factory UI](https://tokenfactory.nebius.com/project/api-keys). 2. [Download the latest release](https://prometheus.io/download) of Prometheus for your platform. 3. Extract the contents and switch to the folder with Prometheus: ``` tar xvfz prometheus-***.tar.gz cd prometheus-*** ``` 4. Create the `prometheus.yml` configuration file that configures Prometheus to retrieve Monitoring metrics. Use one of the following configurations depending on your Prometheus version: ```yaml Prometheus 3 theme={null} scrape_configs: - job_name: 'Export time series from Nebius Monitoring' honor_labels: true scrape_interval: 15s scheme: https metrics_path: '/projects//service-provider/prometheus/federate' params: match[]: - '{__name__=~".+"}' bearer_token: '' static_configs: - targets: - 'read.monitoring.api.nebius.cloud' ``` ```yaml Prometheus 2 theme={null} scrape_configs: - job_name: 'Export time series from Nebius Monitoring' honor_labels: true scrape_interval: 15s scheme: https metric_name_validation_scheme: legacy scrape_protocols: - OpenMetricsText0.0.1 metrics_path: '/projects//service-provider/prometheus/federate' params: match[]: - '{__name__=~".+"}' bearer_token: '' static_configs: - targets: - 'read.monitoring.api.nebius.cloud' ``` In this file, change the following parameters: * `bearer_token`: enter the static key that you [got earlier.](https://tokenfactory.nebius.com/project/api-keys) * `metrics_path`: specify your project ID in the URL. To get the project ID, go to the [Nebius Token Factory UI →  Project settings](https://tokenfactory.nebius.com/project/). Under the project's name, click  → **Copy project ID**. * `match[]`: optionally specify which data Prometheus collects by filtering for labels or metric names. For example, to collect only metrics with the `disk` prefix, set the following value: ```yaml theme={null} match[]: - '{__name__=~"^disk.*"}' ``` * `scrape_interval`: you can change the interval, but the recommended interval is no less than 15 seconds. Start Prometheus: ``` ./prometheus --config.file=prometheus.yml ``` ### How to connect Grafana data source To view visualized metrics in Grafana dashboards, connect Grafana to Monitoring and query the data by using [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/). 1. Make sure that you have Grafana available, in any of these ways: * [Install Grafana on your local machine](https://grafana.com/docs/grafana/latest/setup-grafana/installation/). * [Create an account in Grafana Cloud](https://grafana.com/auth/sign-up/create-user). 2. Open Grafana in your browser. 3. In the side menu, select **Connections** → **Data sources**. 4. In the top right corner, click **Add new data source**. 5. Select **Prometheus**. 6. In the Prometheus configuration, enter the following settings: * **Connection** → **Prometheus server URL**: `https://read.monitoring.api.nebius.cloud/projects//service-provider/prometheus`. Specify your project ID in the URL. You can get it on the [Project settings](https://console.nebius.com/settings) page of the web console. * **Authentication** → **HTTP headers**: click **Add header** and enter `Authorization` and the value of the static key that you [got earlier](https://docs.nebius.com/observability/metrics/grafana#prerequisites). 7. Click **Save and test**. If Prometheus is connected successfully, you should see the "Successfully queried the Prometheus API" message. # Overview Source: https://docs.tokenfactory.nebius.com/ai-models-inference/overview Get an inference engine overview With Nebius Token Factory, you can test and deploy open-source AI models for generative language processing tasks, such as building virtual assistants and chatbots. ## Available models Nebius Token Factory supports the following model types: > [card] [Text-to-text](https://tokenfactory.nebius.com/endpoints?modality=text2text) > [card] [Embedding](https://tokenfactory.nebius.com/endpoints?modality=embedding) > [card] [Vision](https://tokenfactory.nebius.com/endpoints?modality=image2text) See the full list of available models in [Nebius Token Factory](http://tokenfactory.nebius.com/). ## Model flavors Inference performance is determined by how the endpoint is configured - balancing: * Batch size * GPU type (L40, H100, H200, B200) * GPU count * Inference-time optimizations (e.g., speculative decoding) To cover common usage patterns, **two model flavors are available:** > [card] Base > [card] Fast Both deliver identical model outputs. Differences lie in token pricing, latency, and the level of applied optimizations. The Fast flavor uses smaller batch sizes, increased compute allocation, and techniques such as speculative decoding to reduce latency and improve responsiveness. To use the Fast flavor, append `-fast` to the model name in the [API](https://docs.tokenfactory.nebius.com/api-reference/introduction). These flavors are curated based on infrastructure and model-level expertise. For more specific needs - such as strict latency budgets, cost-efficiency targets, or high-throughput applications - endpoint configurations can be tailored to the customer use case through direct collaboration with the sales and solutions engineering team. ## Inference optimisations Our LLM inference service employs a range of optimization techniques to increase throughput while maintaining model quality. These techniques include: > [card] KV Cache > > A caching mechanism that stores frequently accessed key-value pairs, reducing the number of computations required. > [card] Paged Attention > > A memory-management technique that partitions each request's KV cache into fixed-size blocks. The blocks can be stored non-contiguously and allocated on demand, reducing memory fragmentation. > [card] Flash Attention > > A modified attention mechanism that reduces the number of computations required for attention calculations. > [card] Quantization > > A technique that reduces the precision of model weights and activations, decreasing memory usage and computation. > [card] Continuous Batching > > A method that batches multiple input sequences together, increasing throughput by reducing the overhead of individual requests. > [card] Context Caching > > A caching mechanism that stores the context (i.e., the output of previous layers) for each input sequence, reducing the number of computations required. > [card] Speculative decoding > > An advanced technique that uses auxiliary models to pre-generate likely next tokens. The main model verifies these predictions, reducing the number of forward passes required and improving throughput without degrading output quality. ### **Impact on model quality** Our optimization techniques are designed to minimize the impact on model quality. Through extensive testing and evaluation, we have found that our optimized models maintain approximately 99% of the original model's quality. This means that the optimized models produce nearly identical results to the original models, with only minor differences in output.The quality impact of each optimization technique is carefully evaluated and monitored to ensure that the cumulative effect of all techniques does not compromise the overall quality of the model. Our goal is to provide a high-throughput inference service that delivers accurate and reliable results, while minimizing the computational resources required. ## Generation parameters You can tune the model’s **generation parameters** to adapt outputs for your use case and optimize performance or cost. Nebius Token Factory supports most of OpenAI compatible generation parameters. Supported parameters vary by interface: * **Playground** - Supports the most commonly used parameters. * **API** - Supports the full set of vLLM parameters. To view additional model parameters, please refer to this [section](https://docs.tokenfactory.nebius.com/api-reference/examples/list-of-models). # UI & Playground Source: https://docs.tokenfactory.nebius.com/ai-models-inference/playground The [**Playground**](https://tokenfactory.nebius.com/playground) in Nebius Token Factory lets you experiment with available AI models through a web interface — no coding required. ## Model card In the Nebius Token Factory UI, each **model card** displays key parameters for the model: * **Input tokens** — Price per token included in an API request, shown in USD per million tokens. * **Output tokens** — Price per token generated by the model (returned in the API response), in USD per million tokens. * **Tokens per second** — Approximate generation speed of the model in tokens per second. Actual performance may vary. * **Quality** — MMLU score reported by the model provider. To view an extended list of model parameters via the API, send a request to the **List models** endpoint with the query parameter `verbose=true`. ## Using the playground 1. On the [**Models**](https://tokenfactory.nebius.com/) page, find the model you want to try and click **Go to playground** on its card. 2. Under **System prompt**, enter instructions that guide the model’s behavior. You can add **few-shot examples** to demonstrate the desired output format. 3. Start chatting with the model and refine your setup as needed. Saving your setup: * **Export as code** — Click **View code** in the left panel to copy your model setup (including the chat) for use in your application. * **Save as a prompt preset** — Click **Save preset** in the left panel to store your setup for later use or sharing. ## **Compare setups** To work with two model setups side by side, click **Compare**. This will open two chat windows where you can submit inputs for both setups at the same time. You can also synchronize model parameters and system prompts between the two chats. To do this, click **Copy to right** or **Copy to left** in the **Parameters** menu or next to a system prompt. > [!NOTE] > > If the models have different sets of parameter, synchronization may not be possible. To go back to the single-model mode, close one of the chats. The remaining chat will keep its setup and history. ## **View code** You can copy your model setup and chat as code to continue working with them in your application: * Single-model mode: next to **Compare**, click → **View code**. * Compare mode: Next to **Parameters**, click icon → in dropdown list select → **View code**. # Rate Limits & Scaling Source: https://docs.tokenfactory.nebius.com/ai-models-inference/rate-limits Learn how rate limiting of requests works and what are the scaling rules Nebius AI Inference is elastic by design. When you gradually increase your workload we scale the capacity with you. Most teams on Startup Tier never need to think about rate limits—but when you start pushing tens of thousands of requests per minute it helps to know how the platform behaves. Sudden bursts of AI Model traffic may be subject to throttling. This page explains the **dynamic rate‑limiting** system, how it auto‑scales, and the knobs you can turn when you need more headroom. > [!TIP] > > **Need unlimited throughput?**\ > If you have sustained workloads that dwarf the standard limits, [reach out to us to upgrade to the Enterprise Tier](https://nebius.com/?_gl=1*1ni0ub9*_gcl_au*OTY2MTI0ODU5LjE3NTA4MzkxODkuOTQxMDE3MTg3LjE3NTEwMTgyMjYuMTc1MTAxODIyNg..#ai-contact-form). Enterprise removes the soft caps described below and gives you dedicated capacity plus an SLA. ### How it works Key idea – Limits are dynamic. If your app stays close to the ceiling, we automatically raise it. If traffic falls off, we scale it back. Every user is provided with a default rate limit cap. This limit grows automatically when you consistently operate close to your capacity and current limit. > [!TIP] > > You can find the defaults at Rate Limits section of [Nebius Token Factory](https://tokenfactory.nebius.com/project/rate-limits) We evaluate usage in rolling 15‑minute buckets: * **Scale‑up rule** – When **average** usage in a 15‑minute window ≥ 80 % of the current limit, the limit for the *next* window increases by 20 % (`× 1.2`). * **Scale‑down rule** – When average usage in a 15‑minute window ≤ 50 %, the limit for the next window decreases by one‑third (`÷ 1.5`). * **Hard ceiling** – The limit can grow to **20 ×** your base allocation. Beyond that we require an Enterprise plan. Visual example, assuming you continue to drive ≥ 80 % utilisation each window: | **Window** | **Scale factor** | **RPM limit** | **TPM limit** | | :- | :- | :- | :- | | Baseline | `1.00×` | 60 | 400,000 | | + 15 min | `1.20×` | 72 | 480,000 | | + 30 min | `1.44×` | 86 | 576,000 | | + 1 h | `2.07×` | 124 | 828,000 | | + 2 h | `4.30×` | 258 | 1,720,000 | ### Monitoring your headroom and handling 429s Your current rate limits are always visible in the API response headers, which are detailed further down. If you exceed the active limit you will receive **HTTP 429**. To avoid this, you can track your consumption against your limits using the `x-ratelimit-remaining-requests` and `x-ratelimit-remaining-tokens` response headers. > [!TIP] > > **Use Batch API for async workloads - it has significantly higher limits. Read more** ### **Over-the-Limit Processing** In some cases, requests that exceed your rate limit may still be processed. This occurs when the system has spare capacity available, and your request can be handled with a lower priority without affecting other users. These responses include: ```text theme={null} x-ratelimit-over-limit: yes ``` This indicates that while your request was successful, you are over your nominal limit, and subsequent requests may be throttled if you continue to exceed your quota. Treat this as an early warning—subsequent calls may be throttled. ### Rate Limit Response Headers Here's a simple explanation of response headers you can use to track you limits quotas: **Description of Rate Limits response headers** | Header | Description | | :- | :- | | `x-ratelimit-limit-requests` | The maximum number of requests that are permitted per minute. | | `x-ratelimit-limit-tokens` | The maximum number of tokens that are permitted per minute. | | `x-ratelimit-remaining-requests` | The remaining number of requests that are permitted before exhausting the rate limit. | | `x-ratelimit-remaining-tokens` | The remaining number of tokens that are permitted before exhausting the rate limit. Note that the limit is replenished continuously. If your usage is sustainably below the rate limit, this number will hover near its maximum value. | | `x-ratelimit-reset-requests` | The time in seconds until the rate limit (based on requests) resets. | | `x-ratelimit-reset-tokens` | The time in seconds until the rate limit (based on tokens) resets. | | `x-ratelimit-dynamic-scale-requests` | The current dynamic scale factor applied to your request rate limit. | | `x-ratelimit-dynamic-scale-tokens` | The current dynamic scale factor applied to your token rate limit. | | `x-ratelimit-dynamic-period-remaining` | The time in seconds until the next dynamic rate limit adjustment. | | `x-ratelimit-dynamic-period-usage-requests` | Your average request usage in the current adjustment period, as a percentage. | | `x-ratelimit-dynamic-period-usage-tokens` | Your average token usage in the current adjustment period, as a percentage. | | `x-ratelimit-over-limit` | Set to "yes" if a request that is over the limit is processed. This happens when the system has spare capacity, and the request is handled with a lower priority. | | `Retry-After` | The time in seconds to wait before making another request if the rate limit is exceeded. | # Cancel a multipart upload Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/cancel-a-multipart-upload https://api.tokenfactory.nebius.com/openapi.json post /v1/datasets/uploads/{upload_id}/cancel Cancel a multipart upload # Complete a multipart upload, create a new dataset Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/complete-a-multipart-upload-create-a-new-dataset https://api.tokenfactory.nebius.com/openapi.json post /v1/datasets/uploads/{upload_id}/complete Complete a multipart upload # Create a dataset by uploading data Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/create-a-dataset-by-uploading-data https://api.tokenfactory.nebius.com/openapi.json post /v1/datasets Create a dataset # Create a new multipart upload for a dataset Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/create-a-new-multipart-upload-for-a-dataset https://api.tokenfactory.nebius.com/openapi.json post /v1/datasets/uploads Create a new upload # Delete a dataset Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/delete-a-dataset https://api.tokenfactory.nebius.com/openapi.json delete /v1/datasets/{dataset_id} Delete a dataset # Filter operations by attributes Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/filter-operations-by-attributes https://api.tokenfactory.nebius.com/openapi.json get /v1/operations List operations # Get a list of datasets in project Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-a-list-of-datasets-in-project https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets List datasets # Get dataset info Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-dataset-info https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets/{dataset_id} Get dataset info # Get dataset query template Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-dataset-query-template https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets/{dataset_id}/query_templates Get dataset query template # Get information about a multipart upload Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-information-about-a-multipart-upload https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets/uploads/{upload_id} Get upload information # Get operation errors Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-operation-errors https://api.tokenfactory.nebius.com/openapi.json get /v1/operations/{operation_id}/errors Get errors for a given failed operation. # Get operation info by id Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-operation-info-by-id https://api.tokenfactory.nebius.com/openapi.json get /v1/operations/{operation_id} Get operation info # Get operation results Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/get-operation-results https://api.tokenfactory.nebius.com/openapi.json get /v1/operations/{operation_id}/results Get checkpoints for a fine-tuning operation or the output file id for a dataset-to-file operation. # List parts of a multipart upload Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/list-parts-of-a-multipart-upload https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets/uploads/{upload_id}/parts List upload parts # Patch dataset info Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/patch-dataset-info https://api.tokenfactory.nebius.com/openapi.json patch /v1/datasets/{dataset_id} Partially update dataset info # Read dataset content Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/read-dataset-content https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets/{dataset_id}/content Get dataset content # Read dataset content as csv or jsonl Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/read-dataset-content-as-csv-or-jsonl https://api.tokenfactory.nebius.com/openapi.json get /v1/datasets/{dataset_id}/export Export dataset content # Run operation Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/run-operation https://api.tokenfactory.nebius.com/openapi.json post /v1/operations Create an operation # Stop operation by id Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/stop-operation-by-id https://api.tokenfactory.nebius.com/openapi.json post /v1/operations/{operation_id}/cancel Cancel operation # Upload a new part for a multipart upload Source: https://docs.tokenfactory.nebius.com/api-reference/datasets/upload-a-new-part-for-a-multipart-upload https://api.tokenfactory.nebius.com/openapi.json post /v1/datasets/uploads/{upload_id}/parts Upload a new part # Create Dedicated Endpoint Source: https://docs.tokenfactory.nebius.com/api-reference/dedicated-endpoints/create-dedicated-endpoint https://api.tokenfactory.nebius.com/openapi.json post /v0/dedicated_endpoints # Delete Dedicated Endpoint Source: https://docs.tokenfactory.nebius.com/api-reference/dedicated-endpoints/delete-dedicated-endpoint https://api.tokenfactory.nebius.com/openapi.json delete /v0/dedicated_endpoints/{endpoint_id} # List Dedicated Endpoint Templates Source: https://docs.tokenfactory.nebius.com/api-reference/dedicated-endpoints/list-dedicated-endpoint-templates https://api.tokenfactory.nebius.com/openapi.json get /v0/dedicated_endpoints/templates # List Dedicated Endpoints Source: https://docs.tokenfactory.nebius.com/api-reference/dedicated-endpoints/list-dedicated-endpoints https://api.tokenfactory.nebius.com/openapi.json get /v0/dedicated_endpoints # Update Dedicated Endpoint Source: https://docs.tokenfactory.nebius.com/api-reference/dedicated-endpoints/update-dedicated-endpoint https://api.tokenfactory.nebius.com/openapi.json patch /v0/dedicated_endpoints/{endpoint_id} # Create embeddings Source: https://docs.tokenfactory.nebius.com/api-reference/examples/create-embeddings For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. Request: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) client.embeddings.create( model="BAAI/bge-en-icl", input="Wake up, Neo...", encoding_format="float" ) ``` ```bash cURL theme={null} curl -X POST https://api.tokenfactory.nebius.com/v1/embeddings \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "BAAI/bge-en-icl", "input": "Wake up, Neo...", "encoding_format": "float" }' ``` > [accordion] Response > > ```text theme={null} > { > "object": "list", > "data": [ > { > "object": "embedding", > "embedding": [ > 0.0023064255, > -0.009327292, > .... (1536 floats total for BAAI/bge-en-icl) > -0.0028842222, > ], > "index": 0 > } > ], > "model": "BAAI/bge-en-icl", > "usage": { > "prompt_tokens": 8, > "total_tokens": 8 > } > } > ``` For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). # Files Source: https://docs.tokenfactory.nebius.com/api-reference/examples/files For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. ## **Upload a file: POST** Request: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) batch_requests = client.files.create( file=open("batch-requests.jsonl", "rb"), purpose="batch" ) ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/files \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ -F purpose="batch" \ -F file="@batch-requests.jsonl" ``` > [accordion] Response > > ``` > { > "id": "file-123", > "object": "file", > "bytes": 120000, > "created_at": 1730723658, > "filename": "batch-requests.jsonl", > "purpose": "batch" > } > ``` ## **Get file info: GET** Request: ```python Python theme={null} client.files.retrieve("file-123") ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/files/file-123 \ -H "Authorization: Bearer $NEBIUS_API_KEY" ``` > [accordion] Response > > ``` > { > "id": "file-123", > "object": "file", > "bytes": 120000, > "created_at": 1730723658, > "filename": "batch-requests.jsonl", > "purpose": "batch" > } > ``` ## **Get file content: GET** Request: ```python Python theme={null} batch_result = client.files.content("file-123") print(batch_result.text) ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/files/file-123/content \ -H "Authorization: Bearer $NEBIUS_API_KEY" > batch_result.jsonl ``` ## **List files: GET** Request: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) client.files.list() ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/files \ -H "Authorization: Bearer $NEBIUS_API_KEY" ``` > [accordion] Response > > ``` > { > "data": [ > { > "id": "file-123", > "object": "file", > "bytes": 120000, > "created_at": 1730723658, > "filename": "batch-requests.jsonl", > "purpose": "batch" > }, > { > "id": "file-789", > "object": "file", > "bytes": 120, > "created_at": 1731493853, > "filename": "health-records-batch.jsonl", > "purpose": "batch" > } > ], > "object": "list" > } > ``` ## **Delete a file: DELETE** Request: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) client.files.delete("file_123") ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/files/file_123 \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ -X DELETE ``` > [accordion] Response > > ``` > { > "id": "batch_123", > "object": "file", > "deleted": true > } > ``` For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). # Image generation Source: https://docs.tokenfactory.nebius.com/api-reference/examples/image-generation For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. Request: ```python Python theme={null} from openai import OpenAI import os client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1", api_key=os.environ.get("NEBIUS_API_KEY"), ) completion = client.images.generate( model="stability-ai/sdxl", prompt="An elephant in a desert", response_format="b64_json", extra_body={ "response_extension": "png", "width": 512, "height": 512, "num_inference_steps": 30, "seed": -1, "negative_prompt": "Giraffes, night sky" } ) print(completion.to_json()) ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/images/generations \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "stability-ai/sdxl", "prompt": "An elephant in a desert", "response_format": "b64_json", "response_extension": "webp", "width": 512, "height": 512, "num_inference_steps": 30, "seed": -1, "negative_prompt": "Giraffes, night sky" }' ``` ```javascript JavaScript theme={null} import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1", apiKey: process.env.NEBIUS_API_KEY, }); const response = await client.images.generate({ model: 'black-forest-labs/flux-schnell', response_format: 'b64_json', width: 1024, height: 768, response_extension: 'png', num_inference_steps: 4, negative_prompt: 'Giraffes, night sky', seed: -1, prompt: 'An elephant in a desert', }).then((completion) => { console.log(completion.data); }); ``` > [accordion] Response > > ```Non-verbose Response format: b64_json theme={null} > { > "data": [ > { > "b64_json": "UklGRg66Ag..." > } > ], > "id": "text2img-0941c39c-..." > } > ``` > > ```Verbose Response format: url theme={null} > { > "data": [ > { > "url": "https://pictures-storage-dev.storage.eu-north1.nebius.cloud/text2img-0941c39c-....webp" > } > ], > "id": "text2img-0941c39c-..." > } > ``` > [!NOTE] > > Save the image once you receive the link. Nebius Token Factory does not store the image from the provided link permanently. For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). # List of models Source: https://docs.tokenfactory.nebius.com/api-reference/examples/list-of-models For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. Request: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) client.models.list() ``` ```bash cURL theme={null} curl https://api.tokenfactory.nebius.com/v1/models \ -H "Authorization: Bearer $NEBIUS_API_KEY" ``` > [accordion] Response > > ```Non-verbose Non-verbose theme={null} > { > "object": "list", > "data": [ > { > "id": 'meta-llama/Meta-Llama-3.1-8B-Instruct', > "object": "model", > "created": 1724480826, > "owned_by": 'system' > }, > { > "id": 'meta-llama/Meta-Llama-3.1-70B-Instruct', > "object": "model", > "created": 1724480826, > "owned_by": 'system' > }, > ], > "object": "list" > } > ``` > > ```Verbose Verbose theme={null} > { > "object": "list", > "data": [ > { > "id": "meta-llama/Meta-Llama-3.1-8B-Instruct-fast", > "name": "Meta-Llama-3.1-8B-Instruct (fast)", > "created": 1750954196, > "description": "", > "context_length": 131072, > "architecture": { > "modality": "text->text", > "tokenizer": "Other" > }, > "quantization": "fp8", > "pricing": { > "prompt": "0.00000003", > "completion": "0.00000009", > "image": "0", > "price_per_video_second": "0", > "request": "0" > }, > "per_request_limits": { > "tokens_per_minute": 800000.0, > "requests_per_minute": 1200.0, > "burst_ratio": 1.0 > }, > "object": "model", > "owned_by": "system" > }, > ... > ] > } > ``` For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). ## **Specific model parameter** 1. [Install jq](https://jqlang.org/download/) if you do not have it. 2. Get the model ID: in the **Models** page, next to the model, click → **Copy model ID**. 3. Copy the name of the required parameter. See the list of available parameters in the **RichModel** schema in the [API reference](https://docs.tokenfactory.nebius.com/api-reference/models/list-models#richmodel). 4. Add the values to the following request: ```bash theme={null} curl -s 'https://api.tokenfactory.nebius.com/v1/models?verbose=true' \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ -H 'accept: application/json' \ -X GET | jq '.data[] | select(.id == "") | .' ``` # Overview Source: https://docs.tokenfactory.nebius.com/api-reference/examples/overview Nebius Token Factory offers an OpenAI-compatible API for inference and fine-tuning. Welcome to the API examples library! Here you’ll find practical, real-world requests you can copy, paste, and modify to get results faster. > [card] [Text Generation](/api-reference/examples/text-generation) > [card] [Vision Capabilities](/api-reference/examples/vision-capabilities) > [card] [Text Generation for Code Autocomplete](/api-reference/examples/text-generation-for-code-autocomplete) > [card] [List of Models](/api-reference/examples/list-of-models) > [card] [Image Generation](/api-reference/examples/image-generation) > [card] [Create Embeddings](/api-reference/examples/create-embeddings) > [card] [Files](/api-reference/examples/files) # Text generation Source: https://docs.tokenfactory.nebius.com/api-reference/examples/text-generation For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. Here is a sample JSON request body that includes all supported fields: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) completion = client.chat.completions.create( model="meta-llama/Meta-Llama-3.1-70B-Instruct", messages=[ { "role": "system", "content": "You are a chemistry expert. Add jokes about cats to your responses from time to time." }, { "role": "user", "content": "Hello!" }, { "role": "assistant", "content": "Hello! How can I assist you with chemistry today? And did you hear about the cat who became a chemist? She had nine lives, but she only needed one formula!" } ], max_tokens=100, temperature=1, top_p=1, top_k=50, n=1, stream=false, stream_options=null, stop=null, presence_penalty=0, frequency_penalty=0, logit_bias=null, logprobs=false, top_logprobs=null, user=null, extra_body={ "guided_json": {"type": "object", "properties": {...}} }, response_format={ "type": "json_object" } ) print(completion.to_json()) ``` ```bash cURL theme={null} curl 'https://api.tokenfactory.nebius.com/v1/chat/completions' \ -X 'POST' \ -H 'Content-Type: application/json' \ -H 'Accept: */*' \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ --data-binary '{ "model": "meta-llama/Meta-Llama-3.1-70B-Instruct", "messages": [ { "role": "system", "content": "You are a chemistry expert. Add jokes about cats to your responses from time to time." }, { "role": "user", "content": "Hello!" }, { "role": "assistant", "content": "Hello! How can I assist you with chemistry today? And did you hear about the cat who became a chemist? She had nine lives, but she only needed one formula!" } ], "max_tokens": 100, "temperature": 1, "top_p": 1, "top_k": 50, "n": 1, "stream": false, "stream_options": null, "stop": null, "presence_penalty": 0, "frequency_penalty": 0, "logit_bias": null, "logprobs": false, "top_logprobs": null, "user": null, "guided_json": {"type": "object", "properties": {...}} "response_format": {"type": "json_object"} }' ``` ```javascript JavaScript theme={null} const OpenAI = require("openai"); const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1/", apiKey: process.env.NEBIUS_API_KEY, }); client.chat.completions.create({ "max_tokens": 100, "temperature": 1, "top_p": 1, "top_k": 50, "n": 1, "stream": false, "stream_options": null, "stop": null, "presence_penalty": 0, "frequency_penalty": 0, "logit_bias": null, "logprobs": false, "top_logprobs": null, "user": null, "extra_body": { "guided_json": {"type": "object", "properties": {...},} }, "response_format": { "type": "json_object" }, "model": "meta-llama/Meta-Llama-3.1-70B-Instruct", "messages": [ { "role": "system", "content": "You are a chemistry expert. Add jokes about cats to your responses from time to time." }, { "role": "user", "content": "Hello!" }, { "role": "assistant", "content": "Hello! How can I assist you with chemistry today? And did you hear about the cat who became a chemist? She had nine lives, but she only needed one formula!" } ] }) .then((completion) => console.log(completion)); ``` > [accordion] Response > > ``` > { > "id": "cmpl-*****", > "choices": [ > { > "finish_reason": "stop", > "index": 0, > "logprobs": null, > "message": { > "content": "Hello! It's nice to meet you. Is there something I can help you with, or would you like to chat?", > "role": "assistant", > "function_call": null, > "tool_calls": [] > }, > "stop_reason": null > } > ], > "created": 1721397089, > "model": "meta-llama/Meta-Llama-3.1-70B-Instruct", > "object": "chat.completion", > "system_fingerprint": null, > "usage": { > "completion_tokens": 26, > "prompt_tokens": 12, > "total_tokens": 38 > } > } > ``` For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). # Text generation for code autocomplete Source: https://docs.tokenfactory.nebius.com/api-reference/examples/text-generation-for-code-autocomplete For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. Here is a sample JSON request body that includes all supported fields: ```python Python theme={null} from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) for chunk in client.completions.create( model="meta-llama/Meta-Llama-3.1-70B-Instruct", prompt="Say my name", max_tokens=7, temperature=0, stream=True ): print(chunk.choices[0].text) ``` ```bash cURL theme={null} curl 'https://api.tokenfactory.nebius.com/v1/completions' \ -H "Content-Type: application/json" \ -H "Authorization: $NEBIUS_API_KEY" \ -d '{ "model": "meta-llama/Meta-Llama-3.1-70B-Instruct" "prompt": "Say my name", "max_tokens": 7, "temperature": 0, "stream": true }' ``` ```javascript JavaScript theme={null} import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1/", apiKey: process.env.NEBIUS_API_KEY, }); async function main() { const stream = await openai.completions.create({ model: "meta-llama/Meta-Llama-3.1-70B-Instruct", prompt: "Say my name", stream: true, }); for await (const chunk of stream) { console.log(chunk.choices[0].text); } } main(); ``` > [accordion] Response > > ``` > { > "id": "cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe", > "object": "text_completion", > "created": 1690759111, > "choices": [ > { > "text": "Heisenberg", > "index": 0, > "logprobs": null, > "finish_reason": null > } > ], > "model": "meta-llama/Meta-Llama-3.1-70B-Instruct", > "system_fingerprint": "fp_44709d6aaa" > } > ``` For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). # Vision capabilities Source: https://docs.tokenfactory.nebius.com/api-reference/examples/vision-capabilities For the following example to work, save your [API key](https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication) to the `NEBIUS_API_KEY` environment variable. You can pass images in the following ways: * A URL to the image. * A base64 encoded image directly in the request. ```python Python theme={null} from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) response = client.chat.completions.create( model="Qwen/Qwen2-VL-72B-Instruct", messages=[ { "role": "user", "content": [ {"type": "text", "text": "What’s in this image?"}, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", }, }, ], } ], max_tokens=300, ) print(response.choices[0]) ``` ```bash cURL theme={null} curl 'https://api.tokenfactory.nebius.com/v1/chat/completions' \ -X 'POST' \ -H 'Content-Type: application/json' \ -H 'Accept: */*' \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ --data-binary '{ "model": "Qwen/Qwen2-VL-72B-Instruct", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What’s in this image?" }, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } } ] } ], "max_tokens": 100 }' ``` ```javascript JavaScript theme={null} const OpenAI = require("openai"); const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1/", apiKey: process.env.NEBIUS_API_KEY, }); client.chat.completions.create({ "max_tokens": 100, "temperature": 1, "top_p": 1, "top_k": 50, "n": 1, "stream": false, "stream_options": null, "stop": null, "presence_penalty": 0, "frequency_penalty": 0, "logit_bias": null, "logprobs": false, "top_logprobs": null, "user": null, "extra_body": { "guided_json": {"type": "object", "properties": {...},} }, "response_format": { "type": "json_object" }, "model": "meta-llama/Meta-Llama-3.1-70B-Instruct", "messages": [ { "role": "user", "content": [ { type: "text", text: "What’s in this image?" }, { type: "image_url", image_url: { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", }, }, ] } ] }) .then((completion) => console.log(completion)); ``` For detailed field descriptions, see the [API reference](https://docs.tokenfactory.nebius.com/api-reference/introduction). # Delete file Source: https://docs.tokenfactory.nebius.com/api-reference/files/delete-file https://api.tokenfactory.nebius.com/openapi.json delete /v1/files/{file_id} # List user files Source: https://docs.tokenfactory.nebius.com/api-reference/files/list-user-files https://api.tokenfactory.nebius.com/openapi.json get /v1/files # Retrieve file Source: https://docs.tokenfactory.nebius.com/api-reference/files/retrieve-file https://api.tokenfactory.nebius.com/openapi.json get /v1/files/{file_id} # Retrieve file content Source: https://docs.tokenfactory.nebius.com/api-reference/files/retrieve-file-content https://api.tokenfactory.nebius.com/openapi.json get /v1/files/{file_id}/content # Returns URL with link to download file content Source: https://docs.tokenfactory.nebius.com/api-reference/files/returns-url-with-link-to-download-file-content https://api.tokenfactory.nebius.com/openapi.json get /v1/files/{file_id}/link # Upload file Source: https://docs.tokenfactory.nebius.com/api-reference/files/upload-file https://api.tokenfactory.nebius.com/openapi.json post /v1/files # Cancel fine-tuning job Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/cancel-fine-tuning-job https://api.tokenfactory.nebius.com/openapi.json post /v1/fine_tuning/jobs/{job_id}/cancel Immediately cancel a fine-tuning job. # Create a fine-tuning job Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/create-a-fine-tuning-job https://api.tokenfactory.nebius.com/openapi.json post /v1/fine_tuning/jobs Creates a job that fine-tunes a specified model based on a given dataset. # Get fine-tuning checkpoint Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/get-fine-tuning-checkpoint https://api.tokenfactory.nebius.com/openapi.json get /v1/fine_tuning/jobs/{job_id}/checkpoints/{checkpoint_id} Get details about a specific checkpoint from a fine-tuning job. # Get fine-tuning job info Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/get-fine-tuning-job-info https://api.tokenfactory.nebius.com/openapi.json get /v1/fine_tuning/jobs/{job_id} Get info about a fine-tuning job. # List fine-tuning checkpoints Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-fine-tuning-checkpoints https://api.tokenfactory.nebius.com/openapi.json get /v1/fine_tuning/jobs/{job_id}/checkpoints Get training checkpoints for a fine-tuning job. # List fine-tuning events Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-fine-tuning-events https://api.tokenfactory.nebius.com/openapi.json get /v1/fine_tuning/jobs/{job_id}/events Get status updates for a fine-tuning job. # List fine-tuning jobs Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-fine-tuning-jobs https://api.tokenfactory.nebius.com/openapi.json get /v1/fine_tuning/jobs Lists all fine-tuning jobs. # List spec-draft trainable models Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-spec-draft-trainable-models https://api.tokenfactory.nebius.com/openapi.json get /v1/fine_tuning/models/spec-draft Lists Hugging Face models supported for spec-draft training with their parameter counts, maximum context lengths, metadata, and billing prices. # List spec-draft trainable models Source: https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-spec-draft-trainable-models-1 https://api.tokenfactory.nebius.com/openapi.json get /fine_tuning/models/spec-draft Lists Hugging Face models supported for spec-draft training with their parameter counts, maximum context lengths, metadata, and billing prices. # Create a response Source: https://docs.tokenfactory.nebius.com/api-reference/inference/create-a-response https://api.tokenfactory.nebius.com/openapi.json post /v1/responses Creates a model response for a given input # Create chat completion Source: https://docs.tokenfactory.nebius.com/api-reference/inference/create-chat-completion https://api.tokenfactory.nebius.com/openapi.json post /v1/chat/completions Creates a model response for the given chat conversation. # Create completion Source: https://docs.tokenfactory.nebius.com/api-reference/inference/create-completion https://api.tokenfactory.nebius.com/openapi.json post /v1/completions Creates a model completion for the given input prompt. # Create embeddings Source: https://docs.tokenfactory.nebius.com/api-reference/inference/create-embeddings https://api.tokenfactory.nebius.com/openapi.json post /v1/embeddings Creates a model response for the given text. # Rerank documents Source: https://docs.tokenfactory.nebius.com/api-reference/inference/rerank-documents https://api.tokenfactory.nebius.com/openapi.json post /v1/rerank Reranks documents based on their relevance to a query. # Introduction Source: https://docs.tokenfactory.nebius.com/api-reference/introduction > [!NOTE] > > Nebius Token Factory offers an [OpenAI-compatible API](https://docs.tokenfactory.nebius.com/api-reference/models/list-models) for inference and fine-tuning. Here are examples of Python, cURL and JavaScript SDK command that makes an API request from your terminal: ```python Python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key=os.environ.get("NEBIUS_API_KEY"), ) completion = client.chat.completions.create( model="meta-llama/Meta-Llama-3.1-70B-Instruct", messages=[ { "role": "user", "content": """Hello!""" } ], temperature=0.6 ) print(completion.to_json()) ``` ```bash cURL theme={null} curl 'https://api.tokenfactory.nebius.com/v1/chat/completions' \ -X 'POST' \ -H 'Content-Type: application/json' \ -H 'Accept: */*' \ -H "Authorization: Bearer $NEBIUS_API_KEY" \ --data-binary '{"temperature":0.6,"model":"meta-llama/Meta-Llama-3.1-70B-Instruct","messages":[{"role":"user","content":"Hello!"}]}' ``` ```javascript JavaScript theme={null} const OpenAI = require("openai"); const client = new OpenAI({ baseURL: "https://api.tokenfactory.nebius.com/v1/", apiKey: process.env.NEBIUS_API_KEY, }); client.chat.completions.create({ "temperature": 0.6, "model": "meta-llama/Meta-Llama-3.1-70B-Instruct", "messages": [ { "role": "user", "content": "Hello!" } ] }) .then((completion) => console.log(completion)); ``` > [accordion] Response > > ``` > { > "choices": [ > { > "finish_reason": "stop", > "index": 0, > "message": { > "content": "Hello! It's nice to meet you. Is there something I can help you with, or would you like to chat?", > "role": "assistant" > } > } > ], > "created": 1717516032, > "model": "meta-llama/Meta-Llama-3-70B-Instruct-cheap", > "object": "chat.completion", > "usage": { > "completion_tokens": 26, > "prompt_tokens": 13, > "total_tokens": 39 > } > } > > ``` For more examples, see [Examples of using the Nebius Token Factory API](https://docs.tokenfactory.nebius.com/api-reference/examples/overview). ## Authentication To authenticate, include your *API key* (e.g., `ABC123...`) in the `Authorization` header, as shown below: ``` Authorization: Bearer ABC123... ``` > [!WARNING] > > Keep your keys private; do not share or expose them in client-side code. If a key is compromised, Nebius Token Factory can automatically revoke it To get an API key: 1. In Nebius Token Factory, go to the [API keys](https://tokenfactory.nebius.com/project/api-keys) section. 2. Click  **Create API key**. 3. Enter the key name and then click **Create**. 4. Save the displayed API key. You cannot open it later in Nebius Token Factory. > [!TIP] > > In the [Nebius Token Factory inference playground](https://tokenfactory.nebius.com/playground), you can view your model setup and chat as code that makes API requests, and use this code in your applications. For more details, see [View code](https://docs.tokenfactory.nebius.com/ai-models-inference/playground#view-code). > [!TIP] > > You can use [integrations with third-party instruments](https://docs.tokenfactory.nebius.com/integrations/overview) instead of the API. # List models Source: https://docs.tokenfactory.nebius.com/api-reference/models/list-models https://api.tokenfactory.nebius.com/openapi.json get /v1/models Lists the currently available models, and provides basic information about each one such as the owner and availability. # Get current token information Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/auth/get-current-token-information https://eu-north.nebius.computer/static/api.yaml get /whoami Returns information about the current authentication token, including the token UUID, expiration time, and a map of all known permissions with their granted status. # Check if a file exists for the current namespace Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/files/check-if-a-file-exists-for-the-current-namespace https://eu-north.nebius.computer/static/api.yaml head /files/{sha256} Returns 200 if the file is uploaded by the current namespace, otherwise 404. # Get file info by SHA256 Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/files/get-file-info-by-sha256 https://eu-north.nebius.computer/static/api.yaml get /files/{sha256} Returns file info (uuid, sha256, created_at, updated_at). # List uploaded files for the current namespace Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/files/list-uploaded-files-for-the-current-namespace https://eu-north.nebius.computer/static/api.yaml get /files Returns a paginated list of uploaded files for the current namespace. # Upload a file to the server. the body must be a file content. Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/files/upload-a-file-to-the-server-the-body-must-be-a-file-content https://eu-north.nebius.computer/static/api.yaml post /files Uploads a file to the server. The body must contain the file content. # Add a tag to an image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/images/add-a-tag-to-an-image https://eu-north.nebius.computer/static/api.yaml patch /images/{imageUUID}/tag Adds a tag to an image. Tags are unique per namespace; if the requested tag is already assigned to another image, it will be moved to this image. Assigning a tag that matches a public tag to a public image will freeze that tag to the current image - subsequent public updates to the tag will not affect it. To make the public tag track the latest public image again, remove your tag assignment. When a tag is removed from an image that resides in the public namespace, the API returns HTTP 200 OK. response body contains the tag that now points to the public image (i.e., the image that the tag is automatically re‑assigned to). In other words, un‑tagging a public image does not delete the tag; it simply moves the tag back to the public image and the caller receives that tag in the successful response. # Import a container image from a registry Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/images/import-a-container-image-from-a-registry https://eu-north.nebius.computer/static/api.yaml post /images/import Imports the OCI image filesystem content of from a specified registry. Important limitations and behavior: - Only the image root filesystem (files and directories) is imported. This is like to the output of `docker export` and does not preserve layers metadata. - Most image configuration and manifest data are ignored. Metadata such as `LABEL`, `ENTRYPOINT`, `CMD`, `WORKDIR`, `EXPOSE` and other image configuration directives will **NOT be imported or applied**. - `ENV` variables defined in the image **are imported** and automatically applied to the instance environment when `shell` is set to `true`. When `shell` is `false`, image environment variables are not inherited and must be passed explicitly via the `env` field. - The result is a flat rootfs snapshot with preserved environment variables. - If the specified tag already exists in the public images, the imported image will replace it. To avoid this, you can tag the existing image with a different tag for use it later. You also can use image UUIDs it is not changing for imported and existend image. - In case the remote image is unchanged and already imported, the operation will complete and the same UUID will be returned without re-importing the image. The request creates an import operation which runs asynchronously. # List publicly available images Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/images/list-publicly-available-images https://eu-north.nebius.computer/static/api.yaml get /images Returns a list of all publicly available container images. # Remove tags from an image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/images/remove-tags-from-an-image https://eu-north.nebius.computer/static/api.yaml delete /images/{imageUUID}/tag Removes a tag (or all tags) from an image. When `tag` query parameter is provided, only that specific tag is removed. When omitted, all tags are removed from the image. If any public image has the same tag, tag will start tracking that public image again. In all other cases tag will be removed and the image will be accessible only by its UUID. # Check if a file exists in image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/check-if-a-file-exists-in-image https://eu-north.nebius.computer/static/api.yaml head /inspect/{image_uuid}/download Checks if a file exists in the specified image without returning the file content # Check if a path can be archived from image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/check-if-a-path-can-be-archived-from-image https://eu-north.nebius.computer/static/api.yaml head /inspect/{image_uuid}/archive Checks if a file or a directory exists in the specified image without streaming the archive # Download a file from image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/download-a-file-from-image https://eu-north.nebius.computer/static/api.yaml get /inspect/{image_uuid}/download Returns file content # Download a file or a directory from image as tar archive Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/download-a-file-or-a-directory-from-image-as-tar-archive https://eu-north.nebius.computer/static/api.yaml get /inspect/{image_uuid}/archive Streams the specified path inside the image root filesystem as a POSIX PAX tar archive. A directory becomes the archive root; a regular file becomes a single-entry archive. The response is chunked; total size is not known upfront. Served as an attachment, `filename` is the path with `/` replaced by `_` plus `.tar` (e.g. `/bin/true` -> `bin_true.tar`). # Find image by tag Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/find-image-by-tag https://eu-north.nebius.computer/static/api.yaml get /inspect/ Redirects to the image inspection endpoint for the specified tag # Inspect an image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/inspect-an-image https://eu-north.nebius.computer/static/api.yaml get /inspect/{image_uuid}/ Returns image metadata # List files in image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/list-files-in-image https://eu-north.nebius.computer/static/api.yaml get /inspect/{image_uuid}/list Returns files list # Redirect to /inspect/ Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/redirect-to-inspect https://eu-north.nebius.computer/static/api.yaml get /inspect Redirects to /inspect/ with a trailing slash # Redirect to /inspect/{imageUUID}/ Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/redirect-to-inspect- https://eu-north.nebius.computer/static/api.yaml get /inspect/{imageUUID} Redirects to /inspect/{imageUUID}/ with a trailing slash # Search file contents in image Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/inspect/search-file-contents-in-image https://eu-north.nebius.computer/static/api.yaml get /inspect/{image_uuid}/grep Regex content search inside the image's root filesystem, powered by ripgrep. Symlinks are never followed during traversal, hidden files are searched, `.gitignore`-style files inside the image are ignored, and binary files (containing a NUL byte) are skipped. Rust regex syntax, linear-time matching. Results are a flat, file-ordered list of lines. `before`/`after` request extra `type: context` lines around each `type: match` line, mirroring ripgrep's --json message type field. `path` may be repeated to search multiple roots in one call, the same way `pattern`/`glob` already can; results are concatenated in the given order and share the `max_total` budget across all of them. # Spawn a new container instance Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/instances/spawn-a-new-container-instance https://eu-north.nebius.computer/static/api.yaml post /instances Creates and runs a new execution instance with the specified configuration. Requires a valid `Authorization` header. Common request body rules: * The request body must contain at least `command` and `image` fields all other fields can be omitted. * If the `command` field is a shell expression, you must set `shell` field to `true`. * For specifying the shell binary, you can use `env` field to set `SHELL` variable. * When `shell` is `true`, environment variables defined in the image (via `ENV` directives) are automatically inherited. When `shell` is `false`, image environment variables are not inherited and must be passed explicitly via the `env` field. # Kill one subprocess Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operation/kill-one-subprocess https://eu-north.nebius.computer/static/api.yaml delete /operations/{operationId}/subprocesses/{spid} Sends a signal to the process group of `spid` inside the running instance. Without the `signal` parameter the group gets SIGKILL. Termination is observable, not returned: the `exit` event lands in the event log and `GET /operations/{operationId}/subprocesses/{spid}` reports the terminal `state` (`signal` set, `exit_code` -1 when killed). Killing `spid=1` (the main process) effectively ends the operation, like letting the command fail. # Result of one subprocess, reconstructed from its events Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operation/result-of-one-subprocess-reconstructed-from-its-events https://eu-north.nebius.computer/static/api.yaml get /operations/{operationId}/subprocesses/{spid} Returns an `InstanceResult` for `spid` — the same shape as the parent operation's `metadata.result` — folded from the subprocess's event log (spawn / stdout / stderr / exit). Works for running and terminal operations alike. While the process is still running, `state.exit_code` and `state.signal` are `-1` (unknown) and `resources` holds sentinel defaults; once the exit event lands they carry the real values. `stdout` / `stderr` are consolidated and capped at the spec's `truncate_output_at`. The raw event stream stays available at `GET /operations/{operationId}/events?spid={spid}`. # Spawn an additional subprocess inside a running instance Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operation/spawn-an-additional-subprocess-inside-a-running-instance https://eu-north.nebius.computer/static/api.yaml post /operations/{operationId}/subprocesses Starts a new process inside the VM that already hosts the named operation. Distinct from `POST /instances`, which spins up a VM: this endpoint requires a running operation (EXECUTING or ASSIGNED) and reuses the existing VM. The body is an `ExecSpec` — process-execution fields only. VM-level concerns (`image`, `hostname`, `resources_limits`, `files`, `timeout`, `disposable`, `preserve_env`) are not accepted here; they were set when the parent operation was created. The required permission follows the parent instance: `SPAWN_DISPOSABLE` when it was spawned with `disposable=true`, `SPAWN` otherwise. On success the worker assigns a fresh `spid` (≥2; `spid=1` is the main process spawned from `metadata`) and the response carries it in the body plus a `Location` header pointing at `GET /operations/{operationId}/subprocesses/{spid}` — the subprocess result reconstructed from its events. # Write to a subprocess's stdin and/or close it Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operation/write-to-a-subprocesss-stdin-andor-close-it https://eu-north.nebius.computer/static/api.yaml post /operations/{operationId}/subprocesses/{spid}/stdin Writes a chunk to the stdin of a live process inside the running instance — `spid=1` targets the main process, `≥2` the exec'd children. Requires the process to have been started with `stdin.close=false`; otherwise its pipe is already at EOF and the call returns 409. `close=true` (the default) signals EOF after writing `value`; an empty `value` with `close=true` just closes the pipe. A client that serializes its own requests gets ordered writes; concurrent requests to the same spid are safe but their order is unspecified. A 504 means the guest write timed out mid-call — the chunk may or may not have been delivered (e.g. the process stopped reading and the pipe is full), so blind retries can duplicate data. # Cancel an operation Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operations/cancel-an-operation https://eu-north.nebius.computer/static/api.yaml delete /operations/{operationId} Cancels an operation # Get an operation status Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operations/get-an-operation-status https://eu-north.nebius.computer/static/api.yaml get /operations/{operationId} Returns the status of an operation. For an EXECUTING INSTANCE operation, pass `?inflight=1` to also synthesize the partial `result.stdout` / `result.stderr` from the live event log. Off by default — each fetch with `inflight` triggers an extra subscribe RPC to the guest and drains its current events.gz, which is wasted work for clients that only poll for status transitions. # List operations Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operations/list-operations https://eu-north.nebius.computer/static/api.yaml get /operations Returns a list of running and completed operations # Stream the operation event log via Server-Sent Events Source: https://docs.tokenfactory.nebius.com/api-reference/sandboxes/operations/stream-the-operation-event-log-via-server-sent-events https://eu-north.nebius.computer/static/api.yaml get /operations/{operationId}/events Always returns `text/event-stream` (SSE) on success. The body is a sequence of three kinds of lines (per RFC W3C SSE), each terminated by `\n\n`: ### Frame shapes **Normal event frame** — one `OperationEvent` JSON object in `data:`, dispatchable via `event:`: ``` id: event: data: {"id": N, "ts": "...", "spid": ..., "type": "...", "data": {...}} ``` `event:` always matches `data.type`. See `OperationEvent` and `OperationEventType` for the per-type payload shape. Native `EventSource` dispatches each frame to the matching `addEventListener("", ...)` handler. **Server-side error frame** — surfaces handler exceptions to the connected client without tearing the TCP connection down mid-stream. Sent right before the server closes the response: ``` : stream ended with error, retry since last event id event: sse_error data: ``` The leading SSE comment line lets pure-EventSource clients see the intent ("retry from Last-Event-Id"); the `sse_error` frame carries the error text for logging. Clients should treat this as a non-clean close and reconnect with the standard SSE `Last-Event-Id` semantics (see Resuming). **Keepalive comment** — periodic `: keepalive\n\n` lines emitted while the stream is idle. They keep upstream `proxy_read_timeout` / TCP idle timers fresh and have no application meaning. Spec-compliant; EventSource and any SSE parser must ignore comment lines (those beginning with `:`). ### `follow` semantics The `follow` parameter controls only whether the stream stays open after the last currently-known event: * `follow=0` (default) — the server emits everything currently available and closes the connection. * `follow=1` — same start; if the operation is still running the server keeps the connection open and forwards new events as they appear. For terminal operations `follow=1` is a no-op: there's nothing more to subscribe to, so the connection closes after the last event just like `follow=0`. Optional filters: * `?spid=N` — only events whose `spid` (Spawned Process ID, the routing identity in `OperationEvent`) matches. * `?since=N` — only events with `id > N`. `follow=1` requires `SPAWN` or `SPAWN_DISPOSABLE` on top of the baseline `LIST` — a long-lived subscription reserves per-operation server state. `follow=0` is read-only and stays under `LIST`. ### Resuming after a drop Every normal frame carries `id:` — the canonical event id. On reconnect send the last successfully received id in the standard `Last-Event-Id` request header (or `?since=N` on manual GETs); the server resumes from that point. ### Error handling | Status | Meaning | Client action | |--------|--------------------------------------------------|----------------------------------------------| | 200 | Stream open | Read frames; reconnect with Last-Event-Id if the stream closes before reaching a terminal event | | 400 | Malformed query/header (non-integer param) | Fix request | | 401 | Missing/invalid auth | Refresh credentials | | 403 | Auth lacks LIST (or SPAWN for `follow=1`) | Use a token with the right scope | | 404 | Operation not in this namespace | Wrong UUID | | 410 | Stream is over but the terminal artifact isn't ready yet | Retry after `Retry-After` | | 425 | Not yet ready (operation is still being prepared)| Retry after `Retry-After` | | 502 | Upstream returned an error opening the stream | Retry; if persistent, escalate | | 504 | Upstream took too long to respond | Retry | A `200` followed by an `event: sse_error` frame and immediate close is the in-band equivalent of "the stream broke after we already committed to a 200" — handle it the same way as 410: wait briefly, reconnect with `Last-Event-Id`. See `OperationEvent` for the per-event shape. # Model Deprecations: August 2026 Source: https://docs.tokenfactory.nebius.com/august-2026-deprecation-notice Models soon leaving Token Factory Serverless with recommended migration paths. > [!NOTE] > > **On August 31, 2026:** > > * Affected Serverless models will no longer be available via API or Playground. > * Dedicated Endpoints for these models will be unaffected by this change. ## What to Know These models will be removed from Token Factory on **August 31, 2026**. After that date, you will not be able to select them in the Playground or send API requests using their model IDs. * This change only affects Serverless usage. [Dedicated Endpoints](https://tokenfactory.nebius.com/endpoints/create-dedicated-endpoint) are unaffected. * Token Factory does not automatically reroute requests from deprecated models. * Choose a replacement based on your workload, then test before migrating traffic. | Deprecating Model | Recommended Replacement | | - | - | | [`deepseek-ai/DeepSeek-V4-Flash`](https://tokenfactory.nebius.com/models/catalog/text2text/deepseek-ai%2FDeepSeek-V4-Flash) | [`deepseek-ai/DeepSeek-V4-Flash-0731`](https://tokenfactory.nebius.com/?modals=endpoint-details\&model-id=deepseek-ai/DeepSeek-V4-Flash-0731) | | [`meta-llama/Llama-3.3-70B-Instruct`](https://tokenfactory.nebius.com/models/catalog/text2text/meta-llama%2FLlama-3.3-70B-Instruct) | [`nvidia/Nemotron-3_5-Lightning`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNemotron-3_5-Lightning) | | [`MiniMaxAI/MiniMax-M2.5`](https://tokenfactory.nebius.com/models/catalog/text2text/MiniMaxAI%2FMiniMax-M2.5) | [`MiniMaxAI/MiniMax-M3`](https://tokenfactory.nebius.com/models/catalog/text2text/MiniMaxAI%2FMiniMax-M3) | | [`NousResearch/Hermes-4-70B`](https://tokenfactory.nebius.com/models/catalog/text2text/NousResearch%2FHermes-4-70B) | [`nvidia/Nemotron-3_5-Lightning`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNemotron-3_5-Lightning) | | [`nvidia/Cosmos3-Super-Reasoner`](https://tokenfactory.nebius.com/models/catalog/image2text/nvidia%2FCosmos3-Super-Reasoner) | [`MiniMaxAI/MiniMax-M3`](https://tokenfactory.nebius.com/models/catalog/text2text/MiniMaxAI%2FMiniMax-M3) | | [`nvidia/Llama-3_1-Nemotron-Ultra-253B-v1`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FLlama-3_1-Nemotron-Ultra-253B-v1) | [`nvidia/nemotron-3-super-120b-a12b`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2Fnemotron-3-super-120b-a12b) | | [`nvidia/Nemotron-3-Nano-Omni`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNemotron-3-Nano-Omni) | [`nvidia/Nemotron-3_5-Lightning`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNemotron-3_5-Lightning) | | [`Qwen/Qwen2.5-VL-72B-Instruct`](https://tokenfactory.nebius.com/models/catalog/image2text/Qwen%2FQwen2.5-VL-72B-Instruct) | [`MiniMaxAI/MiniMax-M3`](https://tokenfactory.nebius.com/models/catalog/text2text/MiniMaxAI%2FMiniMax-M3) | | [`Qwen/Qwen3-32B`](https://tokenfactory.nebius.com/models/catalog/text2text/Qwen%2FQwen3-32B) | [`nvidia/Nemotron-3_5-Lightning`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNemotron-3_5-Lightning) | | [`Qwen/Qwen3-Next-80B-A3B-Thinking`](https://tokenfactory.nebius.com/models/catalog/text2text/Qwen%2FQwen3-Next-80B-A3B-Thinking) | [`Qwen/Qwen3.5-397B-A17B`](https://tokenfactory.nebius.com/models/catalog/text2text/Qwen%2FQwen3.5-397B-A17B) | ## Preparing to Migrate 1. Identify applications and workflows that send requests to a deprecating model ID. 2. Compare the replacement model's capabilities, performance and price. 3. Test prompts, inputs and workloads to verify the new model will work for you use cases. 4. Update the `model` value in your API requests then verify. ## Consider a Dedicated Endpoint For production workloads that need guaranteed stability or custom configurations, we recommend [Dedicated Endpoints](https://tokenfactory.nebius.com/?modals=create-dedicated-endpoint "https://tokenfactory.nebius.com/?modals=create-dedicated-endpoint") which provide: * Full control over model version and deployments. * Predictable performance and scaling * Enterprise-grade reliability and isolation To learn more about dedicated endpoints or for help getting started, our team is ready to help: 👉 [Contact Token Factory Sales](https://nebius.com/services/token-factory/enterprise-grade-inference?_gl=1*1d02gz7*_gcl_aw*R0NMLjE3NjY1MDAzMzEuQ2p3S0NBaUFtS25LQmhCckVpd0FhcUFuWnhlWUQ5SnlFVW9hS3Q0UUNOZ1ZpRDQzSms0clNFQVdRRTVHTGV4bHU5anNsUFQwNDFjTVBCb0N0UkVRQXZEX0J3RQ..*_gcl_au*MTM3MTMzODczMi4xNzY2NDc5NjA3LjE1MzYzOTEyOTAuMTc3NDAwNjAxMS4xNzc0MDA2MDEw#token-factory-enterprise-sales-form "https://nebius.com/services/token-factory/enterprise-grade-inference?_gl=1*1d02gz7*_gcl_aw*R0NMLjE3NjY1MDAzMzEuQ2p3S0NBaUFtS25LQmhCckVpd0FhcUFuWnhlWUQ5SnlFVW9hS3Q0UUNOZ1ZpRDQzSms0clNFQVdRRTVHTGV4bHU5anNsUFQwNDFjTVBCb0N0UkVRQXZEX0J3RQ..*_gcl_au*MTM3MTMzODczMi4xNzY2NDc5NjA3LjE1MzYzOTEyOTAuMTc3NDAwNjAxMS4xNzc0MDA2MDEw#token-factory-enterprise-sales-form") ## Need Help? If you need assistance migrating, choosing the right model or getting started with dedicated endpoints our team is ready to help. 👉 [Contact Token Factory Support](mailto:tokenfactory-support@nebius.com) # Cached Tokens Source: https://docs.tokenfactory.nebius.com/cached-tokens Token Factory automatically reuses previously computed prompt prefixes. Tokens served from this cache are billed at the model's **cached input** price, and every response reports how many tokens were cached. Caching is implicit: you don’t need to change your requests, set cache keys, or opt in. It works on both Serverless and Dedicated Endpoints. The cached input price applies to Serverless only, because Dedicated Endpoints are billed per GPU hour. Caching is also best-effort. ## How it works When you send a request, the inference engine checks whether the beginning of your prompt (the prefix) matches a prompt it processed recently. If it does, it reuses the stored computation for that prefix instead of recomputing it. The tokens served this way are *cached tokens*. Prompts with a long, stable prefix benefit most, for example: * a repeated system prompt or set of instructions; * tool and function definitions that are the same across calls; * few-shot examples or reference documents placed at the start of the prompt; * multi-turn conversations and agent loops, where each request repeats the earlier history. ## Billing Every Serverless text-generation request is billed under up to three token types: | Token type | What it covers | | :- | :- | | Input | Prompt tokens that were **not** served from the cache | | Cached input | Prompt tokens served from the cache | | Output | Tokens generated by the model | On Dedicated Endpoints, caching works too, but billing is per GPU hour and doesn’t change. Cached input tokens are a subset of the prompt tokens, so each prompt token is billed once: ```text theme={null} prompt tokens = input (uncached) tokens + cached input tokens ``` For example, a request with 3,108 prompt tokens, of which 3,072 are cached, is billed for 36 input tokens, 3,072 cached input tokens, and the output tokens. Your invoice and consumption report show cached input as a separate line item. If a request has no cache hit, no cached input item is created and all prompt tokens are billed at the regular input price. ### Pricing The cached input price is set per model. See the [pricing page](https://nebius.com/token-factory/prices) for current input, cached input, and output prices for each model. The cached input price applies only to tokens that were actually served from the cache. How many tokens are served from the cache depends on your workload and on factors outside your control, so the amount you save is not guaranteed and can vary from request to request. Models that are not listed, or that don't yet have a cached input price, bill all prompt tokens at the regular input price. ## Check cache usage in API responses The number of cached tokens is returned in the usage object of every response, including streaming responses. prompt\_tokens (or input\_tokens) is always the **total** number of input tokens, cached tokens included. ### Chat Completions and Completions ```json theme={null} { "usage": { "prompt_tokens": 3108, "completion_tokens": 62, "total_tokens": 3170, "prompt_tokens_details": { "cached_tokens": 3072 } } } ``` ### Responses API ```json theme={null} { "usage": { "input_tokens": 3108, "output_tokens": 62, "total_tokens": 3170, "input_tokens_details": { "cached_tokens": 3072 } } } ``` ### Streaming > [!NOTE] > > Not all models return usage information in streaming mode by default. To make sure usage, including cached\_tokens, is returned when streaming, set stream\_options.include\_usage to true. Without it, a streaming response may not show how many tokens were cached, even though the tokens are still billed. For Chat Completions and Completions, the final chunk of the stream then includes the usage object. The Responses API returns usage in the final response.completed event. ```python theme={null} from openai import OpenAI client = OpenAI( base_url="https://api.tokenfactory.nebius.com/v1/", api_key="", ) response = client.chat.completions.create( model="", messages=[ {"role": "system", "content": ""}, {"role": "user", "content": ""}, ], ) usage = response.usage cached = usage.prompt_tokens_details.cached_tokens print(f"{cached} of {usage.prompt_tokens} prompt tokens were cached") ``` ### Check a charge If you think a request was billed incorrectly, compare the usage object in the response with the line items in your consumption report, and contact support with the request ID. Billing is based on the cached token count reported for each request. For streaming requests, make sure stream\_options.include\_usage is set, so that the response contains usage to compare against. ## Get more cache hits * Put static content first (system prompt, tool definitions, examples, documents) and dynamic content last (the user's latest message). * Keep the prefix identical between requests: the same text, the same order, and the same tool definitions. Even a small change early in the prompt can prevent a cache hit for everything after it. * In multi-turn conversations, append new messages to the end of the history instead of rewriting earlier messages. * Send requests that share a prefix close together in time, because cache entries are evicted over time. * Use the same model for requests that share a prefix. The cache is not shared between models. ## Best-effort caching and no guarantees Caching is best-effort. Nebius doesn't provide a service level agreement (SLA) for caching, and doesn't guarantee a cache hit, a minimum cache-hit rate, a specific discount or cost saving, or how long a prefix stays cached. The cached input price is the price per token for tokens that were served from the cache. It is not a promise that any share of your tokens will be cached. In particular: * A repeated request can return cached\_tokens: 0. This is a valid result, not an error. Possible reasons include cache eviction, the request being served by a different replica, or a model or service update. * cached\_tokens does not have to match the length of the repeated part of your prompt. The engine caches in internal blocks, so the value is usually rounded down to a block boundary. * The first request with a new prefix can still show some cached tokens, for example when it shares a chat template or prefix with other requests. * Changing the model, chat template, or tokenization parameters changes the effective prefix and can reduce cache hits. ## Data, privacy, and cache scope ### What is cached The cache holds temporary computed state that the model derives from your prompt. It doesn't hold prompt or response text, can't be read back into text, and isn't exposed through any API. Frequently reused prefixes stay cached longer, and less-used ones are removed. How long a prefix stays cached isn't guaranteed. An unused prefix may be removed after only a few minutes, and entries can be evicted at any time under load. ### Zero data retention (ZDR) Caching works the same way for accounts with zero data retention (ZDR) enabled. Prompts and responses are still not stored or logged, so ZDR commitments stay in place. #### Cache scope * **Serverless:** the cache is shared within a model. A request gets a cache hit only if its prompt starts with exactly the same content as a recent request to the same model. This doesn't depend on the organization, project, or API key. A cache hit doesn't reveal who sent the earlier request or what the rest of its prompt contained. * **Dedicated Endpoints:** prompt caching works the same way as on Serverless, but each customer has an isolated cache that is never shared with other customers. Don't rely on caching as an access control or isolation boundary. Don't put secrets in the beginning of a prompt expecting them to be isolated from other requests. If you use prompt\_cache\_key, note that it only helps route requests to the server that holds the cache. It isn't an access key or a security boundary. ### What Nebius Token Factory records Nebius Token Factory records only per-request token counts (input, cached input, and output) and the resulting cache-hit share. These records are used for billing and for resolving billing disputes, in the same way as input and output token counts today. They don't contain prompt fragments, token IDs, prefix hashes, cache keys, or session identifiers. Cached tokens don't introduce new data collection. For details on how Nebius Token Factory handles your data, see the [Privacy policy](https://docs.nebius.com/legal/privacy) and your agreement with Nebius Token Factory. ### OpenRouter and other routers Requests that arrive through OpenRouter are served by Nebius Token Factory as Serverless endpoints traffic, so the same cache scope applies. There is no separate cache isolation for each downstream OpenRouter customer. ## Limitations * Cached input pricing applies to Serverless text-generation requests: Chat Completions, Completions, and the Responses API. * Embeddings, rerank, and image APIs don't report or bill cached tokens. * Batch inference is not covered. * You can't configure cache keys, cache lifetime (TTL), or explicitly cache a prompt. * Cached input pricing isn’t applied to Dedicated Endpoints. Prompt caching itself works on Dedicated Endpoints in the same way, but they are billed per GPU hour, so there is no separate cached input price and your bill doesn’t change. Cached tokens there improve throughput and latency. # Nebius Token Factory Cookbook Source: https://docs.tokenfactory.nebius.com/cookbook/overview Examples and recipes to use with Token Factory ## Repository The GitHub repository can found here: [https://github.com/nebius/token-factory-cookbook](https://github.com/nebius/token-factory-cookbook) ```shellscript theme={null} git clone https://github.com/nebius/token-factory-cookbook ``` ## APIs and Models > [card] [Model cards](https://github.com/nebius/token-factory-cookbook/tree/main/models) > > GPT-OSS, Qwen3 and more > [card] [APIs](https://github.com/nebius/token-factory-cookbook/tree/main/api) > > openAI, LiteLLM, hugging face, aisuite ## Agents > [card] [Starter Agents](https://github.com/nebius/token-factory-cookbook/tree/main/agents#agents-by-functionality) > [card] [Advanced Agents](https://github.com/nebius/token-factory-cookbook/tree/main/agents#agents-by-functionality) > [card] [MCP Agents](https://github.com/nebius/token-factory-cookbook/tree/main/agents#agents-by-functionality) ### Agents by framework > [card] [Agno](https://github.com/nebius/token-factory-cookbook/tree/main/agents#agno) > [card] [Camel AI](https://github.com/nebius/token-factory-cookbook/tree/main/agents#camel-ai) > [card] [Crew AI](https://github.com/nebius/token-factory-cookbook/tree/main/agents#crewai) > [card] [Google ADK](https://github.com/nebius/token-factory-cookbook/tree/main/agents#google-adk-agent-development-kit) > [card] [Llama-Index](https://github.com/nebius/token-factory-cookbook/tree/main/agents#llama-index) > [card] [Pydantic](https://github.com/nebius/token-factory-cookbook/tree/main/agents#pydantic-ai) > [card] [Strands](https://github.com/nebius/token-factory-cookbook/tree/main/agents#strands-agent) [See all agent examples](https://github.com/nebius/token-factory-cookbook/blob/main/agents/README.md) ## RAG (Retrieval-augmented generation) > [card] [Chat with Documents](https://github.com/nebius/token-factory-cookbook/tree/main/rag/chat-with-pdf) > > Ask questions about PDF documents > [card] [RAG pipeline](https://github.com/nebius/token-factory-cookbook/tree/main/rag/rag-milvus-1) > > End to end RAG pipeline using vector databases > [card] [Content generation](https://github.com/nebius/token-factory-cookbook/tree/main/rag/content-gen-pipeline-qdrant) > > Create social posts and demo apps [All RAG examples](https://github.com/nebius/token-factory-cookbook/tree/main/rag) ## Finetuning and Distillation > [card] [Distillation](https://github.com/nebius/token-factory-cookbook/tree/main/distillation/distillation-1) > > Train a smaller model from a teacher > [card] [LORA finetuning](https://github.com/nebius/token-factory-cookbook/blob/main/AddLora.ipynb) > > Efficient training of models ## Fun > [card] [Fun images with LORA](https://github.com/nebius/token-factory-cookbook/tree/main/lora/lora-1) > > Create fun images using LORA adapters > [card] [Pelican challenge](https://github.com/nebius/token-factory-cookbook/tree/main/fun/pelican-riding-bicycle) > > A cool vibe benchmark for models ## Community and Apps > [card] [Events](https://github.com/nebius/token-factory-cookbook/blob/main/community/events.md) > > Hackathons, workshops > [card] [Community](https://github.com/nebius/token-factory-cookbook/blob/main/community/README.md) > > Contributions > [card] [Apps](https://github.com/nebius/token-factory-cookbook/blob/main/apps/README.md) > > Apps gallery # Import Chat Completions Source: https://docs.tokenfactory.nebius.com/data-lab/chat-completions Data Lab allows you to import historical **chat completion logs** into structured datasets for analysis and reuse. ### Source of chat completions Chat completions may come from: * API requests to Nebius Token Factory * Playground interactions Each completion may include: * Input messages (system, user, assistant, tool) * Model outputs * Metadata (model name, timestamps, token usage, errors, etc.) ### Zero Data Retention (ZDR) behavior Data import is subject to **Zero Data Retention** settings: * When ZDR is **enabled**, chat completion logs are not stored. * When ZDR is **disabled**, chat completion logs are collected and available for import. * If ZDR was enabled during part of the selected time range, only the periods with ZDR disabled will be imported. > [!NOTE] > > Importing a time range where ZDR was fully enabled will result in an empty import. ### Import workflow 1. Click **Import completions** 2. Specify the time range, model, and a name for the import 3. Click **Start import** to initiate the process 4. Imported completions appear as a new dataset in Datasets tab inside Data Lab Imported datasets can then be: * Filtered and transformed by sql * Downloaded * Used for batch inference or fine-tuning ### Typical use cases * Reviewing real production prompts and responses * Debugging incorrect or unexpected model behavior * Building evaluation datasets from real usage * Preparing training data without manual logging # Data Processing Source: https://docs.tokenfactory.nebius.com/data-lab/data-processing Data Lab works with several types of data, such as inference logs (chat completions), uploaded datasets, batch inference outputs, and fine-tuning results. To ensure full transparency, this section explains how your data is processed, your level of control, and where processing takes place. ### **How We Handle Your Data** For all data you submit or generate through Data Lab, including: * Inference logs - inputs and outputs (unless you enable Zero Data Retention) * Uploaded datasets * Filtered datasets * Batch inference outputs Nebius Token Factory acts as a **Data Processor** under the terms of our [Data Processing Agreement (DPA)](https://docs.tokenfactory.nebius.com/legal/dpa). ### Data retention Data Lab retains your data as follows:
Data type Retention
Raw completions not exported to a dataset Deleted automatically after 1 year
Datasets you upload Kept until you delete them
Datasets created by exporting completions Kept until you delete them
Datasets created from completed batch jobs Kept until you delete them
If you want to keep completions for longer than one year, export them to a dataset before they expire. Datasets have no automatic expiration, so you can delete them at any time. ### **Processing Location** All Data Lab processing activities, including handling of logs, datasets, batch outputs, and training data, are performed exclusively in the EU-North1 (Finland) data center. ### **Future Changes** If hosting locations change, we commit to notifying you in advance so you can review compliance implications and adjust your workflows if needed. # Datasets Source: https://docs.tokenfactory.nebius.com/data-lab/datasets Datasets in [**Data Lab**](https://tokenfactory.nebius.com/datalab/datasets) provide a reusable data layer for working with model inputs, outputs, training data, and production inference data. You can upload your own data, connect data from S3-compatible storage, create datasets from inference logs, and reuse existing datasets for [**fine-tuning**](https://docs.tokenfactory.nebius.com/post-training/overview). ## What is a dataset? A dataset is a structured collection of rows with a defined schema. Datasets in Data Lab can come from several sources: * **Uploaded datasets:** data uploaded directly to Data Lab. * **S3-connected datasets:** data connected from S3-compatible object storage. * **Imported inference logs:** historical Chat Completions imported from your Token Factory usage. * **Derived datasets:** datasets created by filtering or transforming another dataset. Once created, datasets appear in the **Datasets** section of Data Lab and can be inspected, filtered, downloaded, or used for [**fine-tuning**](https://docs.tokenfactory.nebius.com/post-training/overview). ## Creating a dataset ### Upload a dataset You can upload structured data directly from your computer. To upload a dataset: 1. Open **Data Lab → Datasets**. 2. Click **Add dataset**. 3. Select the file you want to upload. 4. Specify the dataset name. 5. Start the upload. For large datasets, Data Lab uses multipart upload so the file can be transferred in multiple parts instead of requiring a single large request (better to use API). The dataset becomes available after the upload has been processed successfully. ### Connect a dataset from S3 You can also work with data stored in **S3-compatible object storage**. This is useful when your datasets are already stored externally or are too large to move between systems as part of every workflow. Data Lab works with the dataset and its metadata without creating an additional raw-data copy of the source S3 object. This allows you to: * keep your existing storage architecture; * avoid unnecessary data duplication; * inspect and process datasets through Data Lab; * use the same data for [**fine-tuning**](https://docs.tokenfactory.nebius.com/post-training/overview). ### Create a dataset from inference logs Data Lab can convert historical Chat Completions into a dataset. You can select a time range and model and create a structured dataset containing available request and response information. Imported data may include: * id: string * choice\_id: integer * prompt: json * completion: json * dialogue: json * started: string * completed: string * raw\_prompt: json * raw\_completion: json * completion\_tokens: integer * prompt\_tokens: integer * ai\_project\_id: string * model\_flavor\_id: string * tenant\_user\_account\_id: string * error\_string: string If **Zero Data Retention (ZDR)** was enabled when requests were made, those inference logs are not available for import. ## Supported formats Data Lab currently supports the following dataset formats: | Format | Direct upload | S3 connection | | :- | :- | :- | | JSON Lines (`.jsonl`) | Supported | Supported | | Parquet (`.parquet`) | Not supported | Supported | ### JSON Lines JSON Lines (`JSONL`) is supported both for **direct uploads** and for datasets connected from **S3-compatible storage**. Each line in a JSONL file must contain a valid JSON object. Example: ```text theme={null} {"prompt":"Capital of Australia","completion":"Canberra"} {"prompt":"Capital of Serbia","completion":"Belgrade"} ``` JSONL is well suited for model-related datasets because it can represent both simple records and nested structures such as conversation messages. ### Parquet Parquet datasets are supported when connected from **S3-compatible storage**. Direct upload of Parquet files is currently not supported. Parquet is recommended for large structured datasets already stored in object storage, particularly when efficient storage and analytical processing are important. # Fine-tuning Source: https://docs.tokenfactory.nebius.com/data-lab/fine-tuning [**Data Lab**](https://tokenfactory.nebius.com/datalab) offers tools for preparing and managing datasets for fine-tuning workflows. For more information on fine-tuning, see the [Post-training documentation](https://docs.tokenfactory.nebius.com/post-training/overview). ### Dataset preparation You can create fine-tuning datasets by: * Importing and filtering inference logs (chat completions) * Uploading and filtering structured datasets Prepared datasets are stored in Data Lab and can be reused across fine-tuning jobs. ### Reproducibility By keeping datasets versioned and centralized, Data Lab enables: * Consistent training inputs across experiments * Easier comparison of fine-tuning results * Safer iteration without accidental data changes ### Data location and compliance * Fine-tuning jobs run in **EU or US data centers**, for more information, see our [Legal Quick Guide](https://docs.tokenfactory.nebius.com/legal/legal-quick-guide#4-data-location:-where-your-data-is-processed) (Data Location part) * All datasets are stored centrally in the eu-north1 (Finland) data center. This design balances compliance requirements with operational simplicity. ### Typical use cases * **Adapting models** to internal domain-specific data * **Improving response quality** for specific tasks * Training student models for **distillation pipelines** # Overview Source: https://docs.tokenfactory.nebius.com/data-lab/overview [**Data Lab**](https://tokenfactory.nebius.com/datalab) is the unified workspace inside Nebius Token Factory for working with inference logs (chat completions) and datasets. It centralizes everything related to **inference logs, dataset preparation, batch inference outputs and fine-tuning**, providing a consistent, clean, and reusable data layer for all model-development workflows. Data Lab reduces reliance on manual scripts and custom pipelines by bringing your data into a single, unified workflow: * A single place to **view, filter, and export inference logs (chat completions).** * A unified interface for **preparing datasets via SQL queries.** * Reusable datasets for **batch inference and fine-tuning.** ### What lives inside Data Lab Data Lab stores and manages several types of data: * **Inference Logs:** automatically collected chat completions generated via API or Playground (unless Zero Data Retention is enabled). * **Filtered Datasets:** datasets created from inference logs using sql queries. * **Uploaded Datasets:** user-provided datasets uploaded manually. * **Batch Inference Outputs:** results generated by batch inference jobs. * **Fine-tuning Outputs:** artifacts produced by fine-tuning jobs, including model checkpoints and the resulting fine-tuned model. > [card] [Import Chat Completions](/data-lab/chat-completions) > > Data Lab allows you to import historical chat completion logs into structured datasets for analysis and reuse > [card] [Fine-tuning](/data-lab/fine-tuning) > > Fine-tuning workflows support preparing, validating, and managing training datasets through Data Lab interface > [card] [Data Processing](/data-lab/data-processing) > > This section explains how your data is processed, where it is processed, and what level of control you have > [card] [Datasets](/data-lab/datasets) > > You can upload your own data, connect data from S3-compatible storage, or create datasets from inference logs # Overview Source: https://docs.tokenfactory.nebius.com/integrations/overview Nebius Token Factory third-party integrations for inference ## APIs In addition to the [playground](https://docs.tokenfactory.nebius.com/ai-models-inference/playground) and the OpenAI-compatible [API](https://docs.tokenfactory.nebius.com/api-reference/introduction), Nebius Token Factory provides integrations with multiple third-party API providers. > [card] [AIsuite](/integrations/api/aisuite) > [card] [Llama-Index](/integrations/frameworks/llama-index/overview) > [card] [Hugging Face](/integrations/api/hugging-face) > [card] [LiteLLM](/integrations/api/litellm) ## API Routers > [card] [Open Router](/integrations/api-routers/openrouter) > [card] [Hugging Face](/integrations/api/hugging-face) > [card] [Portkey](/integrations/api-routers/portkey) ## AI Application Frameworks > [card] [Llama-Index](/integrations/frameworks/llama-index/overview) > [card] [Langchain](/integrations/frameworks/langchain) ## Agent Frameworks > [card] [Agno](/integrations/agents/agno) > [card] [Camel AI](/integrations/agents/camelai) > [card] [CrewAI](/integrations/agents/crewai) > [card] [Google ADK](/integrations/agents/google-adk) > [card] [Llama-Index](/integrations/agents/llama-index) > [card] [Pydantic](/integrations/agents/pydantic) > [card] [Strands](/integrations/agents/strands) [All agents examples](https://github.com/nebius/token-factory-cookbook/tree/main/agents#readme) ## Agentic Search > [card] [Tavily](/integrations/search/tavily) ## Coding Assistants > [card] [Cline](/integrations/coding/cline) > [card] [Continue](/integrations/coding/continue) > [card] [Cursor](/integrations/coding/cursor) > [card] [Kilo Code](/integrations/coding/kilo) > [card] [VSCode](/integrations/coding/vscode) > [card] [Zed](/integrations/coding/zed) ## Tools > [card] [Linkup](/integrations/tools/linkup) ## Developer Tools > [card] [Postman](/integrations/dev-tools/postman) ## Observability > [card] [Helicone](/integrations/observability/helicone) > [card] [Keywords AI](/integrations/observability/keywords-ai) # Model Deprecations: June 2026 Source: https://docs.tokenfactory.nebius.com/june-2026-deprecation-notice Models removed from Token Factory Serverless in June 2026. > [!NOTE] > > **Effective June 22, 2026:** > > * Affected Serverless models are no longer available via API or Playground. > * Dedicated Endpoints were unaffected by this change. ## What to Know The following models were removed from Token Factory Serverless on **June 22, 2026**. They can no longer be selected in the Playground or used for Serverless API requests. * This change only affected Serverless usage. * Token Factory does not automatically reroute requests from deprecated models. * Dedicated endpoints were unaffected by this change. | Deprecated Models | | - | | `deepseek-ai/DeepSeek-V3.2` | | `deepseek-ai/DeepSeek-V3.2-fast` | | `MiniMaxAI/MiniMax-M2.5-fast` | | `moonshotai/Kimi-K2.5` | | `moonshotai/Kimi-K2.5-fast` | | `openai/gpt-oss-120b-fast` | | `PrimeIntellect/INTELLECT-3` | | `Qwen/Qwen3-235B-A22B-Thinking-2507-fast` | | `Qwen/Qwen3-Next-80B-A3B-Thinking-fast` | | `Qwen/Qwen3.5-397B-A17B-fast` | | `zai-org/GLM-5` | ## Consider a Dedicated Endpoint For production workloads that need guaranteed stability or custom configurations, we recommend [Dedicated Endpoints](https://tokenfactory.nebius.com/?modals=create-dedicated-endpoint "https://tokenfactory.nebius.com/?modals=create-dedicated-endpoint") which provide: * Full control over model version and deployments. * Predictable performance and scaling * Enterprise-grade reliability and isolation To learn more about dedicated endpoints or for help getting started, our team is ready to help: 👉 [Contact Token Factory Sales](https://nebius.com/services/token-factory/enterprise-grade-inference?_gl=1*1d02gz7*_gcl_aw*R0NMLjE3NjY1MDAzMzEuQ2p3S0NBaUFtS25LQmhCckVpd0FhcUFuWnhlWUQ5SnlFVW9hS3Q0UUNOZ1ZpRDQzSms0clNFQVdRRTVHTGV4bHU5anNsUFQwNDFjTVBCb0N0UkVRQXZEX0J3RQ..*_gcl_au*MTM3MTMzODczMi4xNzY2NDc5NjA3LjE1MzYzOTEyOTAuMTc3NDAwNjAxMS4xNzc0MDA2MDEw#token-factory-enterprise-sales-form "https://nebius.com/services/token-factory/enterprise-grade-inference?_gl=1*1d02gz7*_gcl_aw*R0NMLjE3NjY1MDAzMzEuQ2p3S0NBaUFtS25LQmhCckVpd0FhcUFuWnhlWUQ5SnlFVW9hS3Q0UUNOZ1ZpRDQzSms0clNFQVdRRTVHTGV4bHU5anNsUFQwNDFjTVBCb0N0UkVRQXZEX0J3RQ..*_gcl_au*MTM3MTMzODczMi4xNzY2NDc5NjA3LjE1MzYzOTEyOTAuMTc3NDAwNjAxMS4xNzc0MDA2MDEw#token-factory-enterprise-sales-form") ## Need Help? If you need assistance migrating, choosing the right model or getting started with dedicated endpoints our team is ready to help. 👉 [Contact Token Factory Support](mailto:tokenfactory-support@nebius.com) # Legal Quick Guide Source: https://docs.tokenfactory.nebius.com/legal/legal-quick-guide ## 1. Introduction: Our Commitment to Your Privacy At **Nebius Token Factory**, your trust is our top priority. We are committed to protecting your data, respecting your privacy, and operating in full compliance with applicable laws, including the General Data Protection Regulation (GDPR). This guide provides clear, plain-language answers to your most common questions about how we handle your data, where it is processed, and the rights and controls you have as a user. **Please note:** this guide is a summary for your convenience. It does not amend or replace our Terms of Service, Data Processing Agreement (DPA) or Privacy Policy; in case of any inconsistency, those documents prevail. ## 2. Who You Contract With Your contract for Nebius Token Factory is with the applicable Nebius entity identified in the relevant Terms of Service. That entity also acts as the Data Processor under the applicable DPA, which is governed by the law specified in the Terms of Service, without prejudice to the governing law and jurisdiction applicable under the Standard Contractual Clauses. The contracting entity is part of the Nebius group, whose publicly listed parent company is Nebius Group N.V. (NASDAQ: NBIS). ## 3. Data Processing: What Happens to Your Data To provide our service, we handle different types of data. It is important to understand our role in each case: **3.1. Data Controller:** for your account information (e.g., email address, billing details), we act as the Data Controller: we determine how this data is used for authentication, billing and communication with you. **3.2. Data Processor:** for the content you submit to our model inference and fine-tuning endpoints via the API or web interface (prompts, datasets, etc.) and the output you receive, we act as the Data Processor under our DPA. You are the Data Controller and remain in full control of this data. The detailed subject matter, duration, categories of data subjects and personal data are set out in Annex 1 of the DPA. **3.3. Speculative Decoding:** to improve output speed, your inputs (prompts) and the corresponding outputs may be stored and used for Speculative Decoding. You have complete control over this and can switch it off (see Section 4). * **How Speculative Decoding works and why we need your data:** this feature speeds up inference by introducing a draft model. The draft model generates multiple candidate tokens, and the main model only verifies or corrects them. This reduces the number of expensive forward passes and improves throughput. It is enabled by default for best performance; you can opt out at any time by enabling Zero Data Retention. Enabling Zero Data Retention may impact the level of service provided (e.g., inference speed). ## 4. Your Controls: Data Retention, Opt-Outs & Deletion **4.1. Zero Data Retention (ZDR)** For maximum privacy and control, you can enable Zero Data Retention in your account settings. * **Scope:** ZDR applies at the organization level and covers all projects and endpoints within your organization. Enabling or disabling ZDR is your responsibility as the account owner. * **What it means:** with ZDR enabled, your inputs (prompts) and outputs (responses) are not stored on our systems after each request is processed – no retained copy exists beyond ephemeral in-flight processing. * **No training, no Speculative Decoding:** with ZDR enabled, your data is not used for Speculative Decoding and is not used to train, fine-tune or improve any model – whether ours or a third party's. * **How to enable it:** activate Zero Data Retention on your account profile page. * **Written confirmation:** if you need written confirmation of your organization's ZDR status (e.g., for a data-protection review), contact our support team or your account manager. **4.2. Default Behavior** Unless you enable Zero Data Retention, we keep your inputs and outputs to speed up inference using the Speculative Decoding technique described in Section 3. Your content is not used to train any models in either mode. **4.3. Return & Deletion at End of Contract** When you stop using the service, you decide what happens to your data: upon termination or expiration of the services, we will delete or return Customer Personal Data at your choice, unless retention of certain data is required by applicable law (DPA, Section 7). ## 5. Data Location: Where Your Data Is Processed **5.1. Public endpoints: No Region Commitment** For public model endpoints, the Region field shows **Global**. The processing location is decided dynamically, is not tied to any single data center, and can change at any time without prior notice. If your integration relies on a region-specific `base_url` (e.g. an endpoint URL containing `us-central1`), that URL may stop working if the processing region changes. Public endpoints are intended for testing and non-critical workloads where this variability is acceptable, and are **not** intended for production use cases that require a stable, predictable region. If you need assurance about where requests are processed, for compliance, latency, performance or capacity reasons, deploy the model on a Dedicated Endpoint in the region of your choice (see Section 5.2). **Storage after processing:** real-time processing and subsequent storage are distinct. If you have not enabled Zero Data Retention (see Section 4), the inputs and outputs retained for Speculative Decoding are stored in Finland (EU), regardless of where real-time processing takes place. With ZDR enabled, no inputs or outputs are retained. **5.2. Dedicated Endpoints: Region Commitment** Unlike public endpoints, which offer no region guarantee (see Section 5.1), for dedicated endpoints the data-center region is fixed as part of the endpoint configuration – and it is a contractual commitment: under Section 6.1 of our DPA, we process your personal data within the region you selected for your dedicated endpoint. * We do not use multi-region routing, load balancing, or automatic overflow/failover to other regions for dedicated endpoints: inference runs only in the region you chose. * If your dedicated endpoint is configured in the EU, the inference content and related metadata remain within that region. **5.3. Fine-Tuning Data Location & Storage** Fine-tuning workloads have fixed processing locations, and all resulting data is stored centrally in the EU to ensure consistent compliance and governance: * **Data storage (global policy):** regardless of customer origin (EU, US, or other regions), all fine-tuning datasets, artifacts, and model outputs are stored exclusively in EU data centers. * **Processing for EU customers:** fine-tuning jobs submitted by EU users are processed in EU data centers, and their data is stored in the EU. * **Processing for US customers:** fine-tuning jobs submitted by US users are processed in US data centers, but all data is stored in the EU. Fine-tuning does not offer regional selection options, unlike inference endpoints. **5.4. Future Changes** We notify customers in advance of changes that may affect their compliance posture: * **Terms of Service and DPA changes:** we provide notice of any changes to our Terms of Service, including the DPA. Previous versions of our legal documents remain available in the online archive on the documentation site. * **Sub-processor changes:** at least fifteen (15) days' prior notice of any addition or replacement of a subprocessor. * **Model deprecations:** deprecations of models are announced in advance so you can migrate your workloads. ## 6. Sub-Processors Like every cloud provider, we rely on carefully selected sub-processors – both Nebius group companies and external providers – for parts of the service such as cloud infrastructure, inference capacity, customer support, payments and billing. * **Current list:** we maintain a public, up-to-date Sub-processor List showing each sub-processor's role and location, together with the list's effective date: [https://docs.nebius.com/legal/sub-processors\_tofa](https://docs.nebius.com/legal/sub-processors_tofa). * **Safeguards:** each sub-processor is bound by a written agreement imposing data-protection obligations no less protective than those in our DPA. * **Advance notice of changes:** we will give you at least fifteen (15) days' prior notice before adding or replacing a sub-processor. You may object on reasonable data-protection grounds; if no mutually acceptable solution is found, you may terminate the affected services and receive a pro-rata refund of prepaid, unused fees. ## 7. International Data Transfers * **Standard Contractual Clauses (SCCs):** where personal data protected by the GDPR, UK GDPR or Swiss FADP is transferred to a country without an adequacy decision, the transfer is governed by the EU Standard Contractual Clauses (Commission Implementing Decision (EU) 2021/914), which are incorporated into our DPA. This also covers administrative, maintenance and support access to data from outside the EEA – for example, by Nebius group entities in the United States, Israel or Serbia listed in the Sub-processor List. * **United Kingdom and Switzerland:** transfers of UK-protected data are additionally covered by the ICO's International Data Transfer Addendum, and Swiss-protected data by the Swiss adaptations, both set out in Annex 2 of the DPA. * **EU-US Data Privacy Framework (DPF):** we are certified under the EU-US Data Privacy Framework, which enables compliant transfers of personal data from the EU/EEA to the United States in addition to other available transfer mechanisms. As a DPF-certified organization, we adhere to the DPF Principles and maintain safeguards designed to ensure an appropriate level of protection for EU personal data. ## 8. Compliance & Certifications **8.1. GDPR Compliance** We are fully compliant with the General Data Protection Regulation (GDPR). Our practices and policies are built to meet these rigorous requirements for data protection. **8.2. Data Processing Agreement (DPA)** We provide a DPA to all our customers. To keep the process simple, the DPA is incorporated directly into our Terms of Service: by signing up and agreeing to the Terms of Service, you are covered by the DPA – no separate signature is needed. If your procurement or regulatory process requires a countersigned copy of the DPA or additional contractual arrangements, contact your account manager or our support team. **8.3. Certifications** We are a certified company holding **ISO 27001**, **ISO 27701** and **SOC 2 Type II** certifications. These internationally recognized standards demonstrate our commitment to information security, privacy, and operational resilience. For details, visit our Trust Center: [https://nebius.com/trust-center](https://nebius.com/trust-center) . **8.4. Requesting Audit Reports** Audit reports and certificates (e.g., the SOC 2 Type II report) are available through our Trust Center; certain reports are shared under a non-disclosure agreement. If a third party – such as an external risk assessor – requests reports on your behalf, we will ask for your authorization first. In addition, under the DPA you may request, in writing and at no cost, documentation reasonably necessary to demonstrate our compliance, and you may commission an audit by an independent, suitably qualified auditor with at least 30 days' notice, once per calendar year. **8.5. HIPAA Compliance** We also provide secure services to help customers meet the requirements of the U.S. Health Insurance Portability and Accountability Act (HIPAA). More details: [https://docs.nebius.com/legal/hipaa](https://docs.nebius.com/legal/hipaa). ## 9. Security, Audits & Incident Response * **Security measures:** we implement and maintain appropriate technical and organizational measures, summarized in Annex 3 of the DPA. They include encryption at rest and in transit, access management based on need-to-know, least privilege and segregation of duties, logging and audit trails, physical security of data centers, personnel background checks and confidentiality training, change management, and business-continuity plans. * **Breach notification:** we will notify you without undue delay after becoming aware of a security breach affecting your personal data and will provide the necessary information and reasonable assistance. ## 10. Sensitive & Regulated Data * **Special-category personal data (Art. 9 GDPR):** our DPA expressly contemplates that Customer Content may include special categories of personal data – such as health data or biometric data – the extent of which you determine and control (DPA Annex 1(B)). As the Data Controller, you are responsible for ensuring a lawful basis and for any required notices, consents or authorizations before submitting such data. * **Recommended controls:** for sensitive workloads, or any production workload that depends on a stable, known processing region, we recommend enabling Zero Data Retention and using a dedicated endpoint in your preferred region (see Sections 4 and 5). Public endpoints should not be relied on for such workloads, as their processing region can change without notice. * **US healthcare data:** for HIPAA-regulated workloads, see our HIPAA guideline (Section 8.5). ## 11. Ownership & Copyright You own what you create. We claim no rights to the intellectual property you develop on our platform. * You retain all ownership rights to your input data and datasets. * You retain all ownership rights to any fine-tuned and distilled models you create. * You retain all ownership rights to the content generated by the models from your inputs. * You acknowledge that your outputs may not be unique, and other users of the service may receive the same or similar outputs. ## 12. Key Documents & Contacts * **Nebius Services Agreement:** [https://docs.nebius.com/legal/agreement](https://docs.nebius.com/legal/agreement) * **Privacy Policy:** [https://docs.nebius.com/legal/privacy](https://docs.nebius.com/legal/privacy) * **Data Processing Agreement:** [https://docs.nebius.com/legal/dpa](https://docs.nebius.com/legal/dpa) * **List of Sub-Processors:** [https://docs.nebius.com/legal/sub-processors\_tofa](https://docs.nebius.com/legal/sub-processors_tofa) * **HIPAA Guideline:** [https://docs.nebius.com/legal/hipaa](https://docs.nebius.com/legal/hipaa) * **Trust Center (certifications & reports):** [https://nebius.com/trust-center](https://nebius.com/trust-center) **Privacy contact:** [privacy@nebius.com](mailto:privacy@nebius.com) (Data Protection Officer). For written confirmations, countersigned documents or contractual addenda, contact your account manager or our support team. ## 13. Frequently Asked Questions (FAQ) ### Data Processing & Location **Will my dedicated endpoint ever process data in another region?** No. Under Section 6.1 of our DPA, we process your personal data within the region you selected for the dedicated endpoint. There is no multi-region routing or automatic overflow to other regions. **How will I be notified about changes in model hosting locations?** For dedicated endpoints and model deprecations, we announce changes proactively via email to all account owners and through notifications within the Nebius Token Factory platform. Public endpoints are the exception: their processing region is decided dynamically and can change at any time without advance notice, which is why public endpoints are not recommended for production workloads requiring a stable region. **Can I rely on a public endpoint for production traffic that needs a stable region?** No. Public endpoints run on shared infrastructure with a Region field of "Global," and the actual processing location can change at any time without notice. A region-specific `base_url` may stop working if this happens. For production workloads that depend on a stable region, use a Dedicated Endpoint instead (see Sections 5.1–5.2). **If my data is processed in the US, how do you ensure it complies with EU regulations like GDPR?** For any transfers to countries without an EU adequacy decision, we rely on legally established transfer mechanisms – in particular the Standard Contractual Clauses incorporated into our DPA – and we are certified under the EU-US Data Privacy Framework (see Section 7). ### Data Retention & Control **Is my data used to train your AI models?** No. We do not use your content to train, fine-tune or improve any AI models – ours or third parties'. Unless you enable Zero Data Retention, your inputs and outputs may be stored and used solely for Speculative Decoding (see Section 3), which does not involve training any model. **What happens if I don't enable Zero Data Retention?** Your API inputs and outputs may be stored and used for Speculative Decoding – and for no other purpose. **What happens to my data when I stop using the service?** Upon termination or expiration of the services, we delete or return Customer Personal Data at your choice, except where retention is required by applicable law. ### Legal & Compliance **Are you GDPR compliant?** Yes. We are fully committed to and compliant with the GDPR. **Do I need to sign a separate Data Processing Agreement (DPA)?** No. Our DPA is an integral part of our Terms of Service: by agreeing to the ToS, you are automatically covered. If you need a countersigned copy for your procurement or regulatory process, contact your account manager. **Who is my contracting party?** Your contracting entity is the applicable Nebius entity within the corporate group headed by Nebius Group N.V. (NASDAQ: NBIS), as identified in the relevant Terms of Service. The DPA is governed by the law specified in those Terms of Service, without prejudice to the governing law and jurisdiction applicable under the Standard Contractual Clauses. **How do I get your SOC 2 report or other security documentation?** Through our Trust Center ([https://nebius.com/trust-center](https://nebius.com/trust-center)); certain reports are provided under NDA. Requests from third-party assessors require your authorization. **How will I know if you change sub-processors?** We provide at least 15 days' prior notice of any addition or replacement of a sub-processor, and you have the right to object on reasonable data-protection grounds. **Can commitments such as ZDR or region pinning be recorded in my contract?** The region commitment for dedicated endpoints is already a binding term of the DPA, which forms part of your agreement. If you require additional contractual documentation – for example, an order form or addendum reflecting your ZDR configuration – contact your account manager. **Can I process health data or other special-category data?** Yes, subject to your responsibilities as Data Controller (lawful basis, notices, consents) – see Section 10. For sensitive workloads we recommend Zero Data Retention and a dedicated endpoint, for US healthcare data, see our HIPAA guideline. ### Copyright & Ownership **Who owns the content I generate or the models I fine-tune?** You do. You retain all intellectual property rights to your inputs, outputs, and any models you fine-tune or distill on our platform. Note that outputs may not be unique, and other users may receive the same or similar outputs. # Model Deprecations: November 2026 Source: https://docs.tokenfactory.nebius.com/november-2026-deprecation-notice Models soon leaving Token Factory Serverless with recommended migration paths. > [!NOTE] > > **On November 9, 2026:** > > * Affected Serverless models will no longer be available via API or Playground. > * Dedicated Endpoints for these models will be unaffected by this change. ## What to Know These models will be removed from Token Factory Serverless on **November 9, 2026**. After that date, you will not be able to select them in the Playground or send API requests using their model IDs. * This change only affects Serverless usage. [Dedicated Endpoints](https://tokenfactory.nebius.com/endpoints/create-dedicated-endpoint) are unaffected. * Token Factory does not automatically reroute requests from deprecated models. * Choose a replacement based on your workload, then test before migrating traffic. | Deprecating Model | **Recommended Replacement** | | - | - | | [`zai-org/GLM-5.1`](https://tokenfactory.nebius.com/models/catalog/text2text/zai-org%2FGLM-5.1) | [`zai-org/GLM-5.3`](https://tokenfactory.nebius.com/models/catalog/text2text/zai-org%2FGLM-5.3) | | [`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNVIDIA-Nemotron-3-Nano-30B-A3B) | [`nvidia/Nemotron-3_5-Lightning`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2FNemotron-3_5-Lightning) | | [`nvidia/nemotron-3-super-120b-a12b`](https://tokenfactory.nebius.com/models/catalog/text2text/nvidia%2Fnemotron-3-super-120b-a12b) | [`nvidia/Nemotron-3.5-Super-VL`](https://tokenfactory.nebius.com/models/catalog/image2text/nvidia%2FNemotron-3.5-Super-VL) | | [`deepseek-ai/DeepSeek-V4-Pro`](https://tokenfactory.nebius.com/models/catalog/text2text/deepseek-ai%2FDeepSeek-V4-Pro) | [`deepseek-ai/DeepSeek-V4-Pro-0813`](https://tokenfactory.nebius.com/models/catalog/text2text/deepseek-ai%2FDeepSeek-V4-Pro-0813) | | [`deepseek-ai/DeepSeek-V4-Flash-0731`](https://tokenfactory.nebius.com/models/catalog/text2text/deepseek-ai%2FDeepSeek-V4-Flash-0731) | [`deepseek-ai/DeepSeek-V4.1-Flash-1017`](https://tokenfactory.nebius.com/models/catalog/image2text/deepseek-ai%2FDeepSeek-V4.1-Flash-1017) | | [`deepseek-ai/DeepSeek-V4.1-Flash`](https://tokenfactory.nebius.com/models/catalog/image2text/deepseek-ai%2FDeepSeek-V4.1-Flash) | [`deepseek-ai/DeepSeek-V4.1-Flash-1017`](https://tokenfactory.nebius.com/models/catalog/image2text/deepseek-ai%2FDeepSeek-V4.1-Flash-1017) | | [`Qwen/Qwen3.5-397B-A17B`](https://tokenfactory.nebius.com/models/catalog/text2text/Qwen%2FQwen3.5-397B-A17B) | [`Qwen/Qwen3.8-27B`](https://tokenfactory.nebius.com/models/catalog/image2text/Qwen%2FQwen3.8-27B) | | [`Qwen/Qwen3-235B-A22B-Instruct-2507`](https://tokenfactory.nebius.com/models/catalog/text2text/Qwen%2FQwen3-235B-A22B-Instruct-2507) | [`Qwen/Qwen3-30B-A3B-Instruct-2507`](https://tokenfactory.nebius.com/models/catalog/text2text/Qwen%2FQwen3-30B-A3B-Instruct-2507) | | [`moonshotai/Kimi-K2.6`](https://tokenfactory.nebius.com/models/catalog/image2text/moonshotai%2FKimi-K2.6) | [`moonshotai/Kimi-K3`](https://tokenfactory.nebius.com/models/catalog/image2text/moonshotai%2FKimi-K3) | | [`moonshotai/Kimi-K2.7-Code`](https://tokenfactory.nebius.com/models/catalog/text2text/moonshotai%2FKimi-K2.7-Code) | [`moonshotai/Kimi-K3`](https://tokenfactory.nebius.com/models/catalog/image2text/moonshotai%2FKimi-K3) | | [`openbmb/MiniCPM-V-4_5`](https://tokenfactory.nebius.com/models/catalog/image2text/openbmb%2FMiniCPM-V-4_5) | [`nvidia/Nemotron-3.5-Super-VL`](https://tokenfactory.nebius.com/models/catalog/image2text/nvidia%2FNemotron-3.5-Super-VL) | ## Preparing to Migrate 1. Identify applications and workflows that send requests to a deprecating model ID. 2. Compare the replacement model's capabilities, performance and price. 3. Test prompts, inputs and workloads to verify the new model will work for your use cases. 4. Update the `model` and `base_url` values in your API requests, then verify the results. Refer to our [quick start guide](https://docs.tokenfactory.nebius.com/quickstart) for reference and up to date examples. ## Consider a Dedicated Endpoint For production workloads that need stable model versions or custom configurations, consider [Dedicated Endpoints](https://tokenfactory.nebius.com/endpoints/create-dedicated-endpoint), which provide: * Control over model versions and deployments. * Dedicated capacity and configurable scaling. * Workload isolation. To learn more about Dedicated Endpoints or for help getting started, contact our team: 👉 [Contact Token Factory Sales](https://nebius.com/services/token-factory/enterprise-grade-inference#token-factory-enterprise-sales-form) ## Need Help? If you need assistance migrating, choosing the right model or getting started with Dedicated Endpoints, our team is ready to help. 👉 [Contact Token Factory Support](mailto:tokenfactory-support@nebius.com) # Billing & Consumption Source: https://docs.tokenfactory.nebius.com/other-capabilities/billing-new ## Set up billing When you sign up for **Nebius Token Factory**, you are prompted to create a **billing account** during onboarding. Billing setup is mandatory—you cannot complete onboarding without it. **Setting up a billing account requires a bank card.** You can view and update your billing details at any time on the **Billing** page. *** ## Payment methods ### Bank card If your payment method is a bank card, you can manually top up your balance at any time. #### Automatic charging When using a bank card, Nebius Token Factory debits your balance in real time. Your card is automatically charged in either of the following cases: * At the start of the month, if your balance is negative * When the configured billing threshold is reached The charge amount is calculated to bring your balance back to zero. If a card charge fails, your account is **suspended**. To avoid service interruptions, ensure that your payment method remains valid and up to date. ### Bank transfer If your payment method is bank transfer, you can top up your balance manually. To do so, request a **proforma invoice** from the Nebius sales team. At the beginning of each month, you will also receive an invoice for the previous month’s usage. If your balance was negative at the end of that month, you must pay the invoice using the payment details provided. > **Note:** Bank transfers are available to companies only and are not supported for individual accounts. ### Changing your payment method * To change your bank card, go to **Organisation → Billing details**, then click **Edit**. * If you are a company, you can switch your payment method to **bank transfer** by contacting support. *** ## Topping up your balance To avoid automatic charging, you can manually top up your balance at any time: 1. Click **Top up** in the top-right corner of the header bar 2. Enter the amount to add, or choose the **Promo code** option 3. Review your card details and click **Continue** Once the top-up is completed, the funds are available immediately. ### Applying a promo code A promo code provides free Nebius Token Factory credits and is typically issued as part of a special offer. Promo codes usually have an expiration date—make sure to apply them before they expire. Promo codes **cannot be used to pay outstanding invoices**. Any unpaid invoices must still be settled separately. To apply a promo code: 1. In the navigation menu, click your **balance** 2. Click **Top up** 3. Select **With promo code** 4. Enter the promo code and click **Top up** After a successful application, your balance increases by the promo code amount.\ You can verify this in the **Transactions** section. *** ## Consumption Monitoring You can monitor spending across projects, services, and resources on the **Usage** tab of the **Organisation** page in the web console. To view detailed charts: 1. Click the chart icon on the right 2. Select an entity type and time period using the filters 3. Hover over chart columns to see usage details for a specific period You can further refine results using **region**, **project**, **service**, and **product** filters. *** ## Taxes Depending on your or your company location, the usage of Nebius AI Cloud resources might be subject to taxes such as Value Added Tax (VAT). ### Netherlands Companies registered in the Netherlands and residents of the Netherlands are subject to 21% VAT. VAT amount is listed on invoices on a separate line in USD. We also convert it into EUR and show on another line — it is the same VAT in another currency. ### Another EU country > [tab] Company > > Nebius does not add VAT or other taxes to your charges. > [tab] Individual > > VAT amount is calculated in accordance with your country's tax law. It is listed on invoices on a separate line in USD and repeated on another line in EUR. ### United States For residents of Texas and Washington, Nebius calculates taxes in accordance with United States tax law. For details, see [State and Local Sales Tax Rates](https://taxfoundation.org/data/all/state/sales-tax-rates). Residents of other states are not charged. The tax amount is listed on invoices on a separate line in USD. ### The rest of the world > [tab] Company > > Nebius does not add VAT or other taxes to your charges. > [tab] Individual > > At the moment, Nebius does not add VAT or another taxes to your charges. > > In the future, we will calculate the taxes in accordance with your country tax law. The taxes amount will be listed on invoices on a separate line in USD. # Custom speculator Source: https://docs.tokenfactory.nebius.com/post-training/custom-speculator Use the Custom Speculator API to train a speculative decoding drafter for a supported base model in Token Factory. A custom speculator job produces a drafter artifact that can be served with vLLM for speculative decoding. ## Create a custom speculator job Create a fine-tuning job with `method.type="spec-draft"` and provide speculator hyperparameters under `method.spec_draft.hyperparameters`. ```python theme={null} from openai import AsyncOpenAI job_request = { "model": "Qwen/Qwen3-30B-A3B-Instruct-2507", "training_file": training_file, "method": { "type": "spec-draft", "spec_draft": { "hyperparameters": { "batch_size": 8, "learning_rate": 0.0075, "n_epochs": 1, "warmup_ratio": 0.1, "max_grad_norm": 1.0, "context_length": 8192, "loss": {"type": "kl"}, "num_decoding_heads": 3, "architecture": "eagle3_original", }, }, }, "seed": 2214, "suffix": "specdec-example", } client = AsyncOpenAI( base_url="", api_key="", ) job = await client.fine_tuning.jobs.create(**job_request) ``` ## Dataset format Only pretokenized datasets are supported. Upload a JSONL file where each line contains: * `input_ids` — array of token IDs. * `attention_mask` — array of `1`s and `0`s aligned with `input_ids`. * `labels` — array of target token IDs. Use `-100` to ignore a position in the loss. ```jsonl theme={null} {"input_ids": [1, 14, 52, 16], "attention_mask": [1, 1, 1, 1], "labels": [-100, -100, 52, 16]} {"input_ids": [160, 34, 129, 10432], "attention_mask": [1, 1, 1, 1], "labels": [160, 34, 129, 10432]} ``` ## Request fields ### Top-level fields | Field | Type | Required | Description | | - | - | - | - | | `model` | string | Yes | Base model to train the speculator against. | | `training_file` | string | Yes | Training dataset file ID. | | `method` | object | Yes | Fine-tuning method configuration. Use `type="spec-draft"`. | | `seed` | integer | No | Random seed for reproducibility. | | `suffix` | string | No | Custom suffix for the resulting job or artifact name. | ### Method fields | Field | Type | Required | Description | | - | - | - | - | | `method.type` | string | Yes | Must be `spec-draft`. | | `method.spec_draft.hyperparameters` | object | Yes | Speculator training hyperparameters. | ### Hyperparameters | Field | Type | Description | | - | - | - | | `batch_size` | integer | Training batch size. A large batch size (e.g. `32`) is recommended. | | `learning_rate` | number | Optimizer learning rate. `0.0075` is recommended for models under 100B parameters; use a lower value for larger models. | | `n_epochs` | integer | Number of training epochs. | | `warmup_ratio` | number | Fraction of total steps used for learning-rate warmup. | | `max_grad_norm` | number | Gradient clipping threshold. | | `context_length` | integer | Maximum sequence length used during training. | | `num_decoding_heads` | integer | Number of speculative decoding heads to train. Supported values: `1`–`7`. | | `architecture` | string | Drafter architecture. Supported value: `eagle3_original` & `eagle3`. | | `loss.type` | string | Speculator training loss. Supported values: `kl`, `lk_alpha`, `lk_hybrid`. | ## Supported architectures | Architecture | Description | | - | - | | `eagle3` | TokenFactory-optimized variant. Can only be served on the TokenFactory platform. | | `eagle3_original` | Reference implementation. Portable to any vLLM-supported platform. | ## Supported losses Set the training loss with `loss.type`. Supported values: * **`kl`** — Standard Kullback-Leibler divergence loss between drafter and target model logits. * **`lk_alpha`** — LK loss with KL disabled. * **`lk_hybrid`** — Weighted combination of KL and LK losses. ## Training metrics Custom speculator jobs report two categories of metrics: * **Loss metrics** for monitoring optimization and model behavior during training. * **Sampling performance metrics** for estimating speculative decoding quality and efficiency. > [!NOTE] > > Some per-head metrics are reported conditionally. For a given head, the metric is computed under the assumption that all previous speculative tokens were accepted. For example, metrics for head 4 are conditioned on tokens 1 through 3 being accepted. ### Loss metrics The following loss metrics are reported during training: | Metric | Description | | - | - | | `lk` (per head) | LK loss for each decoding head. | | `kl` (per head) | Kullback-Leibler divergence loss between drafter and target model logits. | | `cross_entropy` (per head) | Cross-entropy loss for each decoding head. | | `target_model_loss` | Cross-entropy loss of the target model. Useful for understanding how the target model behaves on the provided dataset. | | `draft_loss` | Main speculative decoding training loss reported for the job. | > [!NOTE] > > All of the losses above are reported regardless of which `loss.type` is selected. ### Sampling performance metrics Each decoding head reports the following sampling performance metrics: | Metric | Description | | - | - | | `acceptance_rate` | Expected probability that the speculative token from that head is accepted. | | `number_of_tokens` | Expected accepted token length. | | `system_efficiency` | Speculative decoding efficiency, measured as `#tokens / #decoding_heads`. | ### Metric variations Sampling metrics may be reported for multiple evaluation variations: > [accordion] default > > Standard sampling with `temperature=1.0`. Use this variation to understand expected acceptance behavior under normal sampling. ## Output artefacts A completed custom speculator job produces the following artifact structure: ```text theme={null} checkpoint/ model.safetensors # speculator weights config.json # speculator configuration ``` To download the resulting artefacts, see [Download checkpoints and model files](https://docs.tokenfactory.nebius.com/post-training/how-to-fine-tune#7-download-checkpoints-and-model-files). ## Serving with vLLM Serve the resulting artifact with vLLM by passing it through `--speculative-config`: ```bash theme={null} vllm serve meta-llama/Llama-3.1-8B-Instruct \ --speculative-config '{"model": "checkpoints/draft_heads/eagle3_custom_v1.0/", "num_speculative_tokens": 3, "method": "eagle3"}' ``` > [!WARNING] > > **Eagle weight tying.** For Eagle-based architectures, weights are tied across heads. Only one head's weights are stored in the artifact, even when the model was trained with multiple decoding heads (e.g. `num_decoding_heads=3`). > > As a result, the speculator can be served with any `num_speculative_tokens` value from `1` to `N`, but it typically performs best when `num_speculative_tokens` matches or is lower than the number of decoding heads used during training. ### Tuning `ntokens` Set `ntokens` close to the observed acceptance rate to balance speculation against compute overhead. For example, if `ntokens=7` yields an acceptance rate of \~3.86, dropping to `3` or `4` will typically improve throughput. # Dataset formats for fine-tuning Source: https://docs.tokenfactory.nebius.com/post-training/datasets You can create datasets for training a model. Nebius Token Factory supports the [JSON Lines](https://jsonlines.org/) format (`.jsonl`) for dataset files. You can use one of the following dataset types: * [Conversational](https://docs.tokenfactory.nebius.com/post-training/datasets#conversational-data) * [Instruction](https://docs.tokenfactory.nebius.com/post-training/datasets#instruction-data) * [Text](https://docs.tokenfactory.nebius.com/post-training/datasets#text-data) * [**Pretokenized**](https://docs.tokenfactory.nebius.com/post-training/datasets#pre-tokenized-data) The size limit for dataset files is **50GB** via Data Lab and 20GB via Files api. ## **Conversational data** You can train a model using chat-style data. Each training example is a single conversation, represented as one `messages` array. We \*\*expect the last message to be from the \*\*`assistant`, containing the final answer the model should produce for that conversation.\ \ **Basic example:** ```json theme={null} { "messages": [ { "role": "system", "content": "You are a friendly dinner planner." }, { "role": "user", "content": "What's for dinner tonight?" }, { "role": "assistant", "content": "What cuisine do you prefer?" }, { "role": "user", "content": "I wouldn't mind Italian." }, { "role": "assistant", "content": "Then let's try a new pasta!" } ] } ``` Examples of conversational datasets: * [olathepavilion/Conversational-datasets-json](https://huggingface.co/datasets/olathepavilion/Conversational-datasets-json/blob/main/Validation.jsonl) * [princefreddy/jsonL\_text\_to\_sql](https://huggingface.co/datasets/princefreddy/jsonL_text_to_sql/blob/main/chatbot_interactions.jsonl) ### Tool-augmented conversations You can also train the model on conversations that use tools (function calling). Each training example can optionally include a `tools` field that defines the tools available in that conversation. The schema should match what you plan to use at inference time. ```json theme={null} { "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather in a city.", "parameters": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } } } ], "messages": [ { "role": "system", "content": "You are a weather assistant." }, { "role": "user", "content": "What's the weather in Amsterdam?" }, { "role": "assistant", "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\": \"Amsterdam\"}" } } ] }, { "role": "tool", "tool_call_id": "call_1", "name": "get_weather", "content": "{\"temp_c\": 12, \"condition\": \"cloudy\"}" }, { "role": "assistant", "content": "It's about 12°C and cloudy in Amsterdam right now." } ] } ``` Key points: * `tools` is **optional**. Omit it for pure conversational data. * You may include **examples with tool calls** to teach the model: * when to call a tool, * how to format `tool_calls`, * and how to turn tool results into a final answer. * The \*\*final message in \*\*`messages`\*\*should always be an \*\* `assistant`**message** with the natural-language answer you want the model to produce (not a tool call). ## **Instruction data** You can specify prompts and the expected answers to them: ```bash theme={null} {"prompt": "Capital of Australia", "completion": "Canberra"} {"prompt": "Distance between Rome and Kuala Lumpur", "completion": "9703 km"} ``` Example of an instruction dataset: [Andzej-75/German\_RisingWorld\_prompt-text-rejected\_Jsonl](https://huggingface.co/datasets/Andzej-75/German_RisingWorld_prompt-text-rejected_Jsonl/blob/main/training_data_Lines.jsonl). ## **Text data** If you have **unstructured or non-chat data** (tasks, explanations, documents, QA pairs, etc.), you can train using plain text.\ Each training example is a single JSON line with a `text` field. Example (reasoning-style prompt/answer): ```json theme={null} {"text": "Given 10 items, find a fair way to divide them among 3 people.\n\n: Each person gets 3 items, and 1 item remains. You can rotate who gets the extra item over time to keep it fair."} {"text": "You are given a list of transactions. Classify whether the account is at risk of fraud.\n\nTransactions: [...]\n\n