# Dhee AI — Complete Developer & Architecture Documentation

> Adaptive AI Orchestration Layer — Dynamic composition of verified Skills, Tools, Virtual Models, and multi-provider execution through one unified API.

---

## 1. Overview & Architecture

Dhee AI is not a prompt template gateway, model router, or raw LLM wrapper. It is an **Adaptive AI Orchestration Layer**.

When an instruction is sent to Dhee through `https://ai.dheelab.com/v1`, the orchestration engine executes a deterministic 6-stage lifecycle:

1. **Intent Deconstruction**: Analyzes developer prompts to extract business requirements, required domain competencies, output schemas, and latency/cost constraints.
2. **Skill Composition**: Automatically selects and chains verified expert domain workflows (e.g., Financial Anomaly Detection, SEO Content Architecture, Code Review & Refactoring).
3. **Tool Binding**: Connects real-time tools (SERP indexes, HTTP scrapers, arithmetic sandboxes, code interpreters) required by active skills under strict egress policies.
4. **Virtual Model Selection**: Selects or accepts a Dheeman virtual model endpoint (e.g., `dheeman-auto`, `dheeman-pro`, `dheeman-flash`, `dheeman-reasoning`, `dheeman-coding`).
5. **Multi-Provider Resilience**: Dispatches the assembled request across healthy upstream providers (AWS Bedrock, Azure OpenAI, GCP Vertex AI, Anthropic) with automated failover on rate limits (429) or upstream degradation (5xx).
6. **Output Verification**: Performs schema conformity validation, citation integrity audits, and constraint verification before returning the final response.

---

## 2. Drop-in OpenAI Compatibility

Dhee AI provides drop-in OpenAI SDK compatibility for Chat Completions. Existing applications require only two configuration changes: updating the `baseURL` to `https://ai.dheelab.com/v1` and supplying a Dhee API key.

### Base URLs
- **Production Endpoint**: `https://ai.dheelab.com/v1`
- **Chat Completions**: `POST https://ai.dheelab.com/v1/chat/completions`
- **Models Directory**: `GET https://ai.dheelab.com/v1/models`

### Python Example
```python
from openai import OpenAI

client = OpenAI(
    base_url="https://ai.dheelab.com/v1",
    api_key="dhee_live_your_api_key_here",
)

response = client.chat.completions.create(
    model="dheeman-auto",
    messages=[
        {"role": "system", "content": "You are an expert technical advisor."},
        {"role": "user", "content": "Analyze our quarterly cash flow statement for liquidity risks."}
    ],
    temperature=0.2,
)

print(response.choices[0].message.content)
```

### TypeScript / Node.js Example
```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://ai.dheelab.com/v1',
  apiKey: process.env.DHEE_API_KEY,
});

async function main() {
  const completion = await client.chat.completions.create({
    model: 'dheeman-auto',
    messages: [
      { role: 'user', content: 'Generate a validated TypeScript schema for SaaS billing subscriptions.' }
    ],
  });

  console.log(completion.choices[0].message.content);
}

main();
```

### cURL Example
```bash
curl https://ai.dheelab.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer dhee_live_your_api_key_here" \
  -d '{
    "model": "dheeman-auto",
    "messages": [
      {"role": "user", "content": "Perform a competitive positioning analysis of our cloud infrastructure."}
    ],
    "temperature": 0.3
  }'
```

---

## 3. Authentication & API Key Governance

All API requests require authentication via an HTTP `Authorization` header containing a Bearer token.

```http
Authorization: Bearer dhee_live_xxxxxxxxxxxxxxxxxxxxxxxx
```

### Key Formats
- **Live Keys**: `dh_live_` followed by a generated secret — active project keys for production inference.
- **Test Keys**: `dh_test_` followed by a generated secret — project keys for sandbox testing.

### Security Best Practices
- **Project Isolation**: Issue unique API keys per microservice, environment (staging vs. production), or team.
- **IP Allowlists**: Restrict sensitive API keys to specific static server egress CIDR blocks.
- **Model Restrictions**: Scope keys to specific Dheeman models (e.g., restrict a customer-facing bot key exclusively to `dheeman-flash`).
- **Hard Spend Caps**: Configure dollar-based budget ceilings per key or project to prevent runaway billing.

---

## 4. Dheeman Auto Meta-Router

`dheeman-auto` is Dhee’s virtual-model meta-router for chat completions. It does not start a Dheeman Agent run or install a skill. Instead of requiring developers to manually pick models for varying user inputs, `dheeman-auto`:

1. Evaluates token count, reasoning depth, code requirements, and domain complexity deterministically using zero-overhead heuristic classification.
2. Dynamically routes simple extraction or classification tasks to `dheeman-flash` for ultra-low latency and minimal cost.
3. Automatically promotes multi-step reasoning, mathematical calculations, and deep synthesis to `dheeman-pro` or `dheeman-reasoning`.
4. Selects a serving family for the request; use the dedicated Agent Runs API when you need eligible-skill selection, conversation memory, or tool orchestration.
5. Emits `x-dheeman-routed-model` and `x-dheeman-routed-tier` response headers detailing routing decisions.

---

## 4A. Dheeman Agent: Multi-Step Tasks

Dheeman Agent is a task workflow, not a standalone chat-completions model. Use `POST /v1/dheeman-agent/runs` for work that benefits from multiple model steps, an eligible published skill, project-scoped conversation context, or tools that may need human approval. The Agent runtime uses `dheeman-auto` to route its model steps. For a simple single answer, call `POST /v1/chat/completions` with `model: "dheeman-auto"` instead.

```http
POST /v1/dheeman-agent/runs
Authorization: Bearer dh_live_YOUR_PROJECT_KEY
Content-Type: application/json
Idempotency-Key: agent-task-001

{"task":"Review my website SEO and suggest three fixes.","input":{},"pipeline":"auto","execution_mode":"auto"}
```

`task` is required. `input`, `skill`, `conversation_id`, `entity`, `pipeline`, and `execution_mode` are optional. Omit `skill` for automatic selection among eligible published skills; provide a slug to pin one. The response includes `data.run_id`, `data.conversation_id`, `data.status`, `data.output`, `data.steps`, and aggregate `data.usage`. Pass the returned `conversation_id` in a later task to continue the same project conversation. For an asynchronous run, poll `GET /v1/dheeman-agent/runs/{run_id}`. Protected tool calls pause in `waiting_approval`; an authorized key with `agents.approve` can approve or reject a specific call at `POST /v1/dheeman-agent/runs/{run_id}/tools/{call_id}/approve` or `/reject`. A proposal is not a completed action. See [the crawlable Agent guide](https://ai.dheelab.com/docs/agent).

### Brain pipeline for image-grounded answers

Send a JPEG, PNG, or WebP data URL in `input.image_url` and leave `pipeline` as `auto`; this selects `brain`. You can also set `pipeline: "brain"` explicitly for text-only verification. Brain plans the task, extracts visual observations when an image is present, drafts an answer, and checks that answer against the request and evidence. If the check fails, it makes at most one repair attempt with another text model and checks again. A second failure does not produce a successful answer. Each model call is metered separately; Brain defaults to asynchronous execution, so poll the returned `run_id`.

```http
POST /v1/dheeman-agent/runs
Authorization: Bearer dh_live_YOUR_PROJECT_KEY
Content-Type: application/json

{"task":"Describe only visible product features. Do not guess the material.","input":{"image_url":"data:image/jpeg;base64,BASE64_IMAGE"},"pipeline":"auto","execution_mode":"auto"}
```

Replace `BASE64_IMAGE` with actual base64-encoded JPEG bytes, not a file path or remote URL. Brain does not currently execute skill tools or approval-gated actions; use the standard Agent pipeline for those. PDF and audio input are not supported by this endpoint yet and are rejected instead of silently processed as text. The final Agent output is an `answer` string, not an arbitrary product schema.

---

## 5. Skills & Capabilities System

Dhee decouples domain knowledge from foundation models using **Verified Skills**.

A Skill is an auditable, versioned specification defining:
- Step-by-step cognitive procedures for specialized disciplines.
- Expected input arguments, validation schemas, and constraints.
- Sandboxed tool dependencies (e.g., web search, arithmetic interpreters).

### Example Skill Categories
- **Marketing & Growth**: Market Research, Competitor Profiling, Audience Persona Modeling, SEO Content Architecture, Conversion Copywriting.
- **Engineering & Software**: Full-Stack Architecture, Code Review & Linting, SQL Query Optimization, Vulnerability Auditing, API Design.
- **Finance & Accounting**: Financial Anomaly Detection, Balance Sheet Audit, Cash Flow Modeling, Tax Deduction Compliance.
- **Operations & Legal**: Vendor Contract Review, Customer Support Ticket Triage, SLA Breach Detection, Regulatory Compliance Check.

### Using skills as a customer

For an automatically selected skill, send a plain-language task to `POST /v1/dheeman-agent/runs`. The `skill` field is optional. This endpoint may prepare a missing skill only when its exact slug is allowlisted on a trusted source. It does not install a separate copy for each customer. `GET /v1/skills` lists skills already published and entitled to the calling project; it does not list pending external candidates.

```http
POST /v1/dheeman-agent/runs
Authorization: Bearer dh_live_YOUR_PROJECT_KEY
Content-Type: application/json
Idempotency-Key: agent-task-001

{"task":"Review my website SEO and suggest the three most important fixes.","input":{}}
```

If a matching eligible skill is not yet ready, the response is HTTP 202 with `success: true` and `data.status: "skill_pending"`. `data.reason` can be `discovering`, `preparing`, or `review_required`; `data.retry_after_seconds` is currently 10. No agent run has started, and there is no `run_id` in this response. For `discovering` or `preparing`, wait at least the suggested interval, then repeat the task with a **new** `Idempotency-Key`. Reusing the previous key replays its cached pending response. Stop retrying when a `run_id` appears; asynchronous agent runs can also return HTTP 202, so inspect `data.status` rather than HTTP status alone. For `review_required`, contact an administrator instead of retrying automatically.

Only clean, text-only, tool-free first versions with passed verification and a known commercially usable license may auto-publish. Other packages need human review. Existing published versions are not overwritten. Project entitlements remain in force after publication. The on-demand preparation path does **not** run through `POST /v1/skills/{slug}/run` or `POST /v1/chat/completions`. See `/docs/skills` for the illustrated customer guide.

---

## 6. Tools Runtime & Egress Boundaries

Tools allow active skills to fetch fresh, grounded real-world data during inference.

### Tool Safety Architecture
- **Egress Isolation**: Tools execute within isolated sandboxes. Outbound network requests are limited to explicit whitelisted domains.
- **Execution Limits**: Hard timeouts (maximum 8 seconds per tool call) prevent hung connections.
- **Deterministic Schemas**: All tool inputs and outputs must pass strict JSON Schema validation before being passed back to the model context.

---

## 7. Chat Completions API Specification

### Endpoint
`POST https://ai.dheelab.com/v1/chat/completions`

### Request Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `model` | string | Yes | — | Virtual model identifier (e.g., `dheeman-auto`, `dheeman-pro`, `dheeman-flash`). |
| `messages` | array | Yes | — | Array of message objects with `role` and `content`. Roles: `system`, `user`, `assistant`, `tool`. |
| `stream` | boolean | No | `false` | Whether to stream chunks using Server-Sent Events (SSE). |
| `temperature` | float | No | `1.0` | Sampling temperature between 0.0 and 2.0. |
| `top_p` | float | No | `1.0` | Nucleus sampling probability threshold. |
| `max_tokens` | integer | No | null | Maximum tokens to generate in the completion. |
| `tools` | array | No | null | Standard OpenAI tool definitions for client-side execution. |
| `skills` | array | No | null | Optional list of explicit skill slugs to bind to the request context. |

---

## 8. Server-Sent Events (SSE) Streaming

When `"stream": true` is passed, Dhee delivers chunks over standard HTTP Server-Sent Events.

### Protocol Format
```http
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

data: {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1741478400,"model":"dheeman-pro","choices":[{"index":0,"delta":{"role":"assistant","content":"Dhee"},"finish_reason":null}]}

data: {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1741478400,"model":"dheeman-pro","choices":[{"index":0,"delta":{"content":" AI"},"finish_reason":null}]}

data: [DONE]
```

### Telemetry Headers on Streams
- `x-request-id`: Unique trace ID (`req_xxxxxxxxxxxxxxxx`).
- `x-dheeman-routed-model`: Effective model used for generation.
- `x-ratelimit-remaining-requests`: Remaining request quota.

---

## 9. Error Codes & Resilient Handling

Dhee uses standard HTTP status codes accompanied by structured error objects.

```json
{
  "error": {
    "message": "Monthly spending budget limit reached for project 'production-api'.",
    "type": "budget_exceeded_error",
    "code": "BUDGET_EXCEEDED",
    "request_id": "req_8f1c93a0b2"
  }
}
```

### HTTP Status Reference
| Code | Error Type | Cause | Resolution |
|---|---|---|---|
| `400` | `invalid_request_error` | Malformed JSON body or invalid parameter type. | Verify payload against API schema. |
| `401` | `authentication_error` | Missing or invalid Bearer API key. | Check `Authorization` header and key status. |
| `402` | `payment_required` | Account credits depleted or payment failure. | Top up balance or upgrade plan in dashboard. |
| `403` | `permission_denied` | Key does not have access to requested model or project. | Update key scopes in Developer Console. |
| `404` | `not_found_error` | Requested model or resource does not exist. | Check `GET /v1/models` for active slugs. |
| `413` | `payload_too_large` | Request payload exceeds maximum context window. | Reduce message history or input length. |
| `422` | `unprocessable_entity` | Input violates provider content safety boundaries. | Review prompt input content. |
| `429` | `rate_limit_error` | RPM, TPM, or monthly budget cap exceeded. | Inspect `Retry-After` header and back off. |
| `502` | `bad_gateway` | Upstream provider failure and standbys exhausted. | Client retry with exponential backoff. |
| `503` | `service_unavailable` | Temporary cluster maintenance or capacity limit. | Automated retry recommended. |

---

## 10. Rate Limits & Concurrency Leases

Rate limits are enforced using sliding window counters and atomic concurrency leases.

### Response Headers
- `x-ratelimit-limit-requests`: Maximum RPM allocated to your tier.
- `x-ratelimit-remaining-requests`: Remaining requests in the active window.
- `x-ratelimit-limit-tokens`: Maximum TPM allocated to your tier.
- `x-ratelimit-remaining-tokens`: Remaining tokens in the active window.
- `Retry-After`: Seconds to wait before re-attempting a throttled request.

---

## 11. Complete Dheeman Virtual Model Catalog

| Model Slug | Modalities | Primary Strengths | Service Tier |
|---|---|---|---|
| `dheeman-auto` | Dynamic / Multi | Autonomous routing across skills, tools, and depth | Dynamic |
| `dheeman-pro` | Text, Image | Deep multi-step reasoning, synthesis, tool calling | HIGH |
| `dheeman-flash` | Text | Ultra-low latency, high-throughput extraction | LOW |
| `dheeman-reasoning` | Text | Deliberative chain-of-thought, math, formal logic | HIGH |
| `dheeman-coding` | Text, Code | Full-stack engineering, refactoring, test suites | HIGH |
| `dheeman-vision` | Text, Image | Diagram understanding, UI analysis, visual QA | MID |
| `dheeman-ocr` | Image, PDF | Form extraction, tables, scanned document digitizing | MID |
| `dheeman-stt` | Audio, Video | Multilingual speech-to-text with timestamps | LOW |
| `dheeman-tts` | Text $\rightarrow$ Audio | Expressive, low-latency neural voice synthesis | LOW |
| `dheeman-image` | Text $\rightarrow$ Image | High-fidelity photorealistic image generation | HIGH |
| `dheeman-video` | Text $\rightarrow$ Video | Generative video and motion clips | HIGH |
| `dheeman-live` | Audio, Text | Real-time bidirectional voice conversation | HIGH |
| `dheeman-embed` | Text, Image | Dense vector embeddings for semantic search | LOW |
| `dheeman-rerank` | Query, Docs | Cross-encoder precision document ranking for RAG | LOW |

---

## 12. Support & Developer Resources

- **Developer Documentation**: `https://ai.dheelab.com/docs`
- **Interactive Quickstart**: `https://ai.dheelab.com/docs/quickstart`
- **Developer Console**: `https://ai.dheelab.com/dashboard`
- **Platform Architecture**: `https://ai.dheelab.com/platform`
- **API Status & Health**: `https://ai.dheelab.com/health`
- **Support Contact**: `support@dhee.ai`
