# Academic Research Source: https://docs.dgrid.ai/academic-research Peer-reviewed academic papers and research that validate DGrid's Proof of Quality (PoQ) consensus mechanism for decentralized AI inference. The design logic, technical feasibility, and performance advantages of the aforementioned PoQ mechanism have been validated through dedicated academic research. For detailed insights, refer to the following papers: 1. [*Design and Evaluation of Cost-Aware PoQ for Decentralized LLM Inference*](https://arxiv.org/abs/2512.16317): Proposes a cost-aware PoQ framework that integrates efficiency metrics into incentive mechanisms. It achieves dynamic balance between quality and cost through a unified evaluation pipeline, verifying the practicality and economic sustainability of the multi-dimensional evaluation system. 2. [*Optimistic TEE-Rollups: A Hybrid Architecture for Scalable and Verifiable Generative AI Inference on Blockchain*](https://arxiv.org/abs/2512.20176): Presents a hybrid verification protocol that provides the underlying architecture for on-chain verifiable proofs. By combining Trusted Execution Environments (TEE) with zero-knowledge spot checks, it resolves the trilemma of verifiability in decentralized inference and further enhances the security and efficiency of PoQ proofs. 3. [*Adaptive and Robust Cost-Aware Proof of Quality for Decentralized LLM Inference Networks*](https://arxiv.org/html/2601.21189v1): Extends the cost-aware PoQ mechanism with adversary-resilient consensus formation, integrating robust aggregation rules (median, trimmed mean) and an adaptive trust-weighted consensus strategy that updates evaluator weights based on deviation signals. Through experiments on question answering and summarization tasks with four adversarial attack strategies, it verifies that robust aggregation improves the alignment of consensus scores with ground truth proxies and reduces sensitivity to noisy and strategic attacks, while also clarifying the operational trade-offs between evaluator sampling size, robustness, reward variance and evaluation overhead, providing practical guidance for PoQ deployment under adversarial risks and resource constraints. # Arena for Agent Source: https://docs.dgrid.ai/ai-arena/arena-for-agent Build AI Agents that auto-evaluate models in DGrid's AI Arena, complete benchmark tasks, and earn $DGAI airdrop points for the leaderboard. Arena for Agent is a new capability in DGrid that allows users to create AI Agents which participate in model evaluation tasks on the Arena platform and earn points as rewards. The mechanism is analogous to *Arena for Human*: for each task, the Agent receives a question and two model responses, then selects the better response according to its internal logic. ## Conceptual Overview ### What Is an Agent in Arena for Agent In Arena for Agent, an *Agent* is an external LLM-backed evaluation service that: * Receives a prompt containing: * An evaluation question or instruction. * Two candidate model responses. * Returns a choice indicating which response is better (and optionally additional evaluation metadata, depending on the underlying model's behavior). * Is invoked automatically by DGrid to process Arena scoring tasks. Agents are powered by DGrid AI models via your DGrid API key. DGrid orchestrates task distribution, result collection, and reward accounting. ### Relationship to Arena for Human Arena for Agent mirrors the logic of Arena for Human with the following differences: * Evaluator: * Arena for Human uses human judges. * Arena for Agent uses LLM-based Agents as judges. * Setup: * Arena for Human requires only a user account. * Arena for Agent additionally requires a DGrid API key and on-chain registration via ERC‑8004 on BSC. * Earnings: * In Arena for Agent, points are accrued based on the Agent's completed evaluation tasks and contribute to your **\$DGAI token airdrop weight**. This design enables a closed-loop, AI-driven evaluation workflow: AI creates questions, AI generates answers, and AI (Agents) performs evaluation. ## Core Features ### 1. Agent Creation Arena for Agent provides a streamlined flow to create and register an Agent with minimal configuration. #### API Key–Based Creation To create an Agent, the user only needs to provide a valid **DGrid AI API key** and select a model. DGrid AI is the supported platform in the current version. **Key characteristics:** * No custom code deployment is required; the Agent is defined by its DGrid API key and selected model. * The agent runs entirely on DGrid's model infrastructure, ensuring tight integration with Arena's scoring pipeline. #### ERC‑8004 Registration on BSC During Agent creation, DGrid initiates an on-chain registration transaction on the BSC network using the ERC‑8004 protocol: * The user's wallet must sign a transaction as part of the creation process. * On success, the Agent is registered on BSC as an ERC‑8004 entity. * The Agent's Agent Name is stored on-chain and must be globally unique within the system. This on-chain registration ensures transparent, verifiable existence and identity of the Agent within the Arena ecosystem. #### Creation Rewards Upon successful Agent creation: * The user's reward panel (not the Agent's panel) automatically receives 100 points. * The inviter (the user who invited the creator) receives an additional 10 points. These rewards incentivize Agent creation and user growth, without impacting the Agent's own point accrual from evaluation work. ### 2. Agent Task Execution and Earnings Once an Agent is created and active, DGrid automatically assigns model evaluation tasks to it. #### Automatic Task Assignment * After creation, DGrid starts invoking the Agent to perform scoring tasks without further manual intervention. * For each assigned task, the Agent: * Receives the evaluation input (question and two model responses). * Calls the configured DGrid AI model using the stored API key. * Produces a selection indicating which model response is better. * Tasks are processed asynchronously by DGrid, and points are credited after each completed task. #### Point Accrual and Quality Dependency * For each completed task, the Agent earns points. * The number of points per task is dependent on the quality of task completion (e.g., consistency and reliability of judgments, as determined by Arena's internal evaluation metrics). * This encourages the use of higher-quality models and careful configuration of agents. #### Daily Limit and Task Availability * Each agent can earn up to 10,000 points per day. * Arena has a limited number of tasks per day: * Tasks are refreshed at 00:00 (system daily reset). * Once all tasks for the day have been distributed, no additional Agent invocations occur until the next reset. This mechanism controls system load and maintains a balanced reward economy. #### Points and Airdrop Allocation All points earned by your Agent accumulate alongside your manual battle points and contribute to your **\$DGAI token airdrop weight**: * Points convert to airdrop weight at TGE. * Early participants earn higher multipliers. * There is no minimum threshold — every point counts. ### 3. Architecture Overview Arena for Agent is part of an AI-driven, closed-loop model evaluation system characterized by: * **AI Question Generation**: Questions and evaluation prompts are generated by Questions-Setting Agents, ensuring scalable and diverse test cases. * **AI Answer Generation**: Multiple models produce candidate answers to the generated questions. * **AI-Based Evaluation (Agents)**: Agents, powered by DGrid AI models, compare candidate answers and determine the better one. The end-to-end workflow is therefore: *AI creates questions → AI models answer → AI Agents evaluate → Results feed back into Arena metrics and rewards.* Arena for Agent architecture diagram ## User Interaction and Workflows ### Prerequisites Before creating an Agent, the user must: 1. **Complete Twitter follow**: Follow the specified official account as guided by the UI. 2. **Complete on-chain activation**: Perform the required on-chain activation step to enable wallet-based operations. Only after these prerequisites are met will the "Let Agent Work" entry point become fully functional. Let Agent Work entry point in the DGrid UI ### Agent Configuration Fields During creation, the following fields must be configured: 1. **Agent Name** * Description: * A globally unique identifier for on-chain registration and system-wide reference. * Constraints: * Length: 5–20 characters. * Allowed characters: ASCII letters, digits, and hyphen `'-'`. * Must not duplicate any existing Agent Name in the system. * Impact: * Stored on BSC as part of ERC‑8004 registration. 2. **Nick Name** A display name that allows input of various languages and symbols. 3. **API Setup** This section defines the Agent's evaluation backend. * Platform: **DGrid AI** (only supported provider) * API Key Input * Model Selection API setup form with platform, key, and model fields 4. **Create Agent** After all verifications are passed, click the button to send a transaction and complete the creation. ### Agent Management Panel After creation, the Agent can be monitored and controlled through the Agent panel. * **Pause/Start Agent**: The Agent will stop being invoked and stop generating rewards after being paused. * **ERC-8004**: Click "View on BSC" to check the ERC-8004 registration information of the Agent on the chain. * **Edit**: The API Key and model can be changed. Agent management panel * Editing configuration affects subsequent tasks only; previously evaluated tasks and points remain unchanged. * If an invalid key or unsupported model is configured, the Agent may fail to process tasks, which can reduce effective earnings. ## Summary Arena for Agent extends DGrid's Arena ecosystem by enabling AI-powered Agents to perform large-scale, automated model evaluation. Through simple DGrid API key–based configuration and on-chain ERC‑8004 registration on BSC, users can deploy and operate Agents with minimal friction. By integrating AI-generated questions, AI-generated answers, and AI-based evaluation into a closed-loop architecture, Arena for Agent provides a scalable, transparent, and economically aligned framework for continuous model assessment. All earned points contribute to your \$DGAI token airdrop allocation, rewarding both Agent creators and active evaluators. # AI Arena Source: https://docs.dgrid.ai/ai-arena/overview Discover DGrid AI Arena, a gamified hub where users rate AI models, complete daily tasks, climb the leaderboard, and earn $DGAI airdrop points. **DGrid AI Arena** is a dedicated hub inside the DGrid platform where users help evaluate and improve DGrid's AI models — and earn points that convert into **\$DGAI token airdrop weight**. By completing simple daily "AI Battles" and inviting new users, participants: * Compare real AI model responses and signal which are better * Earn points for each decision and referral * Accumulate points toward **\$DGAI token airdrop allocation** * Compete on a **weekly leaderboard** for a shared **300,000 pts prize pool** DGrid AI Arena is not just a gamified layer. It is a core component of DGrid's AI infrastructure that uses community judgment to: * Evaluate model quality * Guide model optimization and deployment * Continuously align DGrid AI with real user expectations ## Key Concepts #### AI Arena The **AI Arena** is the entry point within DGrid where all AI reward and evaluation activities take place. It hosts: * **AI Battle**: daily missions where users compare AI answers * **Points and Rewards**: tracking of earned points, weekly rank, and airdrop allocation Access AI Arena from the DGrid interface or directly at: [`https://dgrid.ai/arena`](https://dgrid.ai/arena) #### AI Battle **AI Battle** is the main interaction flow in DGrid AI Arena. Users: * Receive a random question or prompt * See **two anonymous AI model responses** * Choose which answer they think is better Each decision yields points and feeds into DGrid's model evaluation and training pipeline. #### Points **Points** are the internal metric of contribution in DGrid AI Arena. They are: * Earned by: * Completing daily AI Battle missions * Referring new users * Used for: * Determining your **\$DGAI token airdrop weight** * Competing on the **weekly leaderboard** for bonus point prizes #### Rewards DGrid AI Arena rewards participation with **real on-chain value**: * **\$DGAI airdrop allocation** — total accumulated points convert to airdrop weight at TGE * **Weekly leaderboard prize** — Top 50 users share a **300,000 pts pool** each week, proportional to weekly points earned ## How AI Battle Works ### Daily Missions * Each user can complete up to **5 Daily Missions per day**. * Every mission is designed to be **quick and intuitive**, taking only a short moment. * Missions reset daily, encouraging consistent participation over time. ### Mission Flow For each mission: 1. **Prompt Display** * The user is shown a *random question or prompt*. 2. **Two Anonymous AI Responses** * The prompt is followed by **two AI answers**, each from potentially different models. * The models are anonymous; only the content of the answers is visible. 3. **User Choice** * The user reads both answers carefully. * The user selects the answer they believe: * Better fits the prompt * Better matches their expectations or needs 4. **Points Awarded Based on Consensus** * After enough users have voted, a **community majority** emerges for that mission. * The user's reward depends on whether their choice aligns with this majority (details in the next section). ### Role in Model Training and Evaluation Every vote in AI Battle is a **data point** for DGrid's AI network. DGrid aggregates these user choices to: * **Evaluate model performance**: Identify which models consistently produce preferred answers * **Understand user preferences**: What users value in terms of clarity, helpfulness, safety, and relevance * **Guide model evolution**: Prioritize better-performing models; inform fine-tuning strategies and deployment decisions At scale, thousands of daily micro-decisions across many users form a powerful **human feedback signal**, enabling DGrid to: * Build a more **reliable, human-aligned AI LLM network** * Improve robustness across diverse question types * Move beyond static benchmarks to **continuous, live evaluation** ## Points System ### How Points Are Earned There are two primary ways to earn points in DGrid AI Arena: 1. **Daily Missions in AI Battle** * Each mission awards **5–10 points**: * **10 points** if your choice matches the **community majority** * **5 points** if your choice does **not** match the majority * There is **no "wrong" participation**: * Even if you choose differently from the majority, you still earn points * Every vote is treated as valuable feedback * With **up to 5 missions per day**, users can accumulate points steadily while contributing to model training. 2. **Referral Points** * Users can invite others to join DGrid AI Arena. * For **each valid referred user**, the referrer earns bonus points. * Referrals allow users to **scale rewards via community growth**, not just their own activity. ### How Points Are Used Your **total points** serve two key purposes: * **\$DGAI token airdrop weight** — points directly determine your allocation at Token Generation Event (TGE) * **Weekly leaderboard ranking** — your weekly points determine your share of the 300,000 pts prize pool The more points you earn through missions and referrals: * The larger your future \$DGAI airdrop allocation * The higher your relative position on the weekly leaderboard * The greater your share of the weekly point prize pool ## Rewards Model ### Points → \$DGAI Airdrop Allocation All accumulated points convert to **\$DGAI token airdrop weight** at TGE: * **No minimum threshold** — every point contributes to your allocation * **Early adopter multipliers** — the sooner you participate, the more each point is worth * **Snapshot announced in advance** — the community is notified before the airdrop snapshot is taken The more you contribute early → The higher your multiplier → The larger your \$DGAI airdrop share. ### Weekly Leaderboard: Bonus Point Prizes DGrid AI Arena includes a **Weekly Leaderboard** that rewards the most active participants each week. * **Weekly Prize Pool**: **300,000 pts** per week * **Eligibility**: Top 50 users by weekly points * **Reset**: Every Sunday at 00:00 UTC * **Distribution**: Proportional to weekly points earned — higher rank = larger share; Top 1 earns the most ### Reward Structure Summary * **Casual users** * Earn via consistent daily missions * Accumulate points steadily toward airdrop allocation * **Power users & top contributors** * Benefit from both: * Long-term airdrop allocation growth, and * Additional weekly leaderboard point prizes This **dual reward mechanism** ensures that all participation is recognized, while also **incentivizing sustained and high-impact engagement**. ## Getting Started with DGrid AI Arena ### Step 1: Access AI Arena Navigate to the **AI Arena**: [`https://dgrid.ai/arena`](https://dgrid.ai/arena). Once there: * **Connect your wallet** * **Activate your Arena access** AI Arena access page ### Step 2: Start AI Battle Click **"Start AI Battle"**. After mission begins: You'll see a **question/prompt** and **two anonymous AI responses**. Read both answers carefully and select the one you think is better. For each completed mission: * You earn **5–10 points**, depending on alignment with community consensus. * You can complete **up to 5 missions** per day. AI Battle mission interface ### Step 3: Repeat Daily Return every day to: * Complete your **5 daily missions** * Accumulate more points * Continuously contribute to training and improving DGrid AI Daily missions progress view ### Step 4: Invite Friends (Referrals) Share DGrid AI Arena with your network using your referral mechanism in the DGrid UI. For each **valid referred user**, you receive bonus points. Referrals help: * Grow the **DGrid community** * Increase the **volume and diversity of AI Battle feedback** * Boost your own points and airdrop allocation ### Step 5: Track Your Points & Leaderboard Rank Monitor your **total points** in the DGrid interface. Check the **Weekly Leaderboard** to see: * Your ranking relative to other participants * Your potential share of the **300,000 pts** weekly prize pool * Your current airdrop weight and multiplier status ## Why DGrid AI Arena Matters DGrid AI Arena is a **collaborative intelligence layer** built on top of DGrid's AI infrastructure. It is designed to make the DGrid AI network: * **More aligned** with real user expectations * **More robust** across many question and content types * **Continuously improving**, driven by live, real-world feedback ### Human Judgment at Scale By combining: * Human judgment from thousands of AI Battles * Community-driven evaluation of model quality * A transparent, on-chain point system tied to \$DGAI token airdrops DGrid can: * Determine which models to prioritize and deploy * Learn what users consider: Clear, Helpful, Safe and Relevant * Decide how and when to roll out new capabilities across the ecosystem Every point earned is more than just a number — it is a **signal** that helps decide: * Which models "win" in head-to-head comparisons * How models should be **fine-tuned** * Which behaviors should be **reinforced or discouraged** In this way, **every user choice becomes a vote for better AI**. ## FAQ #### Is there a "wrong" choice in AI Battle? No. There is **no wrong participation**. * If your choice matches the **community majority**, you earn **10 points**. * If your choice does **not** match the majority, you still earn **5 points**. Every decision is considered valuable signal for model evaluation. #### How many missions can I complete each day? You can complete up to **5 Daily Missions** in AI Battle per day. #### How do I earn referral points? Invite others to join DGrid AI Arena using the referral mechanism in the DGrid interface. For each **valid referred user**, you receive bonus points. #### How do points convert to \$DGAI tokens? Points accumulate as **airdrop weight** for the \$DGAI Token Generation Event (TGE). The more points you have — especially as an early participant — the larger your \$DGAI airdrop allocation. The exact snapshot timing will be announced in advance. #### How does the weekly leaderboard work? * Each week, DGrid allocates a **300,000 pts prize pool**. * Users are ranked based on **points earned during that week**. * Rankings reset every **Sunday at 00:00 UTC**. * The Top 50 users share the pool **proportionally**: more weekly points → larger share. #### How does my participation improve DGrid AI? Your votes: * Tell DGrid which AI responses users prefer * Help identify which models perform best in real usage * Provide ongoing feedback that informs: Model selection; Fine-tuning strategies; Safety and quality improvements # Free Models Router Source: https://docs.dgrid.ai/ai-gateway/free-models-router Use DGrid's free intelligent inference gateway for everyday AI tasks with automatic model routing and fair-use rate limits. Free Models Router is DGrid's free intelligent inference gateway for users worldwide. Instead of choosing a specific free model manually, you call one stable model ID and let DGrid route the request to available model capacity based on service availability, response efficiency, and the task requirements. Use model ID `dgridai/free` when you want DGrid to select an available free model automatically. See the [model detail page](https://dgrid.ai/models/dgridai/free) for the live model listing. ## What it is for Free Models Router is designed for general-purpose AI usage where fast access and low friction matter more than selecting a specific provider model. It works well for: * Everyday Q\&A and research assistance * Multilingual writing, rewriting, and translation * Coding help, debugging suggestions, and code explanation * Logical analysis and structured reasoning * Learning support and concept explanation * Drafting, summarizing, and content creation * Complex problem solving that benefits from a capable general model ## How routing works DGrid aggregates multiple sources of free inference capacity behind a single routing layer. For each request, the router evaluates available model resources and schedules the request to a suitable backend. Routing may consider: * Current service availability * Expected response speed * Task type and prompt requirements * Free compute availability across connected model sources * Operational stability of the underlying route This means the underlying model can change from request to request. If your application requires a fixed model identity, use a specific Model API model ID instead of `dgridai/free`. ## Quickstart Free Models Router uses the same OpenAI-compatible chat completion interface as the rest of DGrid AI Gateway. ```bash theme={null} curl https://api.dgrid.ai/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $DGRID_API_KEY" \ -d '{ "model": "dgridai/free", "messages": [ { "role": "user", "content": "Explain zero-knowledge proofs in simple terms." } ] }' ``` You can also use the OpenAI SDK by setting the DGrid base URL: ```typescript theme={null} import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https://api.dgrid.ai/v1', apiKey: process.env.DGRID_API_KEY, }); const completion = await client.chat.completions.create({ model: 'dgridai/free', messages: [ { role: 'user', content: 'Help me outline a launch plan for a developer tool.', }, ], }); console.log(completion.choices[0].message.content); ``` ## Rate limits To keep free access reliable and fair, DGrid applies request limits to Free Models Router. Limits are enforced per account. | Access level | Eligibility | Requests per minute | Requests per day | | ---------------- | ------------------------------------------------------------- | ------------------: | ---------------: | | Standard access | Account has not completed at least `$5` in qualifying top-ups | 10 | 100 | | Increased access | Account has completed at least `$5` in qualifying top-ups | 20 | 1,000 | A qualifying top-up is a direct addition of funds to the account balance and is used to determine whether the account meets the `$5` threshold. ### Rate limit errors Requests that exceed the applicable limit are rejected with: ```text theme={null} Rate limit exceeded. Please try again later. ``` If your application needs predictable higher throughput, use a paid model route or contact DGrid support for production guidance. ## Operational guidance * Treat `dgridai/free` as a convenience router, not a fixed model. * Avoid relying on provider-specific behavior from the underlying routed model. * Add retry logic with backoff for temporary rate-limit or availability responses. * Use paid model IDs when you need deterministic model selection, higher throughput, stronger SLA expectations, or model-specific capabilities. * Log `DGrid-Request-ID` from responses if you need to reconcile usage later. See [Get request billing details](/api-reference/usage-and-billing/get-request-billing-details) for request-level billing lookup. # Integration Tutorials Source: https://docs.dgrid.ai/ai-gateway/integrations Step-by-step integration tutorials showing how to connect DGrid AI Gateway to popular developer tools, SDKs, frameworks, and AI coding assistants. This page collects practical integration tutorials for using **DGrid AI Gateway** in common developer tools and SDKs. ## Cursor (Override OpenAI Base URL) 1. Get your `DGRID_API_KEY` (see the prerequisite in [AI Gateway](/ai-gateway/overview)). 2. Open **Cursor Settings** → **Models**. 3. Under **API Keys**, enable **Override OpenAI Base URL**. 4. Set the base URL to: * `https://api.dgrid.ai/v1` 5. Paste your `DGRID_API_KEY` into **OpenAI API Key**. 6. Pick any supported model name using the DGrid format (for example: `openai/gpt-4o`). Cursor settings example Full tutorial: [How to Configure and Use DGrid AI Gateway in Cursor](https://blog.dgrid.ai/posts/2026-02-18/) ## OpenAI SDK (Node.js / Python) * See: [AI Gateway Quickstart](/ai-gateway/overview#quickstart) ## OpenClaw You can configure OpenClaw to route requests through **DGrid AI Gateway** using the OpenAI-compatible endpoint. 1. Open your OpenClaw model/provider settings. 2. Set the API base URL to `https://api.dgrid.ai/v1`. 3. Paste your `DGRID_API_KEY` into the API key field. 4. Select a supported DGrid model ID. 5. Save the configuration and run a quick test request. ## Blog integration tutorials (collected) * **AI as Workspace (AIaW)**: [Step-by-Step Guide: Configure DGrid AI Gateway in AI as Workspace (AIaW)](https://blog.dgrid.ai/posts/2026-03-10/) * **AnythingLLM**: [Tutorial: Using DGrid AI Gateway with AnythingLLM](https://blog.dgrid.ai/posts/2026-01-30/) * **Chatbox**: [Step-by-Step Guide: Configure DGrid AI Gateway in Chatbox](https://blog.dgrid.ai/posts/2026-03-09/) * **Claude Code**: [Use Claude Code with DGrid](https://blog.dgrid.ai/posts/2026-03-12/) * **Codex CLI**: [Using Codex CLI with DGrid: A Complete Guide](https://blog.dgrid.ai/posts/2026-03-23/) * **Junie CLI**: [Step-by-Step Guide: Integrate DGrid with Junie CLI](https://blog.dgrid.ai/posts/2026-04-13/) * **LibreChat**: [Using DGrid with LibreChat: A Step-by-Step Guide](https://blog.dgrid.ai/posts/2026-01-28/) * **LobeChat**: [Configuring and Utilizing DGrid AI Gateway in LobeChat: A Full Guide](https://blog.dgrid.ai/posts/2026-02-09/) * **Open WebUI**: [Using DGrid AI Gateway with Open WebUI: A Comprehensive Guide](https://blog.dgrid.ai/posts/2026-01-22_2/) * **OpenClaw (agent platform)**: [Supercharging OpenClaw with DGrid: The Ultimate AI Agent Setup](https://blog.dgrid.ai/posts/2026-02-02/) * **OpenClaw (no-code)**: [Step-by-Step Guide: OpenClaw Installation & DGrid AI Gateway Setup (No Code Required)](https://blog.dgrid.ai/posts/2026-02-27/) * **Vercel AI SDK**: [How to Use DGrid AI Gateway with the Vercel AI SDK](https://blog.dgrid.ai/posts/2026-03-26/) # Realtime Source: https://docs.dgrid.ai/ai-gateway/model-api/realtime Build OpenAI-compatible Realtime API sessions on DGrid for low-latency text and audio conversations over WebSocket with streaming voice models. The Realtime API exposes OpenAI-compatible low-latency text and audio conversations through websocket sessions plus an HTTP endpoint for short-lived client tokens. ## WebSocket Connection Open a realtime websocket session directly when your backend can securely hold the DGrid API key. ```http theme={null} WSS wss://api.dgrid.ai/v1/realtime?model={model} ``` | | | | ----------------- | ----------------------------------------------------------------- | | **Authorization** | `Authorization: Bearer ; OpenAI-Beta: realtime=v1` | | **Request** | `websocket` | | **Response** | `websocket events` | ### Query Parameters | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------------------------------------- | | `model` | string | Yes | Realtime model ID, such as `gpt-4o-realtime-preview`. | ### Client Events | Event Type | Description | | --------------------------- | ---------------------------------- | | `session.update` | Update session-level options. | | `input_audio_buffer.append` | Stream audio chunks to the server. | | `input_audio_buffer.commit` | Commit the current buffered audio. | | `response.create` | Trigger a new assistant response. | | `conversation.item.create` | Insert a conversation item. | ### Server Events | Event Type | Description | | ---------------------- | --------------------------------- | | `session.created` | Session was successfully created. | | `session.updated` | Session settings were updated. | | `response.text.delta` | Streamed text token delta. | | `response.audio.delta` | Streamed audio chunk delta. | | `response.done` | Response has completed. | | `error` | Error payload. | ```javascript JavaScript Example theme={null} const ws = new WebSocket( 'wss://api.dgrid.ai/v1/realtime?model=gpt-4o-realtime-preview', [], { headers: { Authorization: `Bearer ${apiKey}`, 'OpenAI-Beta': 'realtime=v1' } } ) ws.onopen = () => { ws.send(JSON.stringify({ type: 'session.update', session: { modalities: ['text', 'audio'], voice: 'alloy' } })) } ws.onmessage = (event) => { const data = JSON.parse(event.data) console.log('received event:', data) } ``` ```http Realtime Notes theme={null} Authorization: Bearer OpenAI-Beta: realtime=v1 ``` ## Create Realtime Session Token Use the realtime endpoint example shown below when you need an authenticated GET request against the realtime HTTP entrypoint. ```http theme={null} GET /v1/realtime ``` | | | | ----------------- | --------------------------------------- | | **Authorization** | `Authorization: Bearer ` | | **Request** | `none` | | **Response** | `101 · application/json` | ### Request Headers | Field | Type | Required | Description | | --------------- | ------ | -------- | ------------------------------------------------------- | | `Authorization` | string | Yes | Bearer token used to authenticate the realtime request. | ### Response Body | Field | Type | Description | | ------- | ------ | ---------------------------------------------- | | `101` | text | Successful upgrade response with no JSON body. | | `error` | object | Error payload returned when the request fails. | ```bash cURL theme={null} curl -X GET "https://api.dgrid.ai/v1/realtime" \ -H "Authorization: Bearer " ``` ```javascript JavaScript theme={null} fetch("https://api.dgrid.ai/v1/realtime", { method: "GET", headers: { "Authorization": "Bearer " } }) ``` ```go Go theme={null} package main import ( "fmt" "net/http" "io/ioutil" ) func main() { url := "https://api.dgrid.ai/v1/realtime" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` ```python Python theme={null} import requests url = "https://api.dgrid.ai/v1/realtime" response = requests.request("GET", url, headers = { "Authorization": "Bearer " }) print(response.text) ``` ```java Java theme={null} import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.time.Duration; HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build(); HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() .uri(URI.create("https://api.dgrid.ai/v1/realtime")) .header("Authorization", "Bearer ") .GET() .build(); try { HttpResponse response = client.send(requestBuilder.build(), BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Response body: " + response.body()); } catch (Exception e) { e.printStackTrace(); } ``` ```csharp C# theme={null} using System; using System.Net.Http; using System.Text; var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Bearer "); var response = await client.GetAsync("https://api.dgrid.ai/v1/realtime"); var responseBody = await response.Content.ReadAsStringAsync(); ``` ```text 101 theme={null} Empty ``` ```json 400 theme={null} { "error": { "message": "string", "type": "string", "param": "string", "code": "string" } } ``` ## WebSocket Events Plan your client around a small set of request and response event types for low-latency conversational streaming. ```http theme={null} WSS wss://api.dgrid.ai/v1/realtime?model={model} ``` | | | | ----------------- | ----------------------------------------------------------------- | | **Authorization** | `Authorization: Bearer ; OpenAI-Beta: realtime=v1` | | **Request** | `websocket` | | **Response** | `event stream` | ### Core Client Events | Event Type | Description | | --------------------------- | ------------------------------------------------------- | | `session.update` | Update modalities, voice, or other session preferences. | | `input_audio_buffer.append` | Send encoded audio fragments. | | `input_audio_buffer.commit` | Mark the buffered audio as ready. | | `response.create` | Ask the server to begin generating a response. | | `conversation.item.create` | Add a conversation turn or tool result. | ### Core Server Events | Event Type | Description | | ---------------------- | ------------------------------------------------------- | | `session.created` | Initial confirmation that the websocket session exists. | | `session.updated` | Confirmation that session settings changed. | | `response.text.delta` | Incremental text output. | | `response.audio.delta` | Incremental audio output. | | `response.done` | Final event for a completed response. | | `error` | Recoverable or fatal error payload. | ### Integration Guidance 1. Buffer client-side audio in small chunks and use `input_audio_buffer.commit` to signal turn boundaries. 2. Listen for both `response.text.delta` and `response.audio.delta` if the session supports multimodal output. 3. Use the HTTP session token endpoint for browser clients so the long-lived API key never reaches the client. ```json response.text.delta theme={null} { "type": "response.text.delta", "response_id": "resp_123", "delta": "Hello" } ``` ```json response.done theme={null} { "type": "response.done", "response": { "id": "resp_123", "status": "completed" } } ``` # AI Gateway Source: https://docs.dgrid.ai/ai-gateway/overview DGrid AI Gateway provides one unified, OpenAI-compatible API to call 200+ leading AI models with crypto billing, routing, and global edge access. DGrid AI Gateway provides a single, unified API to access 200+ leading AI models. Users can directly plug their own API keys into tools like Claude Code, Codex, and Moltbot (Clawdbot), which dramatically reduces integration complexity and operational costs. ## Quickstart DGrid AI Gateway unifies the interfaces of hundreds of AI models. You don't need to handle compatibility adaptations for different models in your code—with a single API endpoint and a standardized API request format, you can freely switch and access all the hundreds of models provided by DGrid. Looking for tool-specific guides (OpenClaw / Cursor / SDK / etc.)? See [Integration Tutorials](/ai-gateway/integrations). Looking for endpoint-level API reference? See [Model API](/api-reference/introduction). Want a free route that chooses available model capacity automatically? See [Free Models Router](/ai-gateway/free-models-router). The DGrid official SDK is currently under active development—stay tuned for its release. Below are the available temporary request methods to interact with DGrid AI Gateway. ### Prerequisites Before getting started, you need to: 1. Obtain a valid `DGRID_API_KEY` ([Guide](https://blog.dgrid.ai/posts/2026-01-04/)). 2. Ensure your development environment has network access to `https://api.dgrid.ai/v1`. 3. For SDK usage, install the corresponding OpenAI SDK package in your project. ### Direct API Request via cURL You can send a direct HTTP POST request to the DGrid AI Gateway endpoint using cURL. ```bash theme={null} curl https://api.dgrid.ai/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $DGRID_API_KEY" \ -d '{ "model": "openai/gpt-4o", "messages": [ { "role": "user", "content": "What is the meaning of life?" } ] }' ``` ### Using the OpenAI SDK (DGrid Compatible) DGrid AI Gateway is fully compatible with the OpenAI SDK specification. You only need to modify the `baseURL` (and fill in the `DGRID_API_KEY`) to quickly migrate or integrate. #### Prerequisite: Install the OpenAI SDK First, install the OpenAI SDK in your project: ```bash theme={null} # For TypeScript/Node.js npm install openai # For Python pip install openai ``` #### TypeScript Implementation ```typescript theme={null} import OpenAI from 'openai'; // Initialize the OpenAI client with DGrid AI Gateway configuration const openai = new OpenAI({ baseURL: 'https://api.dgrid.ai/v1', // Point to DGrid AI Gateway endpoint apiKey: '', // Replace with your valid DGrid API key defaultHeaders: { 'HTTP-Referer': '', // Optional: Your application's site URL 'X-Title': '', // Optional: Your application's name }, }); // Async function to send chat completion request async function getChatCompletion() { const completion = await openai.chat.completions.create({ model: 'openai/gpt-4o', // Specify the target model (DGrid-supported format) messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }); // Print the response result console.log(completion.choices[0].message); } getChatCompletion(); ``` #### Python Implementation ```python theme={null} from openai import OpenAI # Initialize the OpenAI client with DGrid AI Gateway configuration client = OpenAI( base_url="https://api.dgrid.ai/v1", # Point to DGrid AI Gateway endpoint api_key="", # Replace with your valid DGrid API key ) completion = client.chat.completions.create( extra_headers={ "HTTP-Referer": "", # Optional: Your application's site URL "X-Title": "", # Optional: Your application's name }, model="openai/gpt-4o", # Specify the target model (DGrid-supported format) messages=[ { "role": "user", "content": "What is the meaning of life?" } ] ) # Print the response content print(completion.choices[0].message.content) ``` ### Additional Notes 1. **Optional Headers**: The `HTTP-Referer` and `X-Title` headers are optional, but filling them in helps DGrid better identify your application and provide more optimized service support. 2. **Model Naming Format**: The model parameter uses the format `[provider]/[model-name]` (e.g., `openai/gpt-4o`), which is consistent across all DGrid-supported models for easy switching. 3. **SDK Development Update**: The official DGrid SDK is under development and will provide more native features and optimized performance—please pay attention to the official DGrid documentation updates for release information. # Supported Countries and Regions Source: https://docs.dgrid.ai/ai-gateway/supported-regions Regional availability, supported countries, and geographic restrictions for the DGrid AI Gateway, including IP and compliance limitations. *Last updated: Wed 22 Apr* ## Overview This page describes regional availability considerations for DGrid AI Gateway ("AI Gateway"). AI Gateway may not be available in all countries, territories, or jurisdictions. Availability may vary due to legal, regulatory, sanctions, export control, infrastructure, payment, operational, security, or third-party provider constraints. This page applies specifically to AI Gateway. It does not replace any separate regional restrictions, legal notices, or product-specific terms that may apply to other DGrid offerings. For service-use requirements, see [Terms of Service](/ai-gateway/terms-of-service). ## Supported Access Regions AI Gateway is intended to be made available only in regions where DGrid determines that access and use can be supported in a lawful, operationally feasible, and commercially appropriate manner. Supported access may depend on factors including: * applicable law and regulatory requirements; * sanctions and export control obligations; * availability of infrastructure or service providers; * support coverage and operational readiness; * payment, billing, or contracting constraints; and * model, feature, or provider availability in a given region. Confirmed supported countries, regions, and territories for commercial API access are: Albania, Algeria, Andorra, Angola, Antigua and Barbuda, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia and Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina Faso, Burundi, Cabo Verde, Cambodia, Cameroon, Canada, Chad, Chile, Colombia, Comoros, Congo (Brazzaville), Costa Rica, Cote d'Ivoire, Croatia, Cyprus, Czech Republic, Denmark, Djibouti, Dominica, Dominican Republic, Ecuador, Egypt, El Salvador, Equatorial Guinea, Estonia, Eswatini, Fiji, Finland, France, Gabon, Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Honduras, Hungary, Iceland, India, Indonesia, Iraq, Ireland, Israel, Italy, Jamaica, Japan, Jordan, Kazakhstan, Kenya, Kiribati, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Liechtenstein, Lithuania, Luxembourg, Madagascar, Malawi, Malaysia, Maldives, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mozambique, Namibia, Nauru, Nepal, Netherlands, New Zealand, Niger, Nigeria, North Macedonia, Norway, Oman, Pakistan, Palau, Palestine, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Qatar, Romania, Rwanda, Saint Kitts and Nevis, Saint Lucia, Saint Vincent and the Grenadines, Samoa, San Marino, Sao Tome and Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, South Africa, South Korea, Spain, Sri Lanka, Suriname, Sweden, Switzerland, Taiwan, Tajikistan, Tanzania, Thailand, Timor-Leste, Togo, Tonga, Trinidad and Tobago, Tunisia, Turkiye, Turkmenistan, Tuvalu, Uganda, Ukraine (excluding Crimea, Donetsk, Kherson, Luhansk, and Zaporizhzhia regions), United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Vietnam, Zambia, Zimbabwe. Users should refer to this page and the latest published DGrid documentation for current regional availability. ## Restricted or Unsupported Regions DGrid may restrict or decline access to AI Gateway in any country, territory, or jurisdiction where DGrid determines that access or use would create legal, regulatory, sanctions, export control, security, operational, or commercial risk. In some cases, DGrid may: * block account creation or API access; * limit use of particular models or features; * require additional verification or review; or * suspend or terminate access if continued service is not permitted or feasible. Users may not access or use AI Gateway from a restricted or unsupported region in a manner that bypasses geographic, technical, compliance, or contractual controls. ## Service Limitations by Region Even where AI Gateway is available, not all features, models, endpoints, integrations, or account options may be available in every region. Regional differences may result from: * third-party model or provider restrictions; * local compliance requirements; * data routing or infrastructure limitations; * payment or billing availability; * language or support coverage; or * operational rollout timing. DGrid reserves the right to vary, limit, or withdraw regional availability of any AI Gateway feature at any time. ## Compliance and Export Control Use of AI Gateway is subject to all applicable trade restrictions, sanctions laws, export control rules, and related regulatory requirements. You are responsible for ensuring that your access to and use of AI Gateway complies with all applicable laws and restrictions in the jurisdictions relevant to you, your organization, your users, and your use case. DGrid may require additional review, documentation, verification, or contractual assurances before enabling or continuing access in certain regions or for certain use cases. ## Changes to Regional Availability DGrid may update, expand, limit, suspend, or discontinue availability of AI Gateway in any region at any time, with or without notice, subject to applicable law. Changes may result from: * changes in law or regulation; * sanctions or export control developments; * changes in third-party provider support; * infrastructure, security, or operational issues; or * DGrid's internal compliance or risk assessments. Users should refer to the latest published DGrid documentation for current regional availability guidance. ## Contact If you need confirmation about AI Gateway availability for a specific country, territory, or use case, please contact DGrid at [hi@dgrid.ai](mailto:hi@dgrid.ai). # Terms of Service Source: https://docs.dgrid.ai/ai-gateway/terms-of-service Legal terms, acceptable use policy, and service conditions governing access to and use of the DGrid AI Gateway and Model API endpoints. *Last updated: Wed 22 Apr* ## Overview These Terms of Service ("Terms") govern access to and use of DGrid AI Gateway ("AI Gateway"), including related APIs, documentation, tools, interfaces, and service features made available by DGrid. AI Gateway is a service for accessing, routing, managing, and integrating AI model capabilities and related functionality. These Terms apply specifically to AI Gateway and related service features unless DGrid expressly states otherwise in writing. ## Scope of These Terms These Terms apply to your access to and use of AI Gateway as a service. For clarity, these Terms do not govern DGrid Premium or any DGrid Premium license-related offering unless DGrid expressly states otherwise. Separate product-specific or service-specific terms, policies, notices, or commercial terms may apply where DGrid publishes them for other offerings. By accessing or using AI Gateway, you agree to comply with these Terms and any additional documentation, policies, usage requirements, or technical guidance that DGrid may publish for AI Gateway from time to time. ## Eligibility and Compliance You may use AI Gateway only if you are authorized to do so under applicable law and, where relevant, on behalf of yourself or the legal entity you represent. You are responsible for ensuring that your access to and use of AI Gateway complies with all applicable laws, regulations, sanctions restrictions, export control requirements, and internal compliance obligations relevant to your jurisdiction, industry, and use case. DGrid may restrict, suspend, or deny access to AI Gateway where access or use would create legal, regulatory, security, or compliance risk. ## Accounts and API Credentials To access certain AI Gateway features, you may need to create an account, obtain API credentials, or use credentials issued by DGrid. You are responsible for: * maintaining the confidentiality and security of your account and API credentials; * all activity conducted under your account or credentials; * ensuring that credentials are not shared, exposed, resold, or used in an unauthorized manner; and * promptly notifying DGrid of any suspected unauthorized access, credential compromise, or misuse. DGrid may rotate, revoke, suspend, or replace credentials where reasonably necessary for security, operational, legal, or compliance purposes. ## Permitted Use Subject to these Terms, you may use AI Gateway only for lawful, authorized, and documented purposes. You may use AI Gateway in accordance with any technical documentation, usage limits, product guidance, and service-specific restrictions published by DGrid. ## Prohibited Use You may not use AI Gateway to: * violate any applicable law or regulation; * infringe, misappropriate, or otherwise violate the rights of DGrid or any third party; * submit, transmit, or process unlawful, harmful, deceptive, abusive, infringing, or otherwise prohibited content; * attempt to gain unauthorized access to systems, accounts, models, data, or networks; * interfere with, disrupt, degrade, or circumvent the security, integrity, or availability of AI Gateway or related systems; * reverse engineer, extract, scrape, benchmark, or replicate the service except to the extent expressly permitted by applicable law; * bypass rate limits, access controls, safety protections, geographic restrictions, or usage restrictions; * use AI Gateway in a manner that could create unreasonable security, legal, reputational, or operational risk for DGrid, its providers, or other users; * resell, sublicense, or provide unauthorized third-party access to AI Gateway unless DGrid expressly permits such use in writing; or * use AI Gateway for any prohibited or restricted use case identified in DGrid documentation, policy pages, or applicable service notices. DGrid may update or supplement prohibited-use restrictions for AI Gateway from time to time. ## Customer Content As between you and DGrid, you retain any rights you may have in the prompts, inputs, data, files, or other content that you submit to AI Gateway ("Customer Content"), subject to applicable law and any rights reasonably necessary for DGrid and its service providers to operate, secure, and provide AI Gateway. You are solely responsible for Customer Content, including for: * its legality, accuracy, quality, and appropriateness; * obtaining all necessary rights, consents, notices, and permissions; and * ensuring that submission and processing of Customer Content through AI Gateway does not violate law, contract, confidentiality obligations, or third-party rights. DGrid may process Customer Content as reasonably necessary to provide, maintain, secure, support, and improve AI Gateway, subject to applicable law, technical architecture, published documentation, and any service-specific commitments DGrid may provide. DGrid does not assume responsibility for Customer Content submitted by users. ## AI Outputs AI Gateway may generate or return outputs based on Customer Content and model behavior ("Outputs"). You are responsible for evaluating Outputs for accuracy, suitability, legality, and fitness for your intended use. Outputs may be incomplete, inaccurate, biased, unavailable, delayed, or inappropriate for certain use cases and should not be relied on without appropriate review and judgment. To the extent permitted by applicable law and subject to any third-party model provider terms, as between you and DGrid, DGrid does not claim ownership of Outputs generated specifically for you through your permitted use of AI Gateway. You acknowledge that similar or identical outputs may be generated for other users or use cases. ## Third-Party Models and Services AI Gateway may rely on, interoperate with, or provide access to third-party models, infrastructure, tools, or services. DGrid does not control all third-party components and is not responsible for the acts, omissions, availability, performance, content, policies, or terms of third-party providers. Your use of certain AI Gateway features may be subject to additional third-party terms, technical limitations, model-specific restrictions, or regional availability constraints. DGrid may modify, replace, suspend, or remove access to third-party components at any time. ## Availability and Service Changes DGrid may modify, update, improve, suspend, or discontinue any part of AI Gateway at any time, with or without notice, to the extent permitted by applicable law. DGrid does not guarantee that AI Gateway, or any specific feature, model, integration, or interface, will always be available, uninterrupted, secure, or error-free. Access to AI Gateway may vary based on product plan, technical requirements, geography, compliance constraints, provider availability, maintenance needs, or other operational considerations. ## Fees and Billing Use of AI Gateway may be subject to fees, usage-based charges, credits, or other commercial arrangements, as described in applicable ordering materials, product documentation, or commercial terms provided by DGrid. Unless DGrid expressly states otherwise in writing: * fees are non-cancelable and non-refundable once incurred; * you are responsible for applicable taxes, duties, or similar governmental charges, excluding taxes based on DGrid's net income; and * DGrid may suspend or limit access where fees remain unpaid or where billing risk is reasonably identified. If no separate commercial terms apply, DGrid reserves the right to introduce or revise pricing, usage limits, or billing structures for AI Gateway upon reasonable notice. ## Suspension and Termination DGrid may suspend, restrict, or terminate your access to AI Gateway, in whole or in part, immediately or at a later time, where DGrid reasonably determines that: * you have violated these Terms or applicable policies; * your use creates security, legal, compliance, or operational risk; * access is required to be restricted by law, regulation, court order, sanctions requirement, or government request; * fees are overdue; or * continued provision of the service is no longer commercially, technically, or legally feasible. You may stop using AI Gateway at any time. Upon suspension or termination, your right to access and use AI Gateway will cease to the extent specified by DGrid. Provisions that by their nature should survive suspension or termination will survive, including provisions relating to compliance, disclaimers, limitations of liability, payment obligations, and dispute-related matters. ## Regional Availability AI Gateway may not be available in all countries, territories, or jurisdictions, and certain features, models, or capabilities may be unavailable or restricted in particular regions. Your use of AI Gateway is subject to DGrid's then-current regional availability rules and any applicable supported-country or supported-region policy published by DGrid. For additional guidance, see [Supported Countries and Regions](/ai-gateway/supported-regions). ## Disclaimers AI GATEWAY IS PROVIDED ON AN "AS IS" AND "AS AVAILABLE" BASIS TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, DGRID DISCLAIMS ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, AND GUARANTEES, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, ACCURACY, AVAILABILITY, SECURITY, OR RELIABILITY. WITHOUT LIMITING THE FOREGOING, DGRID DOES NOT WARRANT THAT: * AI GATEWAY WILL BE UNINTERRUPTED, ERROR-FREE, OR FREE OF HARMFUL COMPONENTS; * OUTPUTS WILL BE ACCURATE, COMPLETE, TIMELY, RELIABLE, OR FIT FOR ANY PARTICULAR PURPOSE; OR * ANY FEATURE, MODEL, OR THIRD-PARTY INTEGRATION WILL REMAIN AVAILABLE. ## Limitation of Liability TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, DGRID AND ITS AFFILIATES, LICENSORS, SERVICE PROVIDERS, AND SUPPLIERS WILL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR ANY LOSS OF PROFITS, REVENUE, BUSINESS, GOODWILL, DATA, OR USE, ARISING OUT OF OR RELATING TO AI GATEWAY OR THESE TERMS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE TOTAL AGGREGATE LIABILITY OF DGRID FOR ALL CLAIMS ARISING OUT OF OR RELATING TO AI GATEWAY OR THESE TERMS WILL NOT EXCEED THE AMOUNT PAID OR PAYABLE BY YOU TO DGRID FOR AI GATEWAY DURING THE TWELVE (12) MONTHS PRECEDING THE EVENT GIVING RISE TO THE CLAIM, OR, IF NO FEES WERE PAID, A REASONABLE MINIMUM AMOUNT TO BE REVIEWED BY DGRID. Nothing in these Terms excludes or limits liability to the extent such liability cannot be excluded or limited under applicable law. ## Updates to These Terms DGrid may update these Terms from time to time. If DGrid makes material changes, DGrid may provide notice by updating this page, the effective date, or through other reasonable means. Your continued access to or use of AI Gateway after updated Terms become effective constitutes acceptance of the updated Terms, to the extent permitted by applicable law. ## Contact If you have questions about these Terms or AI Gateway policy matters, please contact DGrid at [hi@dgrid.ai](mailto:hi@dgrid.ai). # Create speech Source: https://docs.dgrid.ai/api-reference/audio/create-speech api-reference/openapi.json POST /v1/audio/speech Convert text into natural speech with the OpenAI-compatible audio speech interface. Returns a binary audio stream — save the response body directly to a file. # Create transcription Source: https://docs.dgrid.ai/api-reference/audio/create-transcription api-reference/openapi.json POST /v1/audio/transcriptions Transcribe uploaded audio into text with the OpenAI-compatible Whisper-style interface. Supported formats: FLAC, MP3, MP4, MPEG, MPGA, M4A, OGG, WAV, and WebM. # Create translation Source: https://docs.dgrid.ai/api-reference/audio/create-translation api-reference/openapi.json POST /v1/audio/translations Translate uploaded audio into English with the OpenAI-compatible translation endpoint. # Native Gemini Format Source: https://docs.dgrid.ai/api-reference/audio/native-gemini-format api-reference/openapi.json POST /v1/models/{model}:generateContent Gemini-native generateContent interface for text chat, multimodal media recognition (images, audio, video), speech synthesis, and image generation with structured parts. Use `generationConfig` to request specific response modalities such as speech (`speechConfig`) or images (`imageConfig`). This page uses the same `generateContent` operation as [Generate content (Gemini)](/api-reference/chat/generate-content), with the playground above pre-filled for plain text chat. The notes below describe the Gemini-native fields you can add to `generationConfig` to request audio understanding or generation with structured parts. Set `generationConfig.responseModalities` to `["AUDIO"]` to request audio output, and configure `generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName` to choose a prebuilt voice for generated speech. ### Gemini-native request fields | Field | Type | Required | Description | | ------------------------------------------------------------------------- | ------ | -------- | ------------------------------------------------ | | `generationConfig.responseModalities` | array | Yes | Requested response modalities, e.g. `["AUDIO"]`. | | `generationConfig.speechConfig` | object | No | Speech configuration object. | | `generationConfig.speechConfig.voiceConfig` | object | No | Voice configuration wrapper. | | `generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig` | object | No | Prebuilt voice settings. | | `generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName` | string | No | Prebuilt voice preset name, e.g. `Kore`. | Use a text-to-speech-capable model such as `gemini-2.5-flash-preview-tts` in the `model` path parameter when requesting audio output. ### Example: requesting speech audio ```json theme={null} { "contents": [ { "role": "user", "parts": [ { "text": "Say cheerfully: Have a wonderful day!" } ] } ], "generationConfig": { "responseModalities": ["AUDIO"], "speechConfig": { "voiceConfig": { "prebuiltVoiceConfig": { "voiceName": "Kore" } } } } } ``` ### Response fields The response follows the standard `generateContent` shape. When audio output is requested, the returned `parts` contain inline audio data instead of text: Candidate responses returned by the model. Generated content object. Role returned in the generated content block, typically `model`. Returned parts. For audio output, each part contains an `inlineData` object with `mimeType` (e.g. `audio/L16;codec=pcm;rate=24000`) and base64-encoded `data`. Finish reason string, e.g. `STOP`. Safety evaluation results. Token accounting, including `promptTokenCount`, `candidatesTokenCount`, and `totalTokenCount`. Prompt blocking feedback when applicable. ### Example response ```json 200 theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "inlineData": { "mimeType": "audio/L16;codec=pcm;rate=24000", "data": "" } } ] }, "finishReason": "STOP", "safetyRatings": [] } ], "usageMetadata": { "promptTokenCount": 10, "candidatesTokenCount": 0, "totalTokenCount": 10 } } ``` # Create chat completion Source: https://docs.dgrid.ai/api-reference/chat/create-chat-completion api-reference/openapi.json POST /v1/chat/completions OpenAI-compatible Chat Completions for standard multi-turn chat, structured output, and tool calling. Model names use the `provider/model-name` format, for example `openai/gpt-4o`. Image-capable models can also return generated images through this endpoint. # Create message (Claude) Source: https://docs.dgrid.ai/api-reference/chat/create-message api-reference/openapi.json POST /v1/messages Claude Messages API for Anthropic-compatible payloads, tool use, and system prompts. # Create response Source: https://docs.dgrid.ai/api-reference/chat/create-response api-reference/openapi.json POST /v1/responses OpenAI Responses API for stateful flows, reasoning-specific options, and newer OpenAI tooling patterns. # Gemini Media Recognition Source: https://docs.dgrid.ai/api-reference/chat/gemini-media-recognition api-reference/openapi.json POST /v1/models/{model}:generateContent Gemini-native generateContent interface for text chat, multimodal media recognition (images, audio, video), speech synthesis, and image generation with structured parts. Use `generationConfig` to request specific response modalities such as speech (`speechConfig`) or images (`imageConfig`). This page uses the same `generateContent` operation as [Generate content (Gemini)](/api-reference/chat/generate-content), with the playground above pre-filled for plain text chat. The notes below describe the Gemini-native multimodal fields you can add to `contents[].parts` to analyze images, audio, video, or mixed media in a single request. Each part can carry inline data (base64-encoded bytes plus a MIME type) alongside text instructions, letting the model reason across modalities in one call. ### Gemini-native request fields The generic `contents` and `generationConfig` fields shown in the playground accept the following nested shape for multimodal recognition: | Field | Type | Required | Description | | ---------------------------------------- | ------ | -------- | -------------------------------------------------------------------------- | | `contents[].role` | string | No | Role of the turn, e.g. `user`. | | `contents[].parts` | array | Yes | Ordered list of content parts (text and/or inline media). | | `contents[].parts[].text` | string | No | Text instruction or question for the model. | | `contents[].parts[].inlineData` | object | No | Inline media payload for image, audio, or video understanding. | | `contents[].parts[].inlineData.mimeType` | string | No | MIME type of the inline data, e.g. `image/jpeg`, `audio/mp3`, `video/mp4`. | | `contents[].parts[].inlineData.data` | string | No | Base64-encoded media bytes. | You can mix multiple parts in a single turn — for example a `text` part with an instruction followed by one or more `inlineData` parts containing the media to analyze. ### Example: analyzing an image ```json theme={null} { "contents": [ { "role": "user", "parts": [ { "text": "Describe what is happening in this image." }, { "inlineData": { "mimeType": "image/jpeg", "data": "" } } ] } ] } ``` ### Response fields The response follows the standard `generateContent` shape. The fields most relevant to media recognition are: Candidate responses returned by the model. Generated content object. Role returned in the generated content block, typically `model`. Returned content parts, typically text describing the analyzed media. Finish reason string, e.g. `STOP`. Safety evaluation results. Token accounting metadata, including `promptTokenCount`, `candidatesTokenCount`, and `totalTokenCount`. Inline media (images, audio, video) consumes prompt tokens in addition to any text parts. ### Example response ```json 200 theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "The image shows a golden retriever sitting on a grassy lawn." } ] }, "finishReason": "STOP", "safetyRatings": [] } ], "usageMetadata": { "promptTokenCount": 264, "candidatesTokenCount": 18, "totalTokenCount": 282 } } ``` # Generate content (Gemini) Source: https://docs.dgrid.ai/api-reference/chat/generate-content api-reference/openapi.json POST /v1/models/{model}:generateContent Gemini-native generateContent interface for text chat, multimodal media recognition (images, audio, video), speech synthesis, and image generation with structured parts. Use `generationConfig` to request specific response modalities such as speech (`speechConfig`) or images (`imageConfig`). # Create completion Source: https://docs.dgrid.ai/api-reference/completions/create-completion api-reference/openapi.json POST /v1/completions Classic OpenAI-compatible text completion for single-prompt generation workloads that do not require a multi-message chat schema. # Create embeddings Source: https://docs.dgrid.ai/api-reference/embeddings/create-embedding api-reference/openapi.json POST /v1/embeddings OpenAI-compatible embeddings for retrieval, clustering, and semantic similarity workloads. # Create embeddings (legacy engines) Source: https://docs.dgrid.ai/api-reference/embeddings/create-engine-embedding api-reference/openapi.json POST /v1/engines/{engine}/embeddings Legacy engine-based embeddings path format for older SDK integrations. # Create image Source: https://docs.dgrid.ai/api-reference/images/create-image api-reference/openapi.json POST /v1/images/generations OpenAI-compatible image generation. Also accepts Qwen-compatible payloads (`wanx-v1` style models) using an `input.messages` wrapper instead of `prompt`. # Edit image Source: https://docs.dgrid.ai/api-reference/images/edit-image api-reference/openapi.json POST /v1/images/edits Edit an uploaded image with an optional mask using the OpenAI-compatible image editing endpoint. Also accepts Qwen-compatible JSON payloads with an `input.messages` wrapper. # Gemini Native Format Source: https://docs.dgrid.ai/api-reference/images/gemini-native-format api-reference/openapi.json POST /v1/models/{model}:generateContent Gemini-native generateContent interface for text chat, multimodal media recognition (images, audio, video), speech synthesis, and image generation with structured parts. Use `generationConfig` to request specific response modalities such as speech (`speechConfig`) or images (`imageConfig`). This page uses the same `generateContent` operation as [Generate content (Gemini)](/api-reference/chat/generate-content), with the playground above pre-filled for plain text chat. The notes below describe the Gemini-native fields you can add to `generationConfig` to generate or edit images with provider-specific response controls. Set `generationConfig.responseModalities` to `["IMAGE"]` to request image output, and use `generationConfig.imageConfig` to control the aspect ratio and output size. ### Gemini-native request fields | Field | Type | Required | Description | | ------------------------------------------ | ------ | -------- | ------------------------------------------------- | | `generationConfig.responseModalities` | array | Yes | Requested modalities array, e.g. `["IMAGE"]`. | | `generationConfig.imageConfig` | object | No | Image configuration object. | | `generationConfig.imageConfig.aspectRatio` | string | No | Aspect ratio for the generated image, e.g. `1:1`. | | `generationConfig.imageConfig.imageSize` | string | No | Output image size, e.g. `1024x1024`. | Use an image-generation-capable model such as `gemini-2.0-flash-preview-image-generation` in the `model` path parameter. ### Example: generating an image ```json theme={null} { "contents": [ { "role": "user", "parts": [ { "text": "A photorealistic image of a corgi wearing sunglasses on a beach." } ] } ], "generationConfig": { "responseModalities": ["IMAGE"], "imageConfig": { "aspectRatio": "1:1", "imageSize": "1024x1024" } } } ``` ### Response fields The response follows the standard `generateContent` shape. When image output is requested, the returned `parts` contain inline image data: Candidate responses returned by the model. Generated content object. Role returned in the generated content block, typically `model`. Returned content parts. For image output, each part contains an `inlineData` object with `mimeType` (e.g. `image/png`) and base64-encoded `data`. Finish reason string, e.g. `STOP`. Safety evaluation results. Token usage metadata, including `promptTokenCount`, `candidatesTokenCount`, and `totalTokenCount`. ### Example response ```json 200 theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "inlineData": { "mimeType": "image/png", "data": "" } } ] }, "finishReason": "STOP", "safetyRatings": [] } ], "usageMetadata": { "promptTokenCount": 14, "candidatesTokenCount": 0, "totalTokenCount": 14 } } ``` # OpenAI Chat Format Source: https://docs.dgrid.ai/api-reference/images/openai-chat-format api-reference/openapi.json POST /v1/chat/completions OpenAI-compatible Chat Completions for standard multi-turn chat, structured output, and tool calling. Model names use the `provider/model-name` format, for example `openai/gpt-4o`. Image-capable models can also return generated images through this endpoint. This page uses the same `chat/completions` operation as [Create chat completion](/api-reference/chat/create-chat-completion), with the playground above pre-filled for the generic chat schema. The notes below describe how to use this endpoint to request Gemini-backed image generation from an OpenAI-compatible client. Include an image-generation model in `model` (such as `gemini-2.0-flash-preview-image-generation`), set `stream` as needed, and supply your prompt through `messages`. Optionally include `contents` for additional Gemini-style multimodal context alongside `messages`. ### Provider-specific notes | Field | Type | Required | Description | | -------------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------- | | `model` | string | Yes | Image-generation model identifier, e.g. `gemini-2.0-flash-preview-image-generation`. | | `messages[].content` | string | Yes | Prompt text describing the desired image. | | `contents` | array | No | Optional Gemini-style content array for additional multimodal context, not part of the standard OpenAI chat schema. | The `contents` field is a DGrid extension layered on top of the standard chat completions schema — it lets you pass Gemini-native `parts` (such as `inlineData`) alongside the OpenAI-style `messages` array when the target model supports it. ### Example: requesting an image ```json theme={null} { "model": "gemini-2.0-flash-preview-image-generation", "stream": false, "messages": [ { "role": "user", "content": "Generate an image of a futuristic city skyline at sunset." } ] } ``` ### Response fields The response follows the standard chat completions shape. The generated image is embedded directly in the assistant message content: Returned choice entries. Choice index. Assistant message object. Message role, typically `assistant`. Message content. For image-output models, this is a markdown image reference embedding the generated image as a base64 data URI, e.g. `![generated image](data:image/png;base64,...)`. Finish reason, e.g. `stop`. Token usage summary. ### Example response ```json 200 theme={null} { "id": "chatcmpl-abc123", "model": "gemini-2.0-flash-preview-image-generation", "object": "chat.completion", "created": 1719859200, "choices": [ { "index": 0, "message": { "role": "assistant", "content": "![generated image](data:image/png;base64,)" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 12, "completion_tokens": 0, "total_tokens": 12 } } ``` # Qwen Image Edits Source: https://docs.dgrid.ai/api-reference/images/qwen-image-edits api-reference/openapi.json POST /v1/images/edits Edit an uploaded image with an optional mask using the OpenAI-compatible image editing endpoint. Also accepts Qwen-compatible JSON payloads with an `input.messages` wrapper. This page uses the same `images/edits` operation as [Edit image](/api-reference/images/edit-image), with the playground above pre-filled for the generic OpenAI-style edit schema (`image`, `mask`, `prompt`, etc.). The notes below describe the Qwen-specific request shape for `wanx-v1` style models. Qwen image editing models accept an alternate JSON request shape that wraps your editing instructions and source image references inside `input.messages`, rather than uploading `image`/`mask` files via multipart form data. Provide `model` and `input` together in the playground's request body to use this shape. ### Qwen-specific request fields | Field | Type | Required | Description | | -------------------------- | ------ | -------- | ----------------------------------------------------------------------------------------------- | | `model` | string | Yes | Model identifier, such as `wanx-v1`. | | `input` | object | Yes | Input wrapper object sent in the request body, used instead of multipart `image`/`mask` fields. | | `input.messages` | array | Yes | Messages array nested under `input`. | | `input.messages[].role` | string | Yes | Message role, e.g. `user`. | | `input.messages[].content` | string | Yes | Editing instructions and any referenced source image(s). | Source images can be referenced inline within `input.messages[].content` (for example as URLs or embedded references) rather than as separate multipart file uploads. ### Example: editing an image ```json theme={null} { "model": "wanx-v1", "input": { "messages": [ { "role": "user", "content": "Remove the background and replace it with a solid white backdrop." } ] } } ``` ### Response fields The response follows the standard image edit shape: Creation timestamp. Generated image entries. Image URL. Base64 image payload. Revised prompt returned by the model. ### Example response ```json 200 theme={null} { "created": 1719859200, "data": [ { "url": "https://cdn.dgrid.ai/generated/edited-abc123.png", "b64_json": "", "revised_prompt": "The subject with background removed and replaced with a solid white backdrop." } ] } ``` # Qwen Image Generations Source: https://docs.dgrid.ai/api-reference/images/qwen-image-generations api-reference/openapi.json POST /v1/images/generations OpenAI-compatible image generation. Also accepts Qwen-compatible payloads (`wanx-v1` style models) using an `input.messages` wrapper instead of `prompt`. This page uses the same `images/generations` operation as [Create image](/api-reference/images/create-image), with the playground above pre-filled for the generic OpenAI-style image schema (`prompt`, `model`, `size`, etc.). The notes below describe the Qwen-specific request shape for `wanx-v1` style models. Qwen image models accept an alternate request shape that wraps your prompt inside `input.messages` rather than a top-level `prompt` field. Provide `model` and `input` together in the playground's request body to use this shape. ### Qwen-specific request fields | Field | Type | Required | Description | | -------------------------- | ------ | -------- | ------------------------------------------------------------------------------- | | `model` | string | Yes | Model identifier, such as `wanx-v1`. | | `input` | object | Yes | Input wrapper object sent in the request, used instead of a top-level `prompt`. | | `input.messages` | array | Yes | Messages array nested under `input`. | | `input.messages[].role` | string | Yes | Message role, e.g. `user`. | | `input.messages[].content` | string | Yes | Prompt text describing the desired image. | Unlike the standard `prompt`/`size`/`quality` fields shown in the playground, Qwen's `wanx-v1` models read the prompt from `input.messages[].content`. Other top-level fields such as `n` and `response_format` are not used by this format. ### Example: generating an image ```json theme={null} { "model": "wanx-v1", "input": { "messages": [ { "role": "user", "content": "A serene mountain lake at dawn, photorealistic." } ] } } ``` ### Response fields The response follows the standard image generation shape: Creation timestamp. Generated image entries. Image URL. Base64 image payload. Revised prompt returned by the model. ### Example response ```json 200 theme={null} { "created": 1719859200, "data": [ { "url": "https://cdn.dgrid.ai/generated/abc123.png", "b64_json": "", "revised_prompt": "A serene mountain lake at dawn with mist rising off the water, photorealistic." } ] } ``` # Introduction Source: https://docs.dgrid.ai/api-reference/introduction Overview of DGrid's three API surfaces — the Model API, Management API Keys, and x402 pay-per-inference API — with authentication and base URLs. The DGrid API Reference is organized into three API surfaces, each with its own authentication model and purpose: OpenAI-, Claude-, and Gemini-compatible endpoints for chat, completions, embeddings, images, audio, and moderations. Programmatic lifecycle management for Model API Keys — create, rotate, limit, disable, and revoke. Pay-per-inference access using the x402 payment protocol, with no pre-funded account balance. Every Model API reference page has an interactive playground: fill in your API key and parameters, then press **Send** to test the endpoint live against `https://api.dgrid.ai`. ## Model API The Model API gives you a single gateway to 200+ leading AI models. Every endpoint is compatible with an ecosystem standard — OpenAI, Claude, or Gemini — so your existing SDKs and tooling work unchanged. For request-level cost reconciliation, store the `DGrid-Request-ID` response header and use [Get request billing details](/api-reference/usage-and-billing/get-request-billing-details) to retrieve token usage, pricing, and USD cost details. ### Base URL ```text theme={null} https://api.dgrid.ai ``` ### Authentication All Model API endpoints authenticate with a bearer token: ```http theme={null} Authorization: Bearer ``` The Claude-compatible `POST /v1/messages` endpoint additionally requires: ```http theme={null} anthropic-version: 2023-06-01 ``` Get your key by following the [key creation guide](https://blog.dgrid.ai/posts/2026-01-04/), or use the [Management API Keys](/management-api-keys) surface for programmatic key lifecycle management. ### Model naming The `model` parameter uses the `provider/model-name` format — for example `openai/gpt-4o` — consistent across all DGrid-supported models. Call [List models](/api-reference/models/list-models) to discover the model IDs available to your key. ### Endpoint families | Family | Base path | Best for | | --------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | Chat | `/v1/chat/completions`, `/v1/responses`, `/v1/messages`, `/v1/models/{model}:generateContent` | Conversational apps, multimodal assistants, tool calling | | Completions | `/v1/completions` | Prompt-only text generation and legacy integrations | | Embeddings | `/v1/embeddings`, `/v1/engines/{engine}/embeddings` | Search, clustering, retrieval, ranking | | Images | `/v1/images/generations`, `/v1/images/edits` | Image generation and editing across model formats | | Audio | `/v1/audio/speech`, `/v1/audio/transcriptions`, `/v1/audio/translations` | Speech synthesis, transcription, translation | | Moderations | `/v1/moderations` | Content safety filtering and policy checks | | Models | `/v1/models` | Discover available models and supported endpoint types | | Usage & Billing | `/api/v1/model-router/billing-json` | Retrieve request-level token usage, pricing snapshots, and USD cost details | | Realtime | `/v1/realtime` (WebSocket) | Low-latency streaming conversations | ### Best practices 1. Store the DGrid API key on the server side and never expose it in public clients or repositories. 2. Prefer the OpenAI-compatible format when you want the broadest SDK compatibility with minimal migration effort. 3. Use provider-native formats only when you need provider-specific payload features such as Gemini multimodal parts or Claude tool payloads. 4. Keep request and response examples in sync with your target model family, because parameter names differ between OpenAI, Claude, and Gemini styles. ## Management API Keys Management API Keys are administrative credentials for the full lifecycle of Model API Keys — creation, rotation, usage limits, disabling, and revocation. They are restricted to key management operations and cannot call Model API inference endpoints. See [Management API Keys](/management-api-keys) for the API surfaces, authentication boundaries, and endpoint reference. ## x402 API The x402 API is DGrid's pay-per-inference access mode. Instead of creating an account or pre-funding a balance, requests are authorized and settled per call using the x402 payment protocol — well suited to autonomous agents and on-demand integrations. See [x402 API](/x402/overview) for the payment flow and [x402 API Reference](/x402/api-reference) for endpoint details. # List models Source: https://docs.dgrid.ai/api-reference/models/list-models api-reference/openapi.json GET /v1/models Retrieve all models visible to the current API key. The result is permission-aware and scoped to the key's assigned access group. # Create moderation Source: https://docs.dgrid.ai/api-reference/moderations/create-moderation api-reference/openapi.json POST /v1/moderations OpenAI-compatible content safety checks for user-generated or model-generated text. Evaluates input against categories such as hate, harassment, self-harm, sexual content, and violence. # Get request billing details Source: https://docs.dgrid.ai/api-reference/usage-and-billing/get-request-billing-details Retrieve token usage, pricing, and USD cost details for a completed Model API request. Retrieve the billing record for a single Model API request. Use this endpoint when you need to reconcile user-facing usage, audit model costs, or inspect the pricing snapshot that was applied when a request was billed. Use the same DGrid API key that made the original model request. Billing records are scoped to the authenticated key and cannot be queried across keys. ## Endpoint ```http theme={null} GET https://api.dgrid.ai/api/v1/model-router/billing-json?request_id= ``` | | | | ------------------ | --------------------------------------- | | **Authentication** | `Authorization: Bearer ` | | **Request** | Query parameter | | **Response** | `application/json` | ## Query parameters | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ------------------------------------------------------------------------------------- | | `request_id` | string | Yes | The ID of the completed Model API request whose billing details you want to retrieve. | ## Get the request ID DGrid returns the request ID in the `DGrid-Request-ID` response header of the original model call. Store this value if you need to retrieve the request's billing details later. ```http theme={null} DGrid-Request-ID: req_178027***********6dc9x ``` ## Request example ```bash cURL theme={null} curl --location \ 'https://api.dgrid.ai/api/v1/model-router/billing-json?request_id=' \ --header 'Authorization: Bearer ' ``` ## Response ### 200 OK The billing record was found and belongs to the authenticated API key. ```json 200 theme={null} { "code": 200, "message": "ok", "data": { "request_id": "req_**********86dc9x", "billing_json": { "model": "anthropic/claude-opus-4.6", "input_cost": 0.54909, "output_cost": 0.0027500000000000003, "cache_create_cost": 0, "cache_read_cost": 0, "request_cost": 0, "total_cost": 0.55184, "supplier_id": 1, "input_tokens": 109818, "output_tokens": 110, "cache_create_tokens": 0, "cache_read_tokens": 0, "pricing_mode": "usage", "pricing_snapshot": { "pricing_mode": "usage", "input_price_per_1m": 5, "output_price_per_1m": 25, "cache_create_price": 6.25, "cache_read_price": 0.5, "price_per_request": null, "input_tiers": [], "output_tiers": [], "cache_create_tiers": [], "cache_read_tiers": [] } } } } ``` ```json 401 theme={null} { "code": 401, "message": "unauthorized" } ``` ```json 404 theme={null} { "code": 404, "message": "not found" } ``` ## Billing fields | Field | Description | | ------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `model` | Model ID used by the original request. | | `input_tokens` / `output_tokens` | Token counts charged for prompt and generated output. | | `cache_create_tokens` / `cache_read_tokens` | Cache-related token counts when cache pricing applies. | | `input_cost` / `output_cost` | USD cost attributed to input and output token usage. | | `cache_create_cost` / `cache_read_cost` | USD cost attributed to cache creation and cache reads. | | `request_cost` | Fixed per-request USD cost when the pricing mode includes one. | | `total_cost` | Final USD cost billed for the request. | | `pricing_snapshot` | The pricing configuration used at billing time. Later price changes do not modify this historical record. | ## Best practices * Save `DGrid-Request-ID` with your own request logs so you can reconcile usage later. * Treat `pricing_snapshot` as an immutable historical record for the request. * All cost and price fields are denominated in USD. * Numeric values may contain variable decimal precision. Do not rely on fixed-width decimal formatting. # Background Source: https://docs.dgrid.ai/background Market pain points, industry gaps, and the centralized AI infrastructure problems that motivated DGrid's decentralized inference network. In the current field of artificial intelligence, both centralized systems and Web3 ecosystems face key constraints that hinder the seamless integration of artificial intelligence and blockchain. The AI industry is experiencing explosive growth, yet it lacks both market efficiency and fairness, which restricts the overall development of the ecosystem. ## Market Pain Points: Fragmented Prosperity and Centralized Control In the current field of artificial intelligence, both centralized systems and Web3 ecosystems face key constraints that hinder the seamless integration of artificial intelligence and blockchain. The AI industry is experiencing explosive growth, yet it lacks both market efficiency and fairness, which restricts the overall development of the ecosystem. 1. **Explosive Supply and Fragmented Ecosystem**: The number of proprietary, open-source, fine-tuned models and AI Agents is surging. However, inconsistent interface specifications and drastic quality disparities make it difficult for resources to interoperate and be compatible with each other. 2. **Matching Failure and Value Obscuration**: For developers, the cost of finding, testing, and integrating suitable models and Agents is extremely high, leading to low efficiency. For creators, excellent models and Agents lack efficient distribution channels, with their value monopolized by centralized platforms, resulting in an imbalanced profit distribution. 3. **Lack of Trust and Concentration of Power**: The service process operates in a "black box" mode—AI output results are neither verifiable nor auditable, and there is no room for autonomous governance. Centralized hierarchies control pricing power and traffic distribution, depriving the ecosystem of transparency and fairness. The mission of DGrid AI is to ***"reconstruct the underlying architecture of AI inference"*** by building decentralized infrastructure, freeing AI operations and applications from dependence on a few large platforms. The ultimate goal is to make artificial intelligence a native foundational capability of the blockchain world—seamlessly integrated into blockchain applications, just like current data storage and transaction processing. # Circulation Mechanism Source: https://docs.dgrid.ai/circulation-mechanism How the $DGAI token flows through the DGrid economy via staking, inference payments, rewards, and buyback to form a closed-loop value cycle. \$DGAI operates within a closed-loop economic system, ensuring transparent value flow among users, node operators, and the broader ecosystem. This mechanism is governed by smart contracts (e.g., Bill Contract) and enforced via DGrid Nodes, eliminating intermediaries and aligning incentive mechanisms with network health. ## Core Cycle: From Payment to Rewards The circulation of \$DGAI follows a structured process that links users' inference demands to node contributions: 1. **Initiation of User Payment** When a user submits an inference request via the user client, the process unfolds as follows: * The request is routed to a DGrid Node, which calculates the task fee using the following formula: `Cost = Compute Unit (CU) × Base Price × (1 + Latency Penalty Coefficient)` - **Compute Unit (CU)**: A standardized metric for measuring inference complexity (correlated with model size, number of input tokens, and execution time). - **Base Price**: A fixed price per CU (adjustable via governance mechanisms, with an initial value of 0.05 \$DGAI). - **Latency Penalty Coefficient**: Ranges from 0 to 0.3 (fine-tuned for latency exceeding the target threshold). * The user's \$DGAI is escrowed via the **Bill Contract**—a smart contract deployed on the blockchain—to ensure payment upon task completion. 2. **Distribution of Node Rewards** After inference is completed (verified by Grid Nodes and archived in the AI DA Layer), the escrowed \$DGAI is distributed via the Bill Contract. Recipients include: * **DGrid Nodes**: Compensation for executing inference tasks (proportional to CU, latency, and uptime). * **Treasury**: Used for network maintenance (e.g., AI DA Layer fees, security audits) and developer grants. * **Governance Pool**: Incentivizes \$DGAI holders to participate in voting (e.g., protocol upgrades, parameter adjustments). 3. **Staking and Lock-Up Requirements** Nodes participating in the network must lock up \$DGAI as collateral to ensure accountability. 4. **Governance and Fee Allocation** * **Governance Pool**: 5% of task payments (plus 10% of annual treasury funds) are distributed to \$DGAI holders who participate in proposal voting (e.g., adjusting base prices, whitelisting new models). * **Network Fees**: A 2% processing fee is deducted upfront from all task payments to cover smart contract gas costs and AI DA Layer archiving, ensuring transaction efficiency. 5. **Penalty Mechanisms and Token Burning** Node violations trigger automatic penalties to protect network integrity: * **Confiscated Tokens**: 5–20% of a node's staked \$DGAI will be confiscated for malicious behaviors (e.g., submitting false inference results, downtime exceeding 72 hours). * **Burning Mechanism**: All confiscated tokens are permanently burned, reducing the total supply of \$DGAI over time and enhancing scarcity. ## Key Processes: Capital Inflows and Outflows | Inflows (Sources of \$DGAI) | Outflows (Uses of \$DGAI) | | -------------------------------------------------- | ---------------------------------------------- | | Fees paid by users for inference tasks | Rewards for node operators for inference tasks | | Weekly rewards for DGrid Nodes | Staking lock-up for node participation | | Governance rewards for voting participants | Network fees (gas, AI DA Layer archiving) | | Initial distribution (e.g., public sale, airdrops) | Confiscated tokens (burned) | This mechanism ensures \$DGAI maintains utility as both a medium of exchange and a governance tool, fostering a self-sustaining ecosystem where value is proportional to network participation. By linking payments to contributions and enforcing accountability through staking mechanisms, the circulation of \$DGAI reinforces the decentralization and resilience of DGrid AI. # Core Functions Source: https://docs.dgrid.ai/core-functions The four core functions of $DGAI — staking, payment, incentives, and governance — that power the DGrid decentralized AI inference network. As the native token of the network, \$DGAI undertakes four core functions—staking, payment, incentives, and governance—constructing a positive ecological cycle and driving every key interaction within the DGrid AI ecosystem. ## Staking and Access Nodes and AI service providers must stake \$DGAI to gain network traffic, establish a reputation system, and ensure network security. Staking requirements are tiered based on node type (node performance), and staked tokens serve as collateral for violating behaviors (e.g., submitting false inference results, downtime exceeding 72 hours). Malicious nodes will face confiscation of 5–20% of staked \$DGAI or temporary deactivation; these measures are automatically enforced through smart contracts. ## Payment for Inference Tasks Users pay with \$DGAI via DGrid nodes to access Large Language Model (LLM) inference and Agent services. Fees are dynamically calculated based on the following factors: * **Compute Unit (CU)**: A standardized metric for measuring inference complexity (linked to model size, number of input tokens, and execution time). * **Latency**: Adjusted based on task speed (faster execution earns rewards, while latency incurs minor penalties). Payments are automatically processed through the **Bill Contract**, a smart contract deployed on the blockchain. This contract deducts \$DGAI from user accounts and distributes funds to node operators, service providers, etc., ensuring transparency and immutability of transactions. ## Rewards for Node Operators The network rewards high-quality nodes and AI service providers with \$DGAI based on service quality, usage volume, and user evaluations to stimulate enthusiasm for contributions. Operators earn \$DGAI based on their contributions to inference tasks (e.g., number of CUs processed, low latency, and uptime). Rewards are proportional to performance—nodes hosting large models (over 13B parameters) or processing high-priority requests receive higher rewards. Rewards are distributed weekly via the Bill Contract, with detailed records archived in the AI DA Layer to ensure auditability. ## Network Governance \$DGAI is a governance token; token holders have the right to vote on key matters related to network development, ensuring decisions align with the interests of active network participants. Proposals include: * Adjusting the fee structure (e.g., base CU pricing, latency penalties). * Adding new Large Language Models (LLMs) to the whitelist for network support. * Upgrading core protocols (e.g., DGrid AI Gateway) or settlement rules. * Allocating treasury funds to promote ecosystem growth (e.g., developer grants, security audits). Voting power is proportional to staked \$DGAI, ensuring decisions align with the interests of active network participants. # DClaw Source: https://docs.dgrid.ai/dclaw DClaw is DGrid's one-click deployment layer for spinning up personal AI agents on decentralized nodes without managing infrastructure or servers. **DClaw** is DGrid's one-click deployment layer for personal AI agents. Built on top of **CoPaw**, it helps individuals, developers, teams, and communities launch persistent, user-owned agents with less setup and lower operational complexity. Instead of assembling model access, memory, channels, and agent skills across multiple external services, DClaw provides a more unified deployment experience inside the DGrid ecosystem. The result is a faster path from an agent idea to a working agent that can operate in real environments. ## What DClaw Does DClaw is designed to turn personal agents from a prototype concept into a usable, production-oriented service. A deployed DClaw agent can: * maintain persistent context across interactions * communicate through multiple channels from a single agent identity * execute tasks on behalf of the user in real workflows * evolve over time through memory, skills, and plugin-based extensions In practical terms, DClaw shifts AI from a tool users open manually into an agent that can remain present where communication and coordination already happen. ## Why DClaw Matters Traditional open-source agent frameworks often require environment setup, service orchestration, manual configuration, and ongoing maintenance before an agent becomes usable. DClaw reduces that overhead by packaging key agent infrastructure into a simpler deployment layer. Compared with a framework-first approach such as OpenClaw, DClaw emphasizes: * **one-click deployment** rather than multi-step environment setup * **integrated DGrid API access** instead of stitching together several external services * **built-in models, channels, memory, and skills** in a single workflow * **faster delivery to live usage** for both technical and non-technical users ## Core Capabilities ### Multi-Channel Agent Presence DClaw supports a growing set of communication channels and protocols, including Telegram, iMessage, Matrix, DingTalk, WeCom, WeChat, MQTT, and Twilio-based APIs. This allows one agent to interact across work, social, and developer environments without repeated setup or fragmented identities. ### User-Owned Persistent Memory DClaw includes a persistent memory system that stores useful context such as prior conversations, user preferences, recurring workflows, and task history. The design principle is **user-owned memory**: personalization should remain under the user's control rather than depend on opaque data retention. ### Skills and Plugin Extensibility DClaw agents can be extended through modular skills and plugins. Users can adopt community skills, develop custom capabilities, swap skills without rebuilding the agent, and support increasingly specialized workflows over time. ### Built-In Model Access DClaw includes access to leading AI models without requiring separate API configuration at the start. Users can rely on DClaw's routing logic to select an appropriate model based on capability, latency, and cost, while still retaining the option to choose models directly when needed. ## Typical Usage A typical DClaw workflow is straightforward: 1. Deploy an agent through the DClaw layer. 2. Connect the channels in which the agent should operate. 3. Define the agent's role, memory preferences, and required skills. 4. Let the agent handle recurring coordination, information, or task-oriented workflows. This makes DClaw suitable for use cases such as: * personal productivity assistants * team coordination and reporting agents * ecosystem monitoring or research assistants * developer agents for deployment, debugging, or operations support ## Summary DClaw is the deployment layer that makes personal agents easier to launch, easier to extend, and more practical to use at scale within the DGrid ecosystem. It combines simplified deployment with persistent memory, multi-channel presence, extensibility, and integrated model access so users can move from setup to real agent workflows in minutes. # DGrid's Solution Source: https://docs.dgrid.ai/dgrid-solution Core architecture, key modules, and technical design of DGrid AI's decentralized inference network for routing, verification, and incentives. ***DGrid AI = Decentralized Routing & Verification Network + LLM & Agent Free Market + AI DAO Governance System*** DGrid AI addresses the critical gaps between Web3 AI and centralized AI through an interconnected ecosystem composed of nodes, protocols, and decentralized infrastructure. By integrating standardized AI RPC interfaces, distributed inference nodes, intelligent routing, on-chain settlement, and secure storage, we have built a trustless, scalable, and user-centric LLM and Agent service network—enabling AI to become a native capability of blockchain applications. At its core, DGrid's solution redefines decentralized AI inference through three foundational components: distributed nodes for model execution with result trustworthiness guaranteed by **Proof of Quality (PoQ)**, standardized protocols for universal access, and on-chain mechanisms for full transparency. DGrid solution architecture diagram ## 1. Decentralized Routing & Verification Network * **Unified Intelligent Access**: Provides developers with a single API to access thousands of specialized models and preconfigured Agents simultaneously, significantly reducing integration costs. * **Intelligent Routing & Scheduling**: Automatically recommends and schedules optimal service resources based on multi-dimensional metrics including task type, budget constraints, and historical performance data. * **Trusted Verification Mechanism**: Leverages the **Proof of Quality (PoQ)** algorithm to ensure the trustworthiness of AI and Agent workflows and output results, achieving efficient, censorship-resistant, and traceable services. ## 2. LLM & Agent Free Market * **Open Listing Opportunities**: Model providers, AI developers, and prompt engineers can list fine-tuned models or customized Agents on the DGrid network, set their own prices, and earn revenue directly from global users through a transparent competition mechanism. * **Value Tokenization**: High-quality models and Agents can be tokenized on DGrid to capture long-term market value. ## 3. DGrid Nodes: Decentralized Inference Execution DGrid Nodes are community-operated nodes that form the computational core of the network by hosting one or more Large Language Models (LLMs, e.g., Llama-2, Mixtral) and AI Agents. These nodes: * Execute inference tasks for users, process inputs (e.g., text prompts, smart contract queries), generate outputs via preloaded models, and verify inference result quality through the **PoQ (Proof of Quality)** mechanism to ensure output trustworthiness and accuracy. * Adapt to hardware capabilities: Operators can select models matching their server specifications—ranging from lightweight 7B-parameter models on basic GPUs to 70B+-parameter models on high-performance hardware. * Report real-time metrics (latency, Compute Unit \[CU] consumption) to the DGrid network, providing data support for intelligent routing and enabling optimized task allocation. By distributing inference tasks across thousands of independent nodes, DGrid eliminates single points of failure and ensures geographic redundancy—critical for Web3 applications requiring 24/7 reliability. ## 4. DGrid AI Gateway: Universal Access & Request Verification * **DGrid AI Gateway**: A standardized JSON-RPC protocol that simplifies user access to models and Agents in the network. It provides a unified API for invoking any LLM or Agent (regardless of node or model type) and integrates EIP-712 signatures to verify user requests—ensuring only authorized and pre-paid tasks are processed. DGrid AI Gateway resolves the "interface fragmentation" issue in Web3 AI, making LLM and Agent integration as straightforward as calling a smart contract. ## 5. Proof of Quality (PoQ): Trust Guarantee for Inference Results **Proof of Quality (PoQ)** is the core mechanism in the DGrid ecosystem that ensures the trustworthiness of LLM inference and Agent execution results. Working in tandem with distributed nodes and DGrid AI Gateway, it forms a closed-loop "Request-Execution-Verification" workflow: * **Multi-Dimensional Quality Assessment**: PoQ objectively scores inference results generated by DGrid Nodes based on three key dimensions: **accuracy alignment** (comparison against standard answers or reference results), **response consistency** (output deviation of the same request across different nodes), and **format compliance** (adherence to user-specified output requirements). The evaluation framework further incorporates cost-efficiency considerations and semantic similarity verification logic to balance high quality with low overhead. * **On-Chain Verifiable Proof Generation**: After completing an inference task, nodes upload inference process logs and PoQ score data to the network to generate tamper-proof quality proofs. Users can query these proofs on-chain to quickly verify result reliability without re-executing inference tasks. Combined with a hybrid verification architecture, this mechanism achieves low latency and low cost while ensuring computational integrity. ## 6. Billing Contracts & AI DA Layer: On-Chain Transparency * **Billing Contracts**: Smart contracts deployed on the blockchain for automated \$DGAI token settlement between users and nodes. These contracts calculate fees based on Compute Units (CU) and latency, deduct payments from user accounts via the x402 protocol, and distribute rewards to node operators—eliminating intermediaries. * **AI DA Layer (Data Availability)**: A decentralized storage network where all inference request data is secured by PoQ to ensure auditability. Users can verify billing details, and nodes can prove task completion, thereby increasing transparency for dispute resolution or compliance audits. ## 7. Security Mechanisms DGrid AI has established a comprehensive security framework to ensure trustlessness in the decentralized network, combining technical safeguards with on-chain transparency: ### Trusted Inference Environment * **Immutable Runtime**: DGrid Node operators cannot modify the weights or execution environments of Large Language Models (LLMs) and AI Agents, ensuring consistent model behavior across the network. * **Resource Controls**: Strict limits on CPU, GPU, and network usage (enforced by nodes) prevent Denial of Service (DoS) attacks. ### On-Chain Auditing & Accountability * **Tamper-Proof Records**: All critical activities—node registration, inference metadata (inputs/outputs), fee settlements, and rewards—are recorded on-chain via Billing Contracts and stored in the AI DA Layer. * **Automatic Penalty Mechanisms**: The DGrid network monitors node behavior; malicious actors (e.g., submitting false results) face penalties such as confiscation of staked tokens or node blacklisting, enforced by smart contracts. * **Decentralized Governance**: \$DGAI token holders can vote on protocol upgrades, fee structures, and security parameters, ensuring network development aligns with community interests. ## Core Advantages: Defining the Next-Generation AI Infrastructure By integrating decentralized execution, intelligent coordination, secure inference, and transparent settlement, DGrid builds core advantages that distinguish it from traditional centralized AI and existing Web3 AI solutions—redefining the next generation of AI infrastructure: * **End-to-End Trustworthiness**: Based on PoQ quality proofs and on-chain evidence storage, it achieves verifiable and auditable inference processes and results, solving the "black box" problem. * **Seamless Integration Experience**: A single DGrid AI Gateway API is compatible with thousands of models and Agents, significantly reducing developer integration and migration costs. * **Ecosystem Fairness & Win-Win Collaboration**: The open LLM & Agent Free Market and merit-based incentive mechanism ensure value alignment among creators, builders, and users. * **Elasticity & Resilience**: The distributed node network eliminates single points of failure, and geographic redundancy guarantees 24/7 service availability, resisting regional outages and regulatory risks. * **Community-Driven Autonomous Governance**: AI DAO drives network evolution; \$DGAI holders lead key decisions, and AI Agents can participate in automated governance on behalf of users, ensuring ecosystem development aligns with community interests. # Dori Find Models Source: https://docs.dgrid.ai/dori Dori is DGrid's natural-language assistant for discovering, comparing, and evaluating large language models across providers, prices, and benchmarks. **Dori Find Models** is DGrid's natural-language–driven assistant for discovering and evaluating large language models (LLMs). Using Dori, you express your requirements in plain English, test shortlisted models with your own workloads, and receive structured reports to support confident, data-backed model choices. ## Role in the DGrid Platform Dori is one of two tightly integrated capabilities in the DGrid ecosystem: * **Dori Find Models** – Helps you: * Translate business or product requirements into concrete model candidates * Discover, test, and compare models in a guided, conversational flow * **AI Gateway** – Provides: * A single abstraction layer and API over 200+ production-ready LLMs * Configuration-based model choice and switching, without code changes Together, they enable an end-to-end LLM workflow: **Traditional:** Search vendors → create many accounts → test manually → integrate per-vendor **With DGrid (Dori + AI Gateway with LLM Marketplace):** Describe needs → discover & test in one place → integrate once → swap models via config ## Key Capabilities ### 1. Natural-Language Requirements Intake Dori starts from your real-world needs, captured in free-form text. For example: * "We need a low-latency, cost-efficient model for multilingual customer support (English, Spanish, Portuguese), integrated into our existing chatbot." * "We're building a code assistant focusing on Python and TypeScript; strong reasoning and large-context understanding are important." * "We want a model optimized for long-document RAG, with stable performance on 10k+ token contexts." You do **not** need to know exact model names, providers, or benchmark acronyms. Dori interprets your description and translates it into technical selection criteria. ### 2. Intelligent Search Across the LLM Marketplace Once your requirements are captured, Dori searches across the **DGrid LLM Marketplace**, which aggregates 200+ LLMs behind a single interface. Dori: * Filters candidate models by: * **Task fit** (e.g., chat, code, RAG, multi-lingual support) * **Context window** (short vs long context, e.g., 10k+ tokens) * **Latency and cost profiles** * Other relevant operational characteristics * Ranks models according to your priorities: * Throughput and latency sensitivity * Quality vs cost tradeoffs * Specific capability needs (e.g., coding, reasoning, multilinguality) * Returns a **short, relevant list of recommended models**, so you avoid manually inspecting dozens of vendor pages and benchmark tables. ### 3. Unified, Real-Workload Testing After Dori proposes a shortlist, it helps you test those models in a **single environment**, within DGrid: * Run **trials** on candidate models directly in the platform * Use **your own prompts, documents, and scenarios** instead of generic examples * Evaluate models under a **shared, consistent setup**, making comparisons meaningful This eliminates the common pattern of: * Separate vendor playgrounds * Ad-hoc scripts for each API * Screenshots, notes, and spreadsheets spread across tools ### 4. Structured, Shareable Evaluation Dori produces clear, structured outputs that you can share and discuss with your team, such as: * **Example outputs** from each candidate model * **Qualitative notes** about behavior and suitability * **Latency and performance metrics** observed during tests * **Cost estimates** aligned to your expected traffic patterns and load Instead of "gut-feel" and partial information, teams can rely on a traceable evaluation record when choosing "the best model for our use case." ### 5. Tight Integration with the AI Gateway Dori is directly coupled with the AI Gateway, so everything you discover and test is immediately available to integrate in production via: * **One API key** * **One unified endpoint** * **A single, coherent API interface** Key consequences: * You don't need separate auth, SDKs, or endpoints per provider * A model you validate with Dori is ready to be used **without adding a new vendor integration** * Changing models later becomes a **configuration change**, not a redevelopment project ## Typical Use Cases ### Multilingual Customer Support * Need: Low-latency, cost-efficient LLM for a multilingual chatbot (e.g., English, Spanish, Portuguese) * How Dori helps: * Interprets multilingual and latency requirements * Identifies models well-suited to conversational support across those languages * Lets you test using real customer queries and conversation flows ### Code Assistants and Developer Tools * Need: A model for code generation, explanation, and refactoring in languages like Python and TypeScript * How Dori helps: * Highlights models with strong reasoning and coding capabilities * Emphasizes long-context support for large codebases * Facilitates trials using real repositories, code snippets, or tasks ### Long-Context RAG and Document Applications * Need: Stable performance for long-document retrieval-augmented generation (RAG) with 10k+ token contexts * How Dori helps: * Filters models by context length and RAG suitability * Allows evaluation with your actual documents and retrieval setup * Produces reports capturing both quality and performance under large contexts ## Benefits for Different User Types ### Individual Developers & Startup Teams * Focus on product and UX rather than: * Chasing vendor docs * Wiring up multiple APIs and SDKs * Iterate quickly: * Try several models via Dori * Lock in one (or more) via the Marketplace * Swap later as new, better models arrive ### Enterprises & Large Platforms * Standardize LLM access across business units using: * A single integration with the LLM Marketplace * Shared evaluation workflows via Dori * Reduce long-term maintenance: * Avoid bespoke integrations per vendor * Maintain flexibility to adopt new models as the ecosystem evolves ### Web3 and On-Chain Projects * Build AI-powered agents, dApps, and protocols whose model backbone can: * Upgrade over time * Diversify across providers * Preserve on-chain and off-chain integration logic while: * Changing or augmenting underlying LLMs via configuration * Avoiding breaking changes every time you adopt a new model # DGrid AI Documentation Source: https://docs.dgrid.ai/index Access 200+ leading AI models through DGrid's Web3-native gateway. Explore guides, the API reference, tokenomics, and the $DGAI economy.
DGrid AI
The Decentralized
Smart Network of AI
DGrid AI
Explore the platform

See the flagship products that make up the DGrid ecosystem.

One API for 200+ models with Web3-native payments and intelligent routing.
200+ Models OpenAI-compatible
Blind model battles that turn community votes into routing intelligence.
AI Battle \$DGAI Points
The open catalog of 200+ models and providers behind DGrid AI Gateway, browsable and callable through one API.
200+ Models Open Catalog
Build with DGrid

Beyond the API — the economy, programs, and agent layer that power the DGrid ecosystem.

Resources
Explore the live platform at dgrid.ai Product updates and announcements Get help and meet other builders
# Management API Keys Source: https://docs.dgrid.ai/management-api-keys Programmatically create, rotate, list, and revoke DGrid Model API keys to manage the full lifecycle of credentials, scopes, and team access. Management API Keys provide a programmatic way to manage the full lifecycle of Model API Keys. They are designed for enterprise teams, SaaS platforms, and automation systems that need to create, distribute, rotate, enable, disable, or revoke keys without relying on manual console operations. Management API Keys are administrative credentials and are restricted to key management operations. They cannot be used to call model inference or completion endpoints. ## 1. Overview Management API Keys are intended for scenarios such as: * Issuing separate Model API Keys for different customers, projects, or environments * Applying usage limits and automatic reset cycles to downstream Model API Keys * Rotating, disabling, or revoking keys programmatically * Enforcing least-privilege key management in SaaS, multi-tenant, and compliance-focused workflows Core capabilities: * Strict permission isolation for key management operations * Full lifecycle automation for Model API Keys * Configurable usage limits and reset cycles * Designed for server-side services, internal tools, and automated provisioning workflows ## 2. API Surfaces and Authentication Boundaries Key management is split into two API surfaces, each with its own authentication model: | API Surface | Purpose | Authentication | | --------------------------- | ------------------------------------------------ | ---------------------------------------- | | `/v1/management-keys` | Manage Management API Keys | `JWT` | | `/api/v1/model-router/keys` | Manage Model API Keys using a Management API Key | `Authorization: Bearer ` | Important: * A `Management API Key` can only be used with `/api/v1/model-router/keys` * A `Management API Key` cannot be used with `/v1/management-keys` * `/v1/management-keys` only supports `JWT` authentication * The full secret is returned only once when a key is created and cannot be retrieved later ## 3. Basic Rules * Each account can create up to `10` Management API Keys * Management API Keys are enabled immediately after creation * The full Management API Key secret is returned only once * Subsequent list and detail responses return masked key values only * Model API Keys are currently soft-deleted rather than permanently deleted ## 4. Base URL The public API base URL is: ```text theme={null} https://api.dgrid.ai ``` Route prefixes used in this document: ```text theme={null} /v1/management-keys /api/v1/model-router/keys ``` ## 5. Create a Management API Key Before using the Management API, first create a Management API Key in the DGrid console: If you expose this flow in your own UI, clearly inform users that the secret is shown only once and should be stored immediately. ## 6. Authentication This document covers two authentication modes: * Endpoints under `/v1/management-keys` require `JWT` * Endpoints under `/api/v1/model-router/keys` require a Management API Key Use the following header when calling `/api/v1/model-router/keys` endpoints: ```http theme={null} Authorization: Bearer ``` ## 7. Management API Key Lifecycle Endpoints These endpoints are used to create, view, update, enable, disable, and delete Management API Keys. All of them require `JWT` authentication. | Operation | Method | Path | Notes | | ---------------------- | -------- | -------------------------------------- | ------------------------------------ | | Create management key | `POST` | `/v1/management-keys` | Returns the full key only once | | List management keys | `GET` | `/v1/management-keys` | Supports pagination | | Update management key | `PUT` | `/v1/management-keys/{id}` | Currently only `name` can be updated | | Delete management key | `DELETE` | `/v1/management-keys/{id}` | Soft delete | | Enable management key | `POST` | `/v1/management-keys/{id}/enablement` | Takes effect immediately | | Disable management key | `POST` | `/v1/management-keys/{id}/disablement` | Takes effect immediately | Example create response: ```json theme={null} { "code": 200, "message": "ok", "data": { "id": "3ecf9d8d-9b8f-4df6-9d30-7a693e1f0d1c", "name": "prod-admin", "key": "mk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "keyPreview": "mk-x************************xxxx5", "createdAt": "2026-04-23T10:00:00Z", "status": "Enabled", "enabled": true } } ``` Notes: * `key` is returned only once at creation time * `keyPreview` is the masked display value ## 8. Manage Model API Keys with a Management API Key All endpoints in this section use: ```http theme={null} Authorization: Bearer ``` ### 8.1 Request Fields The current implementation supports the following fields when creating or updating a Model API Key: | Field | Type | Required | Description | | ----------- | ---------------------------- | ------------------ | --------------------------- | | `name` | `string` | Required on create | Key name | | `limit` | `number` | No | Usage limit | | `cycle` | `daily \| weekly \| monthly` | No | Reset cycle for the limit | | `expiredAt` | `string` | No | Expiration timestamp in UTC | | `groupId` | `string` | No | Group ID | Notes: * If you are familiar with OpenRouter's `limit_reset`, the closest equivalent in the current DGrid implementation is `cycle` * `expiredAt` should use an ISO 8601 UTC timestamp such as `2026-12-31T23:59:59Z` ### 8.2 List Keys * Method: `GET` * Path: `/api/v1/model-router/keys` * Query parameters: * `page`: page number, default `1` * `size`: page size, default `20`, maximum `100` Implementation notes: * Pagination uses `page` and `size`, not `limit` and `offset` * Partial name search is not currently supported * `disabled` filtering is not currently supported Request example: ```bash theme={null} curl "https://api.dgrid.ai/api/v1/model-router/keys?page=1&size=20" \ -H "Authorization: Bearer " ``` Response example: ```json theme={null} { "code": 200, "message": "ok", "data": { "total": 2, "page": 1, "items": [ { "id": "e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111", "name": "prod-key", "key": "sk-a************************f9x2d", "limit": 1000, "usageInCycle": 12.34, "usageInTotal": 98.76, "enabled": true, "cycle": "monthly", "expiredAt": "2026-12-31T23:59:59Z", "groupId": null, "groupName": "" } ] } } ``` Field notes: * `key`: masked API key value * `usageInCycle`: usage within the current cycle * `usageInTotal`: cumulative usage * `enabled`: current enabled state * `groupName`: group name ### 8.3 Create a Model API Key * Method: `POST` * Path: `/api/v1/model-router/keys` Request example: ```bash theme={null} curl -X POST "https://api.dgrid.ai/api/v1/model-router/keys" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "name": "prod-key", "limit": 1000, "cycle": "monthly", "expiredAt": "2026-12-31T23:59:59Z" }' ``` Request body example: ```json theme={null} { "name": "prod-key", "limit": 1000, "cycle": "monthly", "expiredAt": "2026-12-31T23:59:59Z" } ``` Response example: ```json theme={null} { "code": 200, "message": "ok", "data": { "id": "e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111", "key": "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } ``` Notes: * `key` is the full API key value and is returned only once * Store it immediately in a secure secrets management system ### 8.4 Get Key Details * Method: `GET` * Path: `/api/v1/model-router/keys/{id}` Implementation note: * The current implementation uses `id (UUID)`, not `key_hash` Request example: ```bash theme={null} curl "https://api.dgrid.ai/api/v1/model-router/keys/e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111" \ -H "Authorization: Bearer " ``` Response example: ```json theme={null} { "code": 200, "message": "ok", "data": { "id": "e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111", "name": "prod-key", "key": "sk-a************************f9x2d", "limit": 1000, "usageInCycle": 12.34, "usageInTotal": 98.76, "enabled": true, "cycle": "monthly", "expiredAt": "2026-12-31T23:59:59Z", "groupId": null, "groupName": "" } } ``` ### 8.5 Update a Model API Key * Method: `PUT` * Path: `/api/v1/model-router/keys/{id}` Currently supported update fields: * `name` * `limit` * `cycle` * `groupId` Request example: ```bash theme={null} curl -X PUT "https://api.dgrid.ai/api/v1/model-router/keys/e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "name": "prod-key-v2", "limit": 2000, "cycle": "monthly" }' ``` Request body example: ```json theme={null} { "name": "prod-key-v2", "limit": 2000, "cycle": "monthly" } ``` Implementation note: * The current update method is `PUT`, not `PATCH` ### 8.6 Disable a Model API Key * Method: `POST` * Path: `/api/v1/model-router/keys/{id}/disablement` Request example: ```bash theme={null} curl -X POST "https://api.dgrid.ai/api/v1/model-router/keys/e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111/disablement" \ -H "Authorization: Bearer " ``` After it is disabled, the API key can no longer be used for model calls. ### 8.7 Enable a Model API Key * Method: `POST` * Path: `/api/v1/model-router/keys/{id}/enablement` Request example: ```bash theme={null} curl -X POST "https://api.dgrid.ai/api/v1/model-router/keys/e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111/enablement" \ -H "Authorization: Bearer " ``` ### 8.8 Delete a Model API Key * Method: `DELETE` * Path: `/api/v1/model-router/keys/{id}` Request example: ```bash theme={null} curl -X DELETE "https://api.dgrid.ai/api/v1/model-router/keys/e8f9c547-4f0c-4d8b-8e1b-8ef9b0aa1111" \ -H "Authorization: Bearer " ``` Implementation note: * Deletion is currently a soft delete rather than a physical delete ## 9. Example Usage ```python Python theme={null} import requests BASE = "https://api.dgrid.ai/api/v1/model-router" MANAGEMENT_KEY = "mk-your-management-key" headers = { "Authorization": f"Bearer {MANAGEMENT_KEY}", "Content-Type": "application/json" } # 1) List keys resp = requests.get( f"{BASE}/keys", headers=headers, params={"page": 1, "size": 20} ) print("LIST:", resp.json()) # 2) Create key resp = requests.post( f"{BASE}/keys", headers=headers, json={ "name": "prod-key", "limit": 1000, "cycle": "monthly", "expiredAt": "2026-12-31T23:59:59Z" } ) create_data = resp.json() print("CREATE:", create_data) key_id = create_data["data"]["id"] # 3) Get key resp = requests.get(f"{BASE}/keys/{key_id}", headers=headers) print("GET:", resp.json()) # 4) Update key resp = requests.put( f"{BASE}/keys/{key_id}", headers=headers, json={ "name": "prod-key-v2", "limit": 2000, "cycle": "monthly" } ) print("UPDATE:", resp.json()) # 5) Disable key resp = requests.post(f"{BASE}/keys/{key_id}/disablement", headers=headers) print("DISABLE:", resp.json()) # 6) Enable key resp = requests.post(f"{BASE}/keys/{key_id}/enablement", headers=headers) print("ENABLE:", resp.json()) # 7) Delete key resp = requests.delete(f"{BASE}/keys/{key_id}", headers=headers) print("DELETE:", resp.json()) ``` ```typescript TypeScript theme={null} const BASE = "https://api.dgrid.ai/api/v1/model-router"; const MANAGEMENT_KEY = "mk-your-management-key"; const headers: HeadersInit = { Authorization: `Bearer ${MANAGEMENT_KEY}`, "Content-Type": "application/json", }; async function main() { const listResp = await fetch(`${BASE}/keys?page=1&size=20`, { method: "GET", headers, }); console.log("LIST:", await listResp.json()); const createResp = await fetch(`${BASE}/keys`, { method: "POST", headers, body: JSON.stringify({ name: "prod-key", limit: 1000, cycle: "monthly", expiredAt: "2026-12-31T23:59:59Z", }), }); const createData = await createResp.json(); console.log("CREATE:", createData); const keyId = createData.data.id; const getResp = await fetch(`${BASE}/keys/${keyId}`, { method: "GET", headers, }); console.log("GET:", await getResp.json()); const updateResp = await fetch(`${BASE}/keys/${keyId}`, { method: "PUT", headers, body: JSON.stringify({ name: "prod-key-v2", limit: 2000, cycle: "monthly", }), }); console.log("UPDATE:", await updateResp.json()); const disableResp = await fetch(`${BASE}/keys/${keyId}/disablement`, { method: "POST", headers, }); console.log("DISABLE:", await disableResp.json()); const enableResp = await fetch(`${BASE}/keys/${keyId}/enablement`, { method: "POST", headers, }); console.log("ENABLE:", await enableResp.json()); const deleteResp = await fetch(`${BASE}/keys/${keyId}`, { method: "DELETE", headers, }); console.log("DELETE:", await deleteResp.json()); } main().catch(console.error); ``` ```javascript JavaScript theme={null} const BASE = "https://api.dgrid.ai/api/v1/model-router"; const MANAGEMENT_KEY = "mk-your-management-key"; const headers = { Authorization: `Bearer ${MANAGEMENT_KEY}`, "Content-Type": "application/json", }; async function main() { let resp = await fetch(`${BASE}/keys?page=1&size=20`, { method: "GET", headers, }); console.log("LIST:", await resp.json()); resp = await fetch(`${BASE}/keys`, { method: "POST", headers, body: JSON.stringify({ name: "prod-key", limit: 1000, cycle: "monthly", expiredAt: "2026-12-31T23:59:59Z", }), }); const createData = await resp.json(); console.log("CREATE:", createData); const keyId = createData.data.id; resp = await fetch(`${BASE}/keys/${keyId}`, { method: "GET", headers, }); console.log("GET:", await resp.json()); resp = await fetch(`${BASE}/keys/${keyId}`, { method: "PUT", headers, body: JSON.stringify({ name: "prod-key-v2", limit: 2000, cycle: "monthly", }), }); console.log("UPDATE:", await resp.json()); resp = await fetch(`${BASE}/keys/${keyId}/disablement`, { method: "POST", headers, }); console.log("DISABLE:", await resp.json()); resp = await fetch(`${BASE}/keys/${keyId}/enablement`, { method: "POST", headers, }); console.log("ENABLE:", await resp.json()); resp = await fetch(`${BASE}/keys/${keyId}`, { method: "DELETE", headers, }); console.log("DELETE:", await resp.json()); } main().catch(console.error); ``` ## 10. HTTP Status and Error Codes | HTTP Status | Error Code | Description | | ----------- | ---------- | -------------------------------------------------------------- | | `400` | `40001` | Invalid request parameters | | `401` | `40101` | Missing Management API Key in request header | | `401` | `40102` | Invalid, expired, or disabled Management API Key | | `403` | `40301` | Insufficient permissions or invalid key type for this endpoint | | `404` | `40401` | Target key not found or does not belong to the current account | | `429` | `42901` | Rate limit exceeded | | `500` | `50001` | Internal server error | ## 11. Standard Response Format Successful responses use the following envelope: ```json theme={null} { "code": 200, "message": "ok", "data": {} } ``` Notes: * Successful requests return HTTP `200` * Create responses may include the full secret key in `data` * List and detail endpoints usually return masked key values * Full secrets for both Management API Keys and Model API Keys are returned only once # Node Operators Source: https://docs.dgrid.ai/node-operators Why node operators are the backbone of DGrid's decentralized AI network and how they earn rewards by contributing GPU compute to model inference. Node Operators are the cornerstone of DGrid AI's mission to democratize AI infrastructure. Their participation delivers three critical advantages. ## Eliminating Centralized Control By decentralizing node ownership across a global community, DGrid AI resists censorship, corporate monopolization, or manipulation by any single entity. Unlike centralized AI platforms—where a sole provider controls access and moderation—no entity can unilaterally restrict, modify, or censor inference results, aligning with the ethos of Web3 neutrality. ## Enhancing Network Resilience A geographically diverse operator base ensures the network can withstand the following risks: * **Regional Outages**: Failures in one region are offset by nodes in other regions, preventing service disruptions. * **Regulatory Risks**: Decentralized ownership reduces vulnerability to localized policy changes or bans. * **Hardware Failures**: Redundancy across thousands of nodes eliminates single points of failure, ensuring 24/7 reliable operation for Web3 applications. ## Driving Ecosystem Development Operators' contributions extend beyond computational power—they shape the network's evolutionary trajectory: * **Feedback Loop**: Through governance mechanisms, operators report performance issues (e.g., model bottlenecks) to guide protocol upgrades. * **Incentive Alignment**: \$DGAI rewards high performance (low latency, high availability), incentivizing operators to invest in node quality improvements that directly benefit users. * **Service Diversity**: Operators can independently choose the models and Agents to host, fostering a diverse ecosystem of LLMs and Agents (ranging from open-source to specialized) to meet the varied needs of Web3 application scenarios. In summary, DGrid AI's node operator ecosystem ensures specialized roles work in synergy—DGrid Nodes execute inference, the network coordinates and verifies, and operators uphold decentralization. Together, they transform AI from a centralized service into a community-governed public utility accessible to all. # Compliance and Regulatory Source: https://docs.dgrid.ai/premium/compliance-and-regulatory Regulation S compliance, disclosures, and regulatory principles that apply to purchases of the DGrid Genesis Premium License worldwide. ## Compliance with Regulation S Obligations The sales plan for the DGrid Premium License is strictly implemented in accordance with the relevant provisions of the U.S. Regulation S. **Participation in this plan by U.S. persons is strictly prohibited**. This participation restriction will be prominently indicated on the official sales website, all promotional materials, and user interfaces. Potential participants must carefully read these compliance requirements and clearly understand that: **the DGrid Premium License may not be transferred, resold, or subject to any form of secondary circulation within twelve (12) months after the completion of the initial issuance**. Violation of this provision will be deemed a breach of compliance obligations. ## Principle of Transparent Information Disclosure All communications, marketing material production, promotional activities, and social media postings related to the sale of DGrid Premium shall be based on the core principle of openness and transparency. At the same time, **targeted marketing or sales messages to U.S. persons are strictly excluded**. In the process of releasing relevant information, all content expressions that may involve U.S. targets will be fully avoided to ensure compliance with Regulation S standards and effectively reduce regulatory risks. Meanwhile, participants shall independently verify the relevant regulatory provisions of their respective jurisdictions, assume sole responsibility for compliance review, ensure that their participation is fully in line with local legal requirements, and avoid risks arising from violations of regional regulatory provisions. # Exclusive Benefits Source: https://docs.dgrid.ai/premium/exclusive-benefits Exclusive economic, resource, governance, and ecosystem benefits available only to DGrid Genesis Members through the Premium License program. As early co-builders of the DGrid ecosystem, Genesis Members are entitled to comprehensive benefits covering economic rewards, resource access, product experience, and ecosystem co-construction. By deeply participating in network construction and governance, members can secure long-term and stable value returns. DGrid has allocated a dedicated reward pool from the total supply of \$DGAI tokens to reciprocate members' core contributions to network governance, ecosystem expansion, and AI service promotion, laying a solid foundation for the stable operation and high-quality development of the decentralized AI inference network. In addition to the core \$DGAI token rewards, Genesis Members can also enjoy diverse additional values brought by ecosystem development, including priority access to new products, discounts on AI services, and exclusive co-branding exposure. These benefits fully reflect the recognition of members' support for the ecosystem and jointly maintain the vitality and security of the DGrid ecosystem. The Genesis Premium Program opens the door for community members to deeply participate in the large-scale decentralized ecosystem of AI computing and inference services. Without requiring advanced technical capabilities or bearing high computing resource costs, anyone can easily tap into the decentralized AI economy and become a core part of the ecosystem's development. ## Detailed Breakdown of Core Benefits ### 1. Sustained Ecosystem Rewards Holding the Genesis Premium status entitles members to sustained \$DGAI ecosystem contribution rewards, as a token of appreciation for their support and participation in the early-stage network construction. Members will also automatically unlock additional airdrop rewards from ecosystem partners, sharing the long-term development dividends of the DGrid decentralized AI ecosystem. ### 2. Priority Access to High-Value AI Models & APIs From the date of joining, members can access enterprise-grade AI service resources that perfectly meet the needs of developers and advanced users: * A monthly platform credit line equivalent to \$300 * 100 free calls to selected models per day * Priority access to high-demand, large-scale AI models * Enhanced rate limits to ensure stable and uninterrupted service operation ### 3. Exclusive Governance Rights Members are granted weighted voting rights in key decision-making scenarios, including network protocol adjustments, treasury fund allocation, and model integration proposals. They can participate in closed-door governance seminars, engage in direct dialogue with the core team and other co-builders, and turn their opinions into tangible influence on the ecosystem's development. ### 4. Priority Experience of New Products & Features Members get early access to Alpha/Beta versions of new products, core infrastructure functions, and development tools. They can join the core team's closed-door feedback mechanism, provide suggestions based on their practical usage experience, contribute to product optimization and upgrades, and jointly shape product forms that align with user needs. ### 5. Priority for Ecosystem Co-Construction When applying to list AI models or launch intelligent agent services on the DGrid Marketplace, members enjoy priority review and onboarding eligibility. They also have priority selection rights for roles related to network infrastructure, such as node operation and computing resource supply, enabling them to deeply participate in the core links of ecosystem construction. # Incentive Mechanism & Rewards Source: https://docs.dgrid.ai/premium/incentive-mechanism-and-rewards How DGrid Genesis Members earn and redeem tDGAI, IOTX, and referral rewards through the Premium License incentive and rebate program. DGrid has tailored a long-term incentive system exclusively for Genesis Members, with \$DGAI tokens as the core, to achieve value alignment between members and the ecosystem, allowing early supporters to fully share the generous dividends brought by network growth. ### Core Incentives: Genesis Co-Building Rewards * **tDGAI & IOTX Token Rewards** During the period of holding Genesis Premium status, members will automatically receive continuous tDGAI & IOTX token rewards without any additional tasks. The total value of the rewards is closely tied to the activity level of the DGrid ecosystem, and will appreciate in tandem with the continuous growth of users, models, and computing tasks within the network, realizing the benefit of **"passive income simply by holding Premium"**. * **2% Referral Rebate Reward** Genesis Members are provided with exclusive referral links. After successfully inviting new users to purchase and activate Genesis Premium, the referrer will receive a 2% USDT rebate based on the new user's purchase amount. Rebates will be credited automatically, and members can view records and withdraw funds in the [Refer Friends](https://premium.dgrid.ai/referral) section of the dashboard. ### tDGAI & IOTX Reward Redemption Tutorial Genesis Members can conveniently redeem tDGAI and IOTX rewards through the DGrid Dashboard by following these steps: Log in to the official DGrid Dashboard using the wallet bound to your Genesis Pass, and complete wallet signature verification (no gas fee required). Navigate to **"My Rewards"**. The system will automatically display the redeemable amount of tDGAI and IOTX rewards. After verifying the details, click the **"Redeem"** button. Upon completion of the redemption operation, rewards will be distributed to your bound wallet. You can check the arrival status via the **"Redemption Records"** on the dashboard or your wallet explorer. tDGAI is the test version of DGAI tokens, which can be used to experience various functions on the DGrid test network. IOTX rewards are ecosystem synergy rewards, and can only be redeemed if your Genesis Premium status remains active. # Legal Disclaimer Source: https://docs.dgrid.ai/premium/legal-disclaimer Important legal disclaimer, risk warnings, and liability terms that govern participation in the DGrid Genesis Premium License program. This page applies to DGrid Premium only and does not govern AI Gateway or other DGrid services. Please read all terms of this "Legal Disclaimer" carefully. This disclaimer does not constitute formal legal, financial, commercial, or tax advice. You must consult your own legal, financial, tax, or other professional advisors before participating in any related activities. The DGrid Foundation (hereinafter referred to as the "Foundation"), all contributors involved in the development of the DGrid Decentralized Artificial Intelligence Inference Network (hereinafter referred to as the "DGrid Network"), the issuer/supplier of the DGrid Premium License (hereinafter referred to as the "Issuer"), and relevant service providers shall not be liable for any direct or indirect losses you may suffer from accessing the DGrid Premium License-related documents (hereinafter referred to as the "DGrid Premium Documents"), other relevant websites, or public information published by the Foundation or its authorized representatives from time to time on the designated website (URL: [https://premium.dgrid.ai/dgridpass](https://premium.dgrid.ai/dgridpass), including its subdomains). ## Eligibility and Restrictions ### Age Requirement To use this website (including all services provided thereon) or participate in the DGrid Premium License issuance plan, you must be at least eighteen (18) years old and have full capacity for civil conduct. ### Regional Restrictions This website, interface, and related services are **strictly prohibited** from being open to individuals or entities in "Restricted Regions". Restricted Regions include: Belarus, Canada, Cuba, North Korea, China, Iran, Russia, Syria, the United States, the United Kingdom, Venezuela, Yemen, and specific regions within Ukraine and Russia (including the Crimean region, Donetsk People's Republic (DNR), Luhansk People's Republic (LNR), Kherson Oblast, and Zaporizhzhia Oblast). Any individual or entity belonging to Restricted Regions (hereinafter referred to as "Restricted Persons") shall not attempt to access or use this website; any act of Restricted Persons accessing or using this website, interface, or services through Virtual Private Networks (VPN) or other means of circumventing restrictions shall be deemed a prohibited act in violation of this disclaimer. ## Core Purpose of the Project You confirm and agree that the sole purpose of obtaining the DGrid Premium License is to participate in the operation of the DGrid Network and enjoy the right to use corresponding services in its ecosystem. The Foundation, the Issuer, and their respective affiliated entities shall be responsible for the development, maintenance, and optimization of the underlying source code of the DGrid Network. It should be specifically noted that in the process of issuing the DGrid Premium License, the Foundation only performs relevant duties as an independent third party, and shall never act as a financial advisor or fiduciary for any participant, nor shall it be liable for providing advice on any decisions of participants. ## Legal Effect of the Website and Documents All contents of this website and the DGrid Premium Documents are for informational purposes only and do not constitute an offer for sale of the DGrid Premium License by the Foundation, the Issuer, or the DGrid Team. No part thereof or any facts presented therein may be relied upon as a basis for you to enter into a contract with any party or make a purchase decision. At the same time, no content on this website or in the DGrid Premium Documents may be construed as a commitment, statement, or guarantee regarding the future operational performance or development prospects of the DGrid Network. Any agreement reached between you and the Issuer (or any third party) regarding the issuance or transfer of the DGrid Premium License shall be solely governed by the exclusive terms and conditions of that separate agreement and shall have no connection with this disclaimer. ## Your Representation and Warranty Obligations Once you access this website or the DGrid Premium Documents (or any part thereof), you are deemed to have made the following irrevocable representations and warranties to the Foundation, the Issuer, their respective affiliates, and the DGrid Team: ### Warranty of Independent Decision-Making In deciding whether to obtain the DGrid Premium License, you act based on your own independent judgment and investigation, and have not relied and will not rely on any statements, information, or contents on this website or in the DGrid Premium Documents. ### Assumption of Compliance Obligations You shall bear all costs and responsibilities to ensure that your actions (including but not limited to obtaining, holding, and using the DGrid Premium License) fully comply with the laws, regulations, regulatory requirements, and relevant restrictions of your jurisdiction. ### Recognition and Acceptance of Risks You have fully understood and confirmed that the DGrid Premium License has no inherent value or predetermined pricing, and the Foundation, the Issuer, and relevant entities have never guaranteed its market value or liquidity; the DGrid Premium License is not an investment product and is not intended for any investment (including speculative) purposes, and you are willing to bear all risks associated therewith. ### Confirmation of Disclaimer The Foundation, the Issuer, their respective affiliates, and the DGrid Team shall not be liable for or make any commitments regarding the market value, transferability, liquidity of the DGrid Premium License, or whether a third party will establish a relevant trading market. In addition, the Foundation, the Issuer, and the DGrid Team have not made and do not claim to make any representations, warranties, or commitments related to this website, the DGrid Premium Documents, or other public information (including but not limited to warranties regarding the accuracy, completeness, timeliness, or reliability of the contents), and hereby explicitly disclaim all relevant legal liabilities. To the maximum extent permitted by law, the Foundation, the Issuer, their respective affiliates, and service providers shall not be liable for any indirect, special, incidental, consequential, or other forms of losses (including but not limited to liabilities arising from negligence or breach of contract, loss of income or profits, loss of right to use, or data loss) arising from the use of this website, the DGrid Premium Documents, or other relevant materials (including but not limited to errors or omissions in the contents). All persons intending to obtain the DGrid Premium License shall carefully evaluate all risks and uncertainties (including financial, legal, and market risks) related to the issuance of this license, the Foundation, the Issuer, and the DGrid Team before deciding whether to participate. ## Core Attributes of the DGrid Premium License The DGrid Premium License is designed to serve participants of the DGrid Network, which is also the core objective of its issuance. You confirm and agree that the DGrid Premium License has the following attributes: 1. It has no physical form, no inherent value or agreed pricing, and no individual or institution has made any statements or commitments regarding its market value; 2. Once issued, it is non-refundable and cannot be exchanged for any physical or digital assets, cash (or the equivalent value of other digital assets) from the Foundation, the Issuer, or their respective affiliates, nor can any payment claim be asserted; 3. It does not represent or confer upon the holder any form of rights to the Foundation, the Issuer (or their respective affiliates) or their income or assets, including but not limited to the right to receive dividends, bonuses, or shares, ownership rights, voting rights, distribution rights, redemption rights, liquidation rights, intellectual property rights or license rights, the right to inspect financial statements, the right to participate in shareholder meetings or nominate directors, and any other financial, legal, or participatory rights related to the DGrid Network, the Foundation, the Issuer, and/or their service providers; 4. It is not a right certificate under a swap contract or other contracts for the purpose of profiting or avoiding losses; 5. It does not constitute currency (including electronic currency), payment instruments, securities, commodities, bonds, debt instruments, units of collective investment schemes, managed investment schemes, or any other financial instruments or investment products; 6. It is not a loan to the Foundation, the Issuer, or their respective affiliates, does not represent any creditor-debtor relationship, and the holder has no right to require any profit distribution or interest payment; 7. It does not confer upon the holder any ownership or other proprietary interests in the Foundation, the Issuer, or their respective affiliates. It should be particularly emphasized that even after the issuance of the DGrid Premium License, the user shall not have any economic or legal rights or beneficial interests in any assets of the Foundation, the Issuer, or their respective affiliates after issuance. If any secondary market or exchange for trading the DGrid Premium License emerges in the future, its operation and management shall have no connection with the Foundation, the Issuer, or the issuance of the DGrid Premium License; neither the Foundation nor the Issuer shall be obligated to establish such a secondary market, nor shall they act as a trading platform for the DGrid Premium License in any form. ## Agreement on Language Effectiveness This website and the DGrid Premium Documents may be available in non-English translated versions, but such translations are for reference only; in case of any conflict or ambiguity between the original English text and the translated versions, the original English text shall prevail. You confirm that you have read and fully understood the original English content of this website and the DGrid Premium Documents and agree to be bound thereby. ## Prohibition of Unauthorized Distribution Without the prior written consent of the Foundation or the Issuer, no one may copy, reproduce, distribute, disseminate, or reprint any content of this website or the DGrid Premium Documents. If you participate in any briefing related to the DGrid Premium Documents or receive paper or electronic copies thereof, you agree to be bound by the aforementioned restrictions; if you violate them, you shall bear corresponding legal responsibilities. # Program Overview Source: https://docs.dgrid.ai/premium/program-overview What the DGrid Genesis Premium License is, why early participants should join, and the benefits unlocked by becoming a Genesis Member. ## What is DGrid Genesis Premium? DGrid Genesis Premium serves as the core credential of the DGrid decentralized AI ecosystem and a symbolic identity for early participants to deeply bind with the network. Upon subscribing to the Genesis Premium service, users will receive the Genesis Pass NFT as their exclusive identity credential. Unlike the benefits of regular Premiums, holders of this NFT can not only directly access high-value AI resource usage rights, but also deeply participate in network development decision-making and share the dividends of ecological growth. To maintain the long-term stable operation and ecological expansion of the network, Genesis Members only need to retain their Premium status and actively participate in ecological construction to obtain stable economic returns. For long-term holders who support the ecosystem, there will be further opportunities to claim additional ecological rewards. This Genesis Premium Program features a specially designed low-threshold and equalized participation mechanism, enabling community members from diverse backgrounds to seize the early opportunities in the development of decentralized AI. ## Why Join the Genesis Premium? At the critical stage of the rise of the decentralized AI economy, becoming a DGrid Genesis Member means transforming from a "spectator" to a "co-builder". While bringing diverse values to the ecosystem, you can achieve a win-win situation for both individuals and the network: * Consolidate the decentralized foundation: Help the network maintain its decentralized architecture, enhance its resistance to external risks, and ensure the long-term stability of the ecosystem. * Drive ecological scale expansion: Facilitate the expansion of the decentralized AI inference network through participation in model deployment, infrastructure operation and other tasks. * Popularize high-quality AI services: Support network operations through practical participation, enabling more users and developers to access high-quality AI resources at low costs. * Claim generous rewards: Earn \$DGAI tokens and other exclusive rewards based on contributions to the ecosystem, and share the dividends of network growth. # Purchase & Activation Source: https://docs.dgrid.ai/premium/purchase-and-activation Step-by-step instructions for buying the DGrid Genesis Pass and activating the Premium License to unlock Genesis Member benefits and rewards. To enable more community members to participate conveniently, DGrid has simplified the Genesis Premium purchase and activation process. Follow the steps below to complete your purchase and activate your exclusive benefits: ### Step 1: Purchase the DGrid Genesis Pass 1. **Visit the official minting page**: Open your browser and enter the URL [https://premium.dgrid.ai/dgridpass?code=LXX9BB](https://premium.dgrid.ai/dgridpass?code=LXX9BB) to access the Genesis Pass purchase page. 2. **Connect your wallet**: Click the "Connect Wallet" button on the page, select a wallet that supports the BNB Smart Chain (e.g., MetaMask, Token Pocket, Binance Wallet, OKX Wallet), and complete wallet connection and transaction authorization. 3. Select the number of Genesis Passes you wish to purchase. After verifying that the order details are correct, complete the payment using USDT. 4. Read and agree to the DGrid Genesis Pass Purchase Agreement. 5. Enter your invitation code and finalize the purchase to successfully obtain the DGrid Genesis Pass (NFT credential). ### Step 2: Activate Genesis Premium Benefits 1. After holding the Genesis Pass NFT, log in to the DGrid Dashboard and locate the **"Activate Genesis Premium Benefits"** button. 2. Follow the on-screen prompts to complete activation. You will then unlock all exclusive Genesis Premium benefits and immediately start earning dual rewards of \$DGAI & \$IOTX. ### Step 3: Monitor Rewards & Benefit Usage 1. Through the DGrid Dashboard, view the real-time accumulation of your \$DGAI and \$IOTX rewards. 2. The Dashboard enables transparent management of your personal assets, including functions for reward withdrawal and benefit usage statistics, allowing you to track your benefit status at any time. The DGrid Genesis Premium Program was officially launched at **00:00 UTC on January 1, 2026**. We recommend completing the purchase and activation process in advance to ensure you can enjoy all benefits immediately. # Quickstart Source: https://docs.dgrid.ai/quickstart Get started with DGrid in under five minutes — create an account, generate an API key, and make your first call to a model through the AI Gateway. DGrid is the decentralized smart network for AI — a single ecosystem that spans model access, model discovery, evaluation, and on-chain incentives. Whichever product you start with, every part of DGrid is reachable through one API key. ## Explore the DGrid ecosystem One OpenAI-, Claude-, and Gemini-compatible API for 200+ leading AI models, with Web3-native payments and intelligent routing. Blind model battles where community votes earn \$DGAI airdrop points and feed DGrid's routing intelligence. A natural-language advisor that turns your requirements into a shortlist of models, tested and compared for you. The open catalog of 200+ models and providers behind DGrid AI Gateway, browsable and callable through one API. ## Get started with DGrid AI Gateway DGrid AI Gateway gives you a single, OpenAI-compatible API for 200+ leading models. This section takes you from zero to your first chat completion. Obtain a valid `DGRID_API_KEY` by following the [key creation guide](https://blog.dgrid.ai/posts/2026-01-04/). Your key secret is shown only once at creation time. Copy it immediately and store it in a secure location such as a secrets manager. Never expose it in client-side code or public repositories. Send a chat completion request to the DGrid AI Gateway endpoint. The `model` parameter uses the `provider/model-name` format (for example `openai/gpt-4o`), consistent across all DGrid-supported models. ```bash cURL theme={null} curl https://api.dgrid.ai/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $DGRID_API_KEY" \ -d '{ "model": "openai/gpt-4o", "messages": [ { "role": "user", "content": "What is the meaning of life?" } ] }' ``` ```python Python theme={null} from openai import OpenAI client = OpenAI( base_url="https://api.dgrid.ai/v1", api_key="", ) completion = client.chat.completions.create( model="openai/gpt-4o", messages=[ { "role": "user", "content": "What is the meaning of life?" } ] ) print(completion.choices[0].message.content) ``` ```typescript TypeScript theme={null} import OpenAI from 'openai'; const openai = new OpenAI({ baseURL: 'https://api.dgrid.ai/v1', apiKey: '', }); const completion = await openai.chat.completions.create({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }); console.log(completion.choices[0].message.content); ``` DGrid is fully compatible with the OpenAI SDK — point `baseURL` at `https://api.dgrid.ai/v1` and your existing code works unchanged. Install it with `pip install openai` or `npm install openai`. Endpoint-level reference for chat, images, audio, embeddings, and more. Connect DGrid to Claude Code, Cursor, Moltbot, and other tools. Pay per inference with the x402 protocol — no account balance required. # Roadmap Source: https://docs.dgrid.ai/roadmap DGrid AI development roadmap covering mainnet launch, decentralized inference milestones, $DGAI token unlocks, and ecosystem product releases. ## 2025 Q1-Q2: Infrastructure Construction Phase * Design of network architecture and economic model * Development of DGrid AI Gateway * Design and implementation of the PoS Quality Proof algorithm * Development of premium presale module ## 2025 Q3-Q4: Testnet Phase * Launch of official website and whitepaper * Completion of seed round financing * Launch of premium membership presale ## 2026 Q1-Q2: Mainnet Launch & Expansion Phase * Release of DGrid AI Gateway and integration of enterprise-grade mainstream models * Launch of premium rewards and incentive pool * Launch of AI Arena * Integration of x402 Protocol, multi-chain payment integration, and DGrid AI Gateway access to multi-chain ecosystems * Introduction of DGrid ecosystem projects to drive the network into a period of scalable growth ## 2026 Q3-Q4: Governance Improvement & Ecosystem Expansion Phase * Launch of Agent launchpad * Activation of on-chain governance and voting system, establishment of AI DAO 1.0 * Launch of Model & Agent Market and DGrid Scan # Token Distribution Source: https://docs.dgrid.ai/token-distribution How the fixed 1 billion $DGAI supply is allocated across nodes, community, team, investors, airdrops, and initial liquidity, including lockups and release schedules. The total supply of \$DGAI is fixed at 1 billion tokens. The allocation prioritizes long-term network development, while lockups and linear release schedules keep the team and early backers aligned through the network's critical growth phase. Detailed $DGAI token allocation chart ## Allocation breakdown * **Nodes: 50% (500,000,000 \$DGAI).** Reserved for node operators and infrastructure providers. Tokens are released linearly over 10 years, with emissions halving every 2 years. * **Community: 15% (150,000,000 \$DGAI).** Supports ecosystem growth, campaigns, contributor programs, and user incentives. A 6-month lock is followed by a 2-year linear release. * **Team Incentives: 10% (100,000,000 \$DGAI).** Allocated to core contributors. A 1-year lock is followed by a 2-year linear release. * **Investors: 10% (100,000,000 \$DGAI).** Allocated to seed-round backers. A 1-year lock is followed by a 2-year linear release. * **Airdrops: 8% (80,000,000 \$DGAI).** Distributed to early ecosystem participants, community contributors, and exchange campaign participants who supported DGrid before the Token Generation Event (TGE). Fully unlocked at TGE. * **Initial Liquidity: 7% (70,000,000 \$DGAI).** Supports market liquidity at launch. Fully unlocked at TGE. This distribution assigns the largest share to network participation, with 50% reserved for nodes and infrastructure incentives. Community and airdrop allocations reward active participation, while team and investor allocations support long-term development alignment. # What is $DGAI? Source: https://docs.dgrid.ai/what-is-dgai $DGAI is the native utility token of DGrid AI, used for staking, paying for inference, governance voting, and distributing network rewards. **\$DGAI** is the native utility token of the DGrid AI ecosystem, serving as the backbone of value exchange, incentive alignment, and network governance in our decentralized AI inference network. Designed to operate seamlessly within Web3 infrastructure, it enables trustless interactions between users, node operators, and developers—eliminating reliance on intermediaries. ## Technical Specifications * **Standard**: BEP-20 token, compatible with BNBChain and all EVM-compatible blockchains, ensuring broad interoperability with wallets, exchanges, and smart contracts. * **Contract Addresses**: * **BNB Smart Chain (BSC)**: [`0x10D4183389e99233db3cc981c43443Ebd28Ebd5e`](https://bscscan.com/token/0x10D4183389e99233db3cc981c43443Ebd28Ebd5e) * **Arbitrum One (ARB)**: [`0x12C2dE43878FB1A06C1Ead481f11E0C693a719c7`](https://arbiscan.io/token/0x12C2dE43878FB1A06C1Ead481f11E0C693a719c7) * **Total Supply**: Fixed at **1 billion** tokens, with no inflationary minting post-launch. This scarcity ensures long-term value stability and aligns incentives with network growth. * **Key Extensions**: Integrates EIP-2612 (permit) for gasless approvals, simplifying payment flows for inference tasks and staking operations # What We Do Source: https://docs.dgrid.ai/what-we-do DGrid's mission to build a trusted, decentralized AI network that efficiently connects model providers with users and developers worldwide. With the core mission of **"building a trusted, efficient AI network connecting supply and demand"**, DGrid addresses the industry pain points of market fragmentation and centralized control. We break down the fragmentation and value mismatch in the AI ecosystem, providing a one-stop solution for both Web3 and traditional AI sectors. Adhering to the core principle that **"AI should serve the open web"**, we are committed to enabling high-quality AI capabilities (including LLMs and AI Agents) to achieve efficient flow, fair distribution, and trusted verification through technological innovation and ecosystem collaboration. To tackle the core challenges—such as the explosion of model supply alongside fragmented interfaces, high integration costs for developers, value monopolization of creators, and non-auditable inference results—DGrid has built a three-tier architecture: **"Decentralized Routing & Verification Network + LLM & Agent Free Market + AI DAO"**, which connects the entire chain from AI capability supply to demand matching: * Through a unified API and intelligent routing, we resolve interface fragmentation. Developers can access thousands of models and Agents without redundant development, significantly lowering integration barriers. * We build a trusted inference environment using the **Proof of Quality (PoQ)** algorithm, enabling verifiability and traceability of AI execution processes and output results, and bridging the trust gap in Web3 AI. * We establish an open LLM & Agent free market, allowing creators such as model providers and prompt engineers to set their own prices and profit directly from global users, breaking platform monopolies. * Via a distributed node network and elastic scheduling mechanism, we address the high costs, single points of failure, and censorship risks of centralized AI, while providing a merit-based incentive system for node operators. Ultimately, DGrid aims to become the **"value hub"** of the AI and Web3 ecosystems. We not only deliver cost-effective, verifiable, high-quality AI services to users but also build a fair and win-win collaboration platform for ecosystem participants, advancing AI from **"centralized services"** to a **"foundational public utility of the open web"**. ## Core Values * **Decentralization**: AI belongs to the open web, not centralized platforms, ensuring equal participation of all ecosystem stakeholders. * **Accessibility**: Anyone can join as a node operator, developer, creator, or user, with low barriers to entry. * **Trustlessness**: Based on on-chain permission and auditing mechanisms, services are verifiable and traceable without relying on third-party trust. * **Scalability**: Modular design enables flexible model deployment, inference, and caching, adapting to diverse scenario requirements. * **Value Discoverability**: Intelligent routing makes inference resources "routable, verifiable, and comparable in price", enabling efficient allocation of intelligent liquidity. # API Reference Source: https://docs.dgrid.ai/x402/api-reference Endpoint reference for DGrid's x402 API, including request format, payment headers, response codes, and pay-per-inference billing details. This page documents the x402-specific endpoint details for DGrid pay-per-inference requests. If you are looking for provider-style request patterns such as **OpenAI-compatible** or **Claude-compatible** payloads, see [Model API](/api-reference/introduction). Those references remain the best source for provider-specific invocation examples. This page focuses on the x402 payment flow plus the shared inference fields exposed at the x402 endpoint. ## x402 AI Inference API Call DGrid inference with x402 payment requirements. The first request returns payment instructions; the second request includes a signed x-payment header and executes inference. ```http theme={null} POST /x402/v1 ``` | | | | ----------------- | ------------------------------------------------------------------- | | **Base URL** | `https://api.dgrid.ai` | | **Authorization** | `Content-Type: application/json; x-payment: ` | | **Request** | `application/json` | | **Response** | `402 / 200 · application/json or text/event-stream` | ### Payment and Authentication This endpoint uses the **x402 payment protocol** instead of an account balance workflow. Required request headers for the paid request: ```http theme={null} Content-Type: application/json x-payment: ``` ### Request Body | Field | Type | Required | Default | Description | | ------------- | ------- | -------- | --------------------------- | -------------------------------------------------- | | `messages` | array | Yes | - | `UIMessage` array containing `role` and `content`. | | `model` | string | No | `anthropic/claude-opus-4.5` | Target model name. | | `stream` | boolean | No | `true` | Whether to return a streaming response. | | `temperature` | number | No | `1` | Sampling temperature. | | `topP` | number | No | `1` | Top-p sampling parameter. | | `topK` | number | No | `40` | Top-k sampling parameter. | ### Response Modes #### `stream = true` (default) Returns **UIMessageStream** SSE (`text/event-stream`) using AI SDK style `UIMessageChunk` events. Common event types include: * `start` * `text-start` * `text-delta` * `text-end` * `finish` The final `finish` event includes `messageMetadata` such as: * `totalTokens` * `allowanceLeft` * `calculatedPriceWei` * `realPriceWei` #### `stream = false` Returns a single JSON response in DGrid's standard completion format with `choices` and `usage`. ### Errors | Status | Meaning | | ------ | --------------------------------------------------------------------------------------------------------------------- | | `402` | Payment validation failed, usually because the first request omitted `x-payment` or the payment signature was invalid | | `400` | Invalid request or upstream validation error | | `500` | Server-side or upstream provider error | ### Settlement Notes * The endpoint settles based on actual usage. * If actual cost exceeds the authorized upper bound, settlement is capped at that authorized limit. ```bash Step 1: Trigger 402 theme={null} curl -i 'https://api.dgrid.ai/x402/v1/responses' \ -H 'Content-Type: application/json' \ --data-raw '{ "model": "anthropic/claude-opus-4.5", "stream": true, "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```bash Step 2: Retry with x-payment theme={null} curl -i 'https://api.dgrid.ai/x402/v1' \ -H 'Content-Type: application/json' \ -H 'x-payment: ' \ --data-raw '{ "model": "anthropic/claude-opus-4.5", "stream": true, "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```http 402 Response theme={null} HTTP/1.1 402 Payment Required Content-Type: application/json X-PAYMENT-RESPONSE: { "x402Version": 1, "error": "Payment required", "accepts": [ { "scheme": "upto", "network": "eip155:56", "maxAmountRequired": "990000000000000000", "resource": "https://api.dgrid.ai/x402/v1", "payTo": "0x...", "asset": "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d", "maxTimeoutSeconds": 86400 } ] } ``` ```text Streaming Response theme={null} data: {"type":"start"} data: {"type":"text-start","id":"..."} data: {"type":"text-delta","id":"...","delta":"Hello"} data: {"type":"text-end","id":"..."} data: {"type":"finish","finishReason":"stop","messageMetadata":{"totalTokens":123,"allowanceLeft":"990000000000000000","calculatedPriceWei":"1230000000000000","realPriceWei":"1230000000000000"}} ``` ```json Non-Streaming Response theme={null} { "id": "chatcmpl-xxxx", "object": "chat.completion", "created": 1773823863, "model": "grok-4-fast", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "xxxxx" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 11, "completion_tokens": 323, "total_tokens": 334 } } ``` # x402 API Source: https://docs.dgrid.ai/x402/overview DGrid's x402 API lets developers pay per inference call using the x402 micropayment protocol — no API keys or accounts required. **DGrid x402 API** is DGrid's pay-per-inference access mode for api payments. Instead of creating an account, pre-funding a balance, or managing separate billing flows, developers and autonomous agents can pay LLM inference costs directly through the **x402 payment protocol** as part of the API request lifecycle. This makes x402 especially useful for: * **Agents and autonomous workflows** that need to call an LLM and settle payment immediately * **Server-side tools and scripts** that should avoid account provisioning and manual top-ups * **On-demand integrations** where the simplest path is "request inference, authorize payment, receive the result" ## Why x402 API Matters Traditional AI billing usually requires: * Creating an account with the provider * Funding a prepaid balance or attaching a billing method * Managing API keys, quotas, and billing dashboards With x402 on DGrid, the flow becomes much more direct: Request inference → receive payment requirements → sign once → submit payment and inference together For agentic systems, this is a major simplification. The same runtime that decides to use a model can also authorize and settle the cost of that inference call, without switching into a separate account-management workflow. ## Primary Use Case: Agents Paying for Inference x402 is designed for the case where an **agent** needs to: 1. Choose a model 2. Call the model API 3. Pay the inference fee 4. Continue execution with the result This is valuable for: * AI agents operating in backend workflows * Web3 agents or protocols that want payment-aware inference * Multi-step automations that should treat inference as a directly payable resource ## How the Flow Works x402 on DGrid uses a **two-step request flow**: 1. **Initial request without `x-payment`** The server returns `402 Payment Required` plus signable payment requirements. 2. **Client signs and retries** The client generates the `x-payment` payload and sends the same inference request again with the payment header. This pattern keeps payment authorization explicit while still letting the inference call remain simple and automatable. ## Supported Payment Asset The current x402 endpoint uses: * **Protocol**: x402 * **Network**: `eip155:56` (BSC) * **Payment token**: `USD1` * **Asset contract**: `0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d` ## Operational Notes After successful settlement, the service records payment logs into the `x402_payment_logs` table on the backend. ## When to Use x402 vs AI Gateway Use **AI Gateway** when you want: * classic API-key access * unified account-based model routing * long-running product integrations with standard billing workflows Use **x402** when you want: * direct per-request payment * no pre-funded account balance * agent-friendly inference plus payment in one flow