diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..f70c2f0f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,174 @@ +# Contributing to Intel® Agent Toolkit + +Thanks for wanting to help. Small fixes are just as welcome as big features. Find what you want to do in the table below and start there. + +## What do you want to do? + +| I want to… | Do this | Where | +|---|---|---| +| Report a bug | Open an issue with the command you ran, what you expected, and the error you got | [Issues](https://github.com/intel/agent-toolkit/issues) | +| Suggest a feature or ask a question | Open an issue and tell us what you're trying to do | [Issues](https://github.com/intel/agent-toolkit/issues) | +| Report a security vulnerability | Please don't open a public issue. Report it privately instead | [Intel Security Center](https://www.intel.com/security) ([SECURITY.md](SECURITY.md)) | +| Fix a typo or improve a guide | Edit the Markdown file and open a pull request | `docs/` | +| Change a default setting | Update `config.yaml`, and the role defaults if the role reads that value | `config.yaml`, `roles//defaults/main.yaml` | +| Fix a bug in a component | Fix it in that component's Ansible role | `roles//tasks/` | +| Update a Helm chart | Edit the chart and run `helm lint` on it | `charts//` | +| Add a new component | See [Add a new component](#add-a-new-component) | `roles/`, `charts/`, `components.yaml`, `config.yaml` | + +If you're not sure where your change fits, open an issue and ask. We're happy to point you in the right direction. + +--- + +## Your first pull request + +1. Fork the repository on GitHub, clone your fork, and make a branch off `main`: + + ```bash + git clone https://github.com//agent-toolkit.git + cd agent-toolkit + git checkout -b fix/short-description + ``` + +2. Make your change. Try to keep each pull request to one thing (one fix, one guide, one component). Smaller pull requests get reviewed a lot faster. + +3. Run the [checks](#checks) that apply to what you changed. If you only touched docs, you can skip this. + +4. Commit and push: + + ```bash + git commit -am "Fix pgvector teardown when the namespace is already gone" + git push origin fix/short-description + ``` + +5. Open a pull request against `main` in `intel/agent-toolkit`. Tell us what you changed, why, and how you tested it. + +The automated checks will run, and a maintainer will review it. + +--- + +## Checks + +Every pull request runs Ansible Lint, ShellCheck, Trivy, Checkov, Bandit, and Dependency Review. You'll save yourself a round trip if you run the relevant ones before you push: + +```bash +# Ansible roles +pip install ansible-lint +ansible-lint --skip-list name,var-naming,fqcn,yaml,jinja,key-order roles/ + +# Helm charts +helm lint charts/ + +# Shell scripts +shellcheck -x path/to/script.sh + +# Any YAML you edited +python3 -c "import yaml; yaml.safe_load(open('components.yaml'))" +``` + +### Testing on a cluster + +If you changed anything in `roles/` or `charts/`, please try it on a scratch cluster with [Toolkit Manager](https://github.com/intel/toolkit-manager). Point Toolkit Manager at your branch, then from the Toolkit Manager directory run: + +```bash +./toolkit_manager.sh install agent-toolkit -- --check # shows the install order without changing anything +./toolkit_manager.sh install +./toolkit_manager.sh validate +./toolkit_manager.sh install # second run should report zero "changed" +./toolkit_manager.sh teardown +./toolkit_manager.sh teardown # second run should still succeed +``` + +Running `install` and `teardown` twice is the part that catches the most bugs. Both have to be safe to re-run. + +--- + +## Add a new component + +A component is one service the toolkit installs on the cluster. Redis is a component, and so is the agent sandbox. These are the ones we have today: + +| Component | What it does | On by default? | +|---|---|---| +| `redis_stack` | Short-term memory: session state and caches | Yes | +| `pgvector` | Long-term memory: PostgreSQL with vector search | Yes | +| `agent_sandbox` | Isolated pods where agent-generated code runs | Yes | +| `openshell` | NVIDIA OpenShell, for stricter, policy-enforced sandboxes on top of the agent sandbox | No | +| `kuberay` | A Ray cluster for distributed Python jobs | No | +| `keycloak_agent_config` | Keycloak setup for agents | Only when Keycloak is the gateway | + +So adding a component means teaching the toolkit to install one more service, like another vector database. When you run an install, Toolkit Manager clones this repository under `ext/` and runs each enabled component in dependency order. + +Each component is made of a few pieces: + +| Piece | Where it goes | What it is | +|---|---|---| +| Role | `roles//` | The Ansible steps to install, check, and remove the service | +| Chart (optional) | `charts//` | The Helm chart the role deploys, committed in the repository | +| Settings | `config.yaml` | Defaults people can change, plus an on/off flag like `my_component_enabled: false` | +| Registry entry | `components.yaml` | Tells Toolkit Manager the component exists and what it depends on | +| Docs | `docs/
/`, `docs/README.md` | A short guide, linked from the docs index | + +Copying an existing component, like `roles/pgvector/` and `charts/pgvector/`, is usually the fastest way to start. + +### The role + +``` +roles// +├── tasks/ +│ ├── main.yaml Picks install, teardown, or validate +│ ├── install.yaml Deploys the service. Must be safe to run twice +│ ├── teardown.yaml Removes what install created. Must succeed if it's already gone +│ └── validate.yaml Checks the service is healthy. Never changes anything +├── defaults/main.yaml Every variable the role uses, with a default that works +└── meta/main.yaml Metadata only. Don't add dependencies here +``` + +`tasks/main.yaml` is the same in every role: + +```yaml +--- +- name: " | Dispatch action: {{ component_action }}" + ansible.builtin.include_tasks: "{{ component_action }}.yaml" +``` + +Toolkit Manager sets `component_action` to `install`, `teardown`, or `validate`. It also passes `env_dir`, `env_name`, and `kubernetes_kubeconfig`. + +### The registry entry + +```yaml +components: + - name: my_component + layer: agent-toolkit + enabled: "{{ my_component_enabled | default(true) | bool }}" + depends_on: [redis_stack] +``` + +A few things trip people up here: + +- `name` has to match the folder name under `roles/`. +- `depends_on` only lists components from this repository. You don't need to list Kubernetes or model serving; those are always installed first. +- `enabled` is evaluated before the role's defaults are loaded, so it needs its own `| default(...)` and should end with `| bool`. + +### The chart + +We commit charts into `charts//` so an install never has to reach an outside Helm repository. If your chart has subcharts, commit those too (as `.tgz` files under `charts//charts/`), or remove the ones you don't use. Otherwise `helm install` fails. In the role, refer to the chart with a path relative to `role_path`. + +### The settings + +When someone runs `init agent-toolkit`, `config.yaml` gets copied to `env//config.agent-toolkit.yaml`, and that copy is what they edit. So anything you want people to be able to change belongs in `config.yaml`. + +--- + +## A few house rules + +- Use the `kubernetes.core.k8s` and `kubernetes.core.helm` modules rather than calling `kubectl` or `helm` from a shell task. +- Keep variables flat, like `my_component_replicas`. Config files are merged, and a nested dictionary in one file overwrites the whole dictionary from another. +- Start variable names with your component name. Every component Toolkit Manager installs shares the same variable namespace. +- Never commit secrets or anything under `env/`. Generate secrets during install, or read them from a Kubernetes Secret. +- Keep LF line endings. `.gitattributes` handles this, but some copy tools sneak in CRLF, which breaks shell scripts on Linux. +- If your change affects a command, a setting, or a default, update the guide that talks about it. + +--- + +## License + +This project is licensed under the [Apache License, Version 2.0](LICENSE). By contributing, you agree that your contributions are licensed under the same terms. diff --git a/README.md b/README.md index ae7b1c3b..8defbbf6 100644 --- a/README.md +++ b/README.md @@ -1,370 +1,167 @@ -# Intel® Agent Toolkit +Intel® Agent Toolkit -[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/intel/enterprise-agent-toolkit/blob/main/LICENSE) -[![Platform: Intel® Xeon®](https://img.shields.io/badge/Platform-Intel%C2%AE%20Xeon%C2%AE-0068B5)](https://www.intel.com/xeon) + +[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/intel/agent-toolkit/blob/main/LICENSE) +[![Platform: Intel® Xeon® processors](https://img.shields.io/badge/Platform-Intel%C2%AE%20Xeon%C2%AE%20processors-0068B5)](https://www.intel.com/xeon) +[![Platform: GPU](https://img.shields.io/badge/Platform-GPU-0068B5)](https://www.intel.com/content/www/us/en/products/details/discrete-gpus.html) [![Deployment: Kubernetes](https://img.shields.io/badge/Deployment-Kubernetes-326CE5)](https://kubernetes.io) [![Gateway: LiteLLM](https://img.shields.io/badge/Gateway-LiteLLM-green)](https://litellm.ai) -[![Frameworks: LangGraph · CrewAI · Flowise](https://img.shields.io/badge/Frameworks-LangGraph%20%C2%B7%20CrewAI%20%C2%B7%20Flowwise-orange)](https://github.com/intel/enterprise-agent-toolkit) - -> **Deploy a production-grade, open source agentic AI stack on Intel® Xeon® in hours — not months.** -> A batteries-included Kubernetes platform with API gateway, intelligent inference routing, agent memory, sandboxed code execution, MCP tool integration, and full agent and system observability — all pre-integrated and ready to run. - -**Keywords:** agentic AI platform · enterprise AI agents · open source AI agent stack · Kubernetes AI deployment · LLM inference on CPU · Intel® Xeon® AI · LiteLLM gateway · AI agent memory RAG · on-premise LLM deployment · private AI infrastructure · AI agent observability · MCP server Kubernetes · vLLM sglang Intel® · Intel® Agent Toolkit - -> **Installing this release.** [Toolkit Manager](https://github.com/intel/enterprise-ai-solutions) installs and operates Intel® Agent Toolkit. Run the commands in these docs from an `enterprise-ai-solutions` checkout: -> -> ```bash -> git clone https://github.com/intel/enterprise-ai-solutions.git && cd enterprise-ai-solutions -> ./es_auto_installer.sh configure -> ./es_auto_installer.sh init agent-toolkit # creates env/local/ -> ./es_auto_installer.sh install agent-toolkit -> export KUBECONFIG=$PWD/env/local/kubeconfig.yaml # the kubectl commands in these docs use it -> ``` -> -> The `agentic-config.cfg` switches these docs mention are settings in `env//`: -> -> | Classic switch | Setting | File | -> |---|---|---| -> | `deploy_agent_sandbox`, `deploy_redis`, `deploy_pgvector` | `agent_sandbox_enabled`, `redis_stack_enabled`, `pgvector_enabled` (on) | `config.agent-toolkit.yaml` | -> | `deploy_openshell`, `deploy_kuberay` | `openshell_enabled`, `kuberay_enabled` (off) | `config.agent-toolkit.yaml` | -> | `deploy_genai_gateway`, `deploy_guardrails` | `auth_type: "litellm_vkey"` (set by `init agent-toolkit`); `guardrails_enabled` | `config.agent-toolkit.yaml` | -> | `deploy_vllm_sr` | `vllm_sr_enabled` | `config.inference.yaml` | -> | `deploy_kata_containers` | `kata_containers_enabled`, `kata_runtime` | `global_config.yaml` | -> | `deploy_llm_models`, `models=` | `llm_services_autodeploy_models`; `./model-manager deploy ` | `config.agent-toolkit.yaml` | -> | `deploy_istio`, `deploy_observability`, `deploy_ceph`, `deploy_kubernetes_fresh` | `istio_enabled`, `observability_enabled`, `storage_backend`, `existing_kubernetes` | `global_config.yaml` | -> -> Remove the toolkit with `./es_auto_installer.sh teardown agent-toolkit`, or the whole cluster with `teardown infrastructure`. Not in this release: the Flowise plugin, Intel® Arc™ (XPU) deployment and rack-scale networking. - ---- - -## Table of Contents - -- [Why This Matters](#why-this-matters) -- [Business Value at a Glance](#business-value-at-a-glance) -- [Architecture](#architecture) -- [Provider Design Pattern](#provider-design-pattern) -- [Provider Blocks](#provider-blocks) - - [API Gateway & Access Control](#api-gateway--access-control) - - [Intelligent Inference Routing](#intelligent-inference-routing) - - [Actions & Tools](#actions--tools) - - [Code Execution & Sandbox](#code-execution--sandbox) - - [Memory, State & Context](#memory-state--context) - - [Observability & Telemetry](#observability--telemetry) - - [Deployment & Orchestration](#deployment--orchestration) -- [Infrastructure Core](#infrastructure-core) -- [Validated Orchestration Frameworks](#validated-orchestration-frameworks) -- [Example Business Use Cases](#example-business-use-cases-not-pre-bundled) -- [Deployment Model](#deployment-model) -- [Rack-Scale AI Fabric Mode](#rack-scale-ai-fabric-mode) -- [Build vs. Build-from-Scratch](#build-vs-build-from-scratch) -- [Frequently Asked Questions](#frequently-asked-questions) -- [Repository Structure](#repository-structure) -- [Links](#links) - ---- - -## Why This Matters - -AI agents are not just smarter chatbots — they are autonomous systems that plan, act, and iterate across multi-step tasks. Building a production-ready agentic AI platform from scratch requires solving a dozen infrastructure problems simultaneously: secure API access, LLM inference routing, agent memory and state management, sandboxed code execution, LLM observability, and enterprise governance. - -Most organizations waste months stitching together LiteLLM, Redis, pgvector, Kubernetes, Langfuse, and agent sandboxes. This open source toolkit delivers them pre-integrated, pre-optimized for Intel® Xeon®, and deployable in a single automated workflow. - -**The core insight:** GPUs accelerate reasoning. But the *value* of agentic AI comes from end-to-end task execution — and that control plane (state, tools, policy, coordination) runs efficiently on CPUs. This toolkit is designed around that reality, making it the ideal platform for cost-efficient, on-premise, and private AI deployments. - ---- - -## Business Value at a Glance - -| Problem | What the Toolkit Delivers | -|---|---| -| Long time-to-production | One-click Kubernetes deployment — base stack live in hours | -| Integration complexity | All layers pre-integrated: gateway, memory, sandbox, observability | -| Vendor lock-in risk | Provider Design Pattern — swap or extend any component without re-architecting | -| Governance & compliance gaps | Policy-driven API gateway, sandboxed execution, full audit trail | -| GPU cost dependency | CPU-efficient LLM inference by default on Xeon; GPU addable on demand | -| Observability blind spots | Every token, latency, and agent step captured and queryable | -| Adoption friction | Works with LangGraph, CrewAI, Flowise, Microsoft Agent Framework, and any OpenAI-compatible framework | - ---- - -## Architecture - -![Intel® Agent Toolkit architecture: your agent (LangGraph, CrewAI, OpenClaw, Microsoft Agent Framework) sits on top; below are seven blocks — API gateway and policy (LiteLLM, auth, rate limits), memory and state (Redis, PostgreSQL, pgvector), inference and routing (vLLM, SGLang, cloud LLMs), actions and tools (MCP servers), sandbox (Agent Sandbox, OpenShell), observability (Langfuse, Prometheus, Grafana), and deployment and scaling (Ansible, Helm, autoscaling) — then the platform (Kubernetes, Docker Compose) and compute (Intel® Xeon® for orchestration and execution, GPUs and cloud LLMs for inference)](docs/pictures/intel-agent-toolkit-architecture.png) - -The toolkit is organized into **seven pluggable provider blocks**, each with a default implementation and a defined interface. Customers can use the defaults on day one and swap or extend individual providers as their needs evolve — without touching any other layer. - ---- +[![Frameworks: LangGraph · CrewAI · OpenClaw · Microsoft Agent Framework](https://img.shields.io/badge/Frameworks-LangGraph%20%C2%B7%20CrewAI%20%C2%B7%20OpenClaw%20%C2%B7%20Microsoft%20Agent%20Framework-orange)](https://github.com/intel/agent-toolkit) + -## Provider Design Pattern - -Each functional block in the toolkit follows a **Provider Design Pattern**: the block defines the capability contract (what it does), not the implementation (how it does it). The default provider is Intel-validated and optimized for Xeon out of the box. Any standard-compliant alternative can be substituted. - -This means: -- **No big-bang replacements.** Swap one provider at a time. -- **No lock-in.** The toolkit never mandates a proprietary runtime. -- **Incremental adoption.** Start with all defaults; introduce your own components over time. - ---- - -## Provider Blocks - -Each functional block ships with an Intel-validated default. Because the toolkit is built on the Provider Design Pattern, any block can be swapped or extended independently — without touching the rest of the stack. - -### API Gateway & Access Control -Unified, secure entry point for all agents, tools, and applications. Routes every request through a policy-driven layer that enforces authentication, authorization, and rate limiting before anything reaches a model or tool. Supports any OpenAI-compatible backend — cloud, on-premise, or hybrid. - -**Default provider:** LiteLLM - ---- - -### Intelligent Inference Routing -Automatically dispatches LLM inference workloads to the optimal compute target based on task intent. Reasoning and planning tasks are routed to GPU or cloud/MaaS endpoints; execution, encoding, and coordination tasks are routed to CPU on Xeon. Rules are configurable per application and model-agnostic — works with OpenAI, Anthropic Claude, Google Gemini, and any self-hosted model. - -**Default provider:** LiteLLM Semantic Router · Intel Native Inferencing Service (vLLM, SGLang) - -The **[Hybrid Router](docs/hybrid-router.md)** extends this with cost- and latency-aware model selection: clients call a single virtual model (`hybrid-router`), which classifies each request by complexity and routes it to the smallest capable model per tier, while an online multi-armed bandit learns which candidate is most efficient. It plugs into the LiteLLM GenAI Gateway with no image rebuild — toggle it with `customRouter.enabled` in the `genai-gateway` Helm chart. See the **[Hybrid Router Guide](docs/hybrid-router.md)**. - ---- +# Intel® Agent Toolkit -### Actions & Tools -Gives agents the ability to take actions in the world — call APIs, run code, query databases, and invoke external services — through a governed and extensible tool layer. MCP (Model Context Protocol) server templates let teams register domain-specific tools without modifying the core stack. +**Quickly deploy a production-ready, open source agentic AI stack.** -**Default provider:** Intel MCP (Model Context Protocol) · ETL / Ingestion Services +> An agentic AI stack with an API gateway, inference routing, agent memory, sandboxed code execution, and observability. Toolkit Manager installs these pieces for you. --- -### Code Execution & Sandbox -Enables agents to safely execute code and run arbitrary actions in isolated environments, preventing runaway agents from affecting production systems. Each sandbox is a fully self-contained ephemeral Kubernetes pod with its own filesystem and process tree. Policy controls limit the blast radius of any single agent action. For untrusted code, microVM-level isolation is available as an opt-in — set `kata_containers_enabled: true` in `global_config.yaml` to run sandboxes on Kata Containers with Firecracker (`kata-fc`) or QEMU (`kata-qemu`), giving each sandbox its own guest kernel instead of sharing the host's. +Teams that want **production AI agents** usually discover that a language-model endpoint is not enough. An agent has to remember a conversation, look up company data, call internal APIs, and sometimes run code it just generated. Doing that on a public cloud API also means prompts and documents leave the premises, and every team rebuilds the same plumbing: a gateway (LiteLLM), memory (Redis and pgvector), a sandbox, and traces (Langfuse). -**Default provider:** `kubernetes-sigs/agent-sandbox` +Intel® Agent Toolkit is that plumbing on **Intel® Platforms** you already operate. [Toolkit Manager](https://github.com/intel/toolkit-manager) installs, updates, and tears it down, including the cluster and model serving. Applications keep an **OpenAI-compatible API**, so developers change the base URL and the API key and keep using LangGraph, CrewAI, OpenClaw, Microsoft Agent Framework, or a similar framework. Data and weights stay on your hardware. A GPU is not required, because memory, tools, and coordination run on the CPU, while a GPU or a cloud model can still answer the language-model call when you want that. -**Optional provider:** [NVIDIA OpenShell](docs/openshell.md) — policy-enforced sandboxes on top of Agent Sandbox (egress default-deny, L7 rules, Landlock, credential isolation with GenAI Gateway keys). Enable with `openshell_enabled: true` in `config.agent-toolkit.yaml`. +

+ Intel® Agent Toolkit. Your agent (LangGraph, CrewAI, OpenClaw, Microsoft Agent Framework) calls an API gateway (LiteLLM, auth, rate limits). The stack provides memory (Redis, PostgreSQL, pgvector), inference and routing (vLLM, SGLang, cloud LLMs), an agent sandbox for code execution, and observability (Langfuse, Prometheus, Grafana). Deployment scales from one node to a rack with Ansible, Helm, and autoscaling, on a cluster (for example Kubernetes) or Docker Compose, using Intel® Xeon® processors for orchestration and execution, with GPUs and cloud LLMs for inference. +

--- -### Memory, State & Context -Maintains agent memory across the full lifecycle — short-term working context within a session and long-term knowledge across sessions and users. Enables RAG (Retrieval-Augmented Generation), semantic search over past interactions, and stateful multi-turn workflows. Agents maintain context across tasks, sessions, and workflows. +## What you get -**Default provider:** Redis + RediSearch (short-term) · PostgreSQL + pgvector (long-term) +A default `install agent-toolkit` brings up platform, model serving, and this toolkit. Every component below is configurable: turn it off, change its settings, or bring your own. See [Configuration](docs/configuration/configuration.md) and [Meet the Agent Toolkit](docs/overview/meet.md#toolkit-components). ---- - -### Observability & Telemetry -Every token, latency measurement, and agent step is captured, stored, and queryable. Provides LLM-native tracing for debugging agent reasoning chains, out-of-the-box dashboards, and seamless integration with existing enterprise monitoring infrastructure — no custom instrumentation required. - -**Default provider:** Langfuse · Prometheus · Grafana · Loki - ---- - -### Deployment & Orchestration -Manages the full lifecycle of the stack — provisioning, scaling, updates, and teardown — across single-node and multi-node environments. Supports both production Kubernetes clusters and lightweight Docker Compose for development and demos, using the same configuration. - -**Default provider:** Kubernetes · Helm · Docker Compose - ---- - -## Infrastructure Core - -All provider blocks run on a common infrastructure foundation: +| Component | Default | Role | +|---|---|---| +| **LiteLLM** | On (`auth_type: litellm_vkey`) | HTTPS gateway: one URL, virtual keys per app, OpenAI-compatible `/v1/chat/completions`. Or Envoy gateway with Keycloak auth (`auth_type: jwt`) | +| **Redis Stack** | On | Short-term memory: session state, caches, and RediSearch | +| **PostgreSQL + pgvector** | On | Long-term memory: embeddings, RAG, and data that persists across restarts | +| **Agent Sandbox** | On | Isolated pods for agent actions, off the host | +| **OpenShell** | Off | Policy layer on the Agent Sandbox. Set `openshell_enabled: true` at install — [OpenShell](docs/reference/openshell.md) | +| **KubeRay** | Off | Distributes Python tasks across worker pods. Set `kuberay_enabled: true` | +| **Keycloak realm** | On | Creates an `agent-toolkit` realm on the platform Keycloak; does not deploy Keycloak itself. Set `keycloak_agent_config_enabled: false` to skip it | +| **Langfuse** | On with LiteLLM | Trace UI for each LLM call: prompt, tokens, latency, and the model that served the request | -| Layer | Details | -|---|---| -| **Operating System** | Ubuntu 24.04 LTS / RHEL | -| **CPU Configuration** | Intel® Xeon® — NUMA tuning, firmware, drivers, AMX enabled | -| **Compute & Runtime** | Intel® Xeon® · Intel® AI Accelerators · Intel® Arc™ | -| **Supported Model APIs** | OpenAI · Anthropic Claude · Google Gemini · SambaNova · local models via vLLM / SGLang | +Platform observability (Prometheus, Grafana, and related stack services) comes with the platform layer. ---- +The toolkit is framework-agnostic. Agents built with LangGraph, CrewAI, Microsoft Agent Framework, OpenClaw, or any other agentic framework use it through standard interfaces: an OpenAI-compatible model gateway, Redis and PostgreSQL/pgvector for memory and state, and the Agent Sandbox. This repository provides the infrastructure those frameworks run on; it does not replace them. -## Validated Orchestration Frameworks +### Validated frameworks | Framework | Style | |---|---| | **LangGraph** | State-machine, multi-step agent workflows | -| **Flowise** | Low-code visual pipeline builder | | **CrewAI** | Role-based multi-agent collaboration | -| **OpenClaw** | Intel-optimized agentic framework =Local gateway for multi-agent routing via chat apps | +| **OpenClaw** | Local gateway for multi-agent routing via chat apps | +| **Microsoft Agent Framework** | Multi-agent and graph workflows in Python and .NET | --- -## Example Business Use Cases (Not pre-bundled) +## Quickstart -| Use Case | Description | -|---|---| -| **Coding Agent** | Automated code generation, review, test, and fix loops — accelerates developer productivity | -| **Deep Research Agent** | Multi-step web and knowledge base research with citation; replaces hours of analyst work | -| **Flowise Agents** | Low-code visual agent pipeline construction for business teams | -| **Customer Support Automation** | RAG-augmented, multi-turn resolution with memory — reduces ticket handle time | -| **Enterprise Data Analyst** | Natural language to SQL/report across internal databases — self-serve analytics | -| **IT Operations Agent** | Infrastructure monitoring, alerting, and self-healing workflows — reduces MTTR | +Start here to run the agent platform on one host. Toolkit Manager installs the stack and one chat model; the last step calls the gateway so you can see that it answers. Defaults are domain `inteltoolkits.ai` and model `qwen2-5-coder-14b` (about 131 GB of RAM for the whole stack). ---- +Complete **[Prerequisites](docs/getting-started/prerequisites.md)** once before you start (Intel® AMX, SSH, and the kernel settings). -## Deployment Model +### 1. Get Toolkit Manager and seed the config -### Deployment Options +Clone Toolkit Manager, install its tools, then create an `env/local/` directory with the defaults for this toolkit. Run every later command from that directory. -| Option | Stack | Best For | -|---|---|---| -| **Multi-node Kubernetes** | Kubespray + Helm + KubeRay (for Parallel Tool Calling) | Production, HA, scale-out | -| **Single-node Kubernetes** | K8s + Helm | Pilot, staging, edge | -| **Docker Compose** | Docker Compose | Development, demos, single machine | -| **Rack-Scale AI Fabric** | Kubespray + Calico BGP + Rook/Ceph on fabric | High-performance rack with high-speed AI fabric (100G/200G/400G/800G) and NVMe storage | - - -## Deployment Platform - -The Intel® Agent Toolkit supports two deployment platforms: - -### Kubernetes (Default) - -Production-grade orchestration with Helm charts, designed for: -- **Multi-node clusters** -- **High availability** -- **Production workloads** - -**Deploy with:** + ```bash -./es_auto_installer.sh install agent-toolkit +git clone https://github.com/intel/toolkit-manager.git +cd toolkit-manager +./toolkit_manager.sh configure +./toolkit_manager.sh init agent-toolkit ``` -See [Kubernetes Deployment](#kubernetes-deployment) below for full setup. - -### Docker Compose +`init` also clones this repository under `ext/`. Leave the files under `env/local/` as they are for the first run. -Simplified single-node deployment with Docker containers, designed for: -- **Development and testing** -- **Proof-of-concept** -- **Resource-constrained environments** (no Kubernetes overhead) +### 2. Install the stack +This brings up the cluster, model serving, and the agent services (memory, sandbox, and the gateway). -**Deploy with:** + ```bash -./docker/deploy.sh # from an enterprise-agent-toolkit checkout +./toolkit_manager.sh install agent-toolkit ``` -See [`docker/README.md`](docker/README.md) for comprehensive Docker deployment guide, including [Multi-Model Deployment](docker/README.md#multi-model-deployment). - -### Decision Tree - -| Your Need | Platform | Rationale | -|-----------|----------|-----------| -| Production deployment | Kubernetes | HA, scaling, resource management | -| Multi-node cluster | Kubernetes | Only K8s supports distributed execution | -| Local development | Docker | Faster setup, no K8s overhead | -| Testing multi-model | Docker | Easy config changes, faster iteration | -| CI/CD integration | Docker | Simpler automation, `--skip-confirmation` flag | -| SLA requirements | Kubernetes | Rolling updates, auto-healing, monitoring | -| Learning the stack | Docker | Lower complexity, direct container access | +The first run usually takes 20–40 minutes, and the model may take longer to download. If the command stops part-way, run it again; it continues from where it left off. ---- - -### How to Deploy +### 3. Call the gateway -### 1. Clone the repository +Confirm the API answers. The curl uses the installer CA and `--resolve`, so you do not need `/etc/hosts` for this smoke test. + ```bash -git clone https://github.com/intel/enterprise-ai-solutions.git -cd enterprise-ai-solutions -./es_auto_installer.sh configure +export KUBECONFIG=$(pwd)/env/local/kubeconfig.yaml +GATEWAY_IP=$(kubectl get svc -n envoy-gateway-system \ + -l gateway.envoyproxy.io/owning-gateway-name=eg-gateway \ + -o jsonpath='{.items[0].status.loadBalancer.ingress[0].ip}') +DOMAIN=$(yq '.base_domain_name' env/local/global_config.yaml) +export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm \ + -o jsonpath='{.data.master_key}' | base64 -d) + +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.$DOMAIN:443:$GATEWAY_IP" \ + "https://litellm.$DOMAIN/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ + -d '{"model": "qwen2-5-coder-14b", + "messages": [{"role": "user", "content": "Write a Python hello world"}], + "max_tokens": 100}' ``` -### 2. Complete prerequisites -Hardware requirements, SSH key setup, and DNS/TLS configuration are covered in **[Prerequisites Guide](docs/prerequisites.md)**. +A working reply includes `choices[0].message.content`. The master key is only for this check. -### 3. Quick Start +### 4. Connect your agent -The full step-by-step deployment guide — covering the base stack, semantic routing, Redis, pgvector, Agent Sandbox, and OpenShell — is in **[Quick Start Guide](docs/README.md)**. +Any OpenAI-compatible framework can call this gateway (LangGraph, CrewAI, OpenClaw, Microsoft Agent Framework, and others). Create a virtual key, point the client at the base URL, and keep your existing agent code. +A worked LangChain example is **[build your first agent](docs/getting-started/first-agent.md)** — same base URL and virtual key pattern for the other frameworks above. -**Estimated time to first running agent: hours, not months.** +When you want a different domain or model, use the [single-node quickstart](docs/getting-started/quickstart.md). --- -## Backend Connection Reference - -In-cluster URLs for all shared backends (Redis, Agent Sandbox, OpenShell, pgvector, KubeRay, Flowise). See **[Backend Connection Reference](docs/backend-connection-reference.md)** for the full reference. +## Choose how to run it ---- - -## Decommission / Reset and Redeploy from Scratch +| Path | Best for | Guide | +|---|---|---| +| **Single node** | The agent platform on one machine. Start here. | [Single-node quickstart](docs/getting-started/quickstart.md) | +| **Multi-node** | One control plane plus workers | [Multi-node](docs/deployment/multi-node.md) | +| **Docker Compose** | Containers on one Linux host, without Toolkit Manager | [Docker](docs/deployment/docker.md) | -To tear down the cluster and redeploy from scratch, see **[Decommission and Redeploy Guide](docs/decommission-and-redeploy.md)**. +Also available: [rack-scale](docs/deployment/rack-scale.md) and [Intel® Arc™ GPU](docs/deployment/intel-arc.md) (both via Toolkit Manager). For Intel® Arc™ Pro B-Series (B70) and other Xe GPUs, start with Toolkit Manager’s [Install the platform](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/install-platform.md) (GPU device plugin), then [Intel® Arc™ GPU](docs/deployment/intel-arc.md) to serve a model. --- -## Rack-Scale AI Fabric Mode +## Documentation -For deployments on a **high-speed AI fabric** (100G, 200G, 400G, or 800G — Arista Clos or equivalent) with Intel® E810-C or compatible NICs, dual-homed nodes, and NVMe Ceph storage, the toolkit ships a dedicated rack-scale deployment path driven by a single declarative `rack-profile.yaml`. +The map of every guide is the [docs index](docs/README.md). Start here: -> **Note:** not available in this release. +- [Meet the Agent Toolkit](docs/overview/meet.md) +- [Prerequisites](docs/getting-started/prerequisites.md) +- [Single-node quickstart](docs/getting-started/quickstart.md) +- [OpenShell](docs/reference/openshell.md) — policy layer on the Agent Sandbox (`openshell_enabled: true`) +- [Troubleshooting](docs/faq-and-troubleshooting/troubleshooting.md) -- **Zero-encapsulation pod networking** — Calico native BGP, no IPIP/VXLAN, wire-speed L3 routing via leaf switches at any link speed -- **Ceph storage on fabric** — OSDs bind to fabric IPs, not management NICs; NVMe drives are the bottleneck, not the network -- **Single config file** — `rack-profile.yaml` describes node roles, NIC mappings, leaf switches, and NVMe devices; a parser generates all derived Kubernetes and Ceph config automatically -- **Speed-agnostic** — migrating from 100G to 400G or 800G requires only updating NIC names and the `mtu` field; no code changes +Related software Toolkit Manager can install: [Intel® Inference Toolkit](https://github.com/intel/inference-toolkit) and [Intel® Chatbot Toolkit](https://swcatalog.intel.com/developer/docs/enterprise-rag). -**Validated on Intel Lab201 (100G Arista Clos, E810-C NICs):** 83 Gbits/sec cross-leaf throughput, 1.42 GB/s Ceph sequential write, 29K IOPS under concurrent burn. - -See **[Rack-Scale Deployment Guide](docs/rack-scale-deployment.md)** for the full setup walkthrough. +> Discover more AI software on the [Intel® Software Catalog](https://swcatalog.intel.com/). --- -## Build vs. Build-from-Scratch - -| Dimension | Build from Scratch | Intel® Agent Toolkit | -|---|---|---| -| Time to production | 3–6 months | Hours to days | -| Vendor lock-in | None | None (Apache 2.0) | -| Component flexibility | Full (you build it) | Full (Provider Pattern) | -| GPU dependency | Your choice | Optional | -| Data residency | Full control | Full control | -| Enterprise governance | You build it | Built-in | -| Intel® Xeon® optimization | Manual | Native | -| Total cost of ownership | High | Low (open source + Xeon) | - ---- - -## Frequently Asked Questions - -**What is the Intel® Agent Toolkit?** -An open source, Kubernetes-based platform that gives enterprises everything they need to deploy, run, and govern production AI agents on Intel® Xeon® — including LLM gateway, inference routing, agent memory, sandboxed execution, MCP tool integration, and full observability. - -**How is this different from LangChain, LangGraph, or CrewAI?** -LangGraph, CrewAI, and similar frameworks handle agent orchestration logic. This toolkit provides the production infrastructure underneath them — the API gateway, inference routing, memory store, sandbox, and observability layer. You use LangGraph or CrewAI *on top of* this toolkit. - -**Does it require a GPU?** -No. The toolkit is designed to run AI agent workloads efficiently on Intel® Xeon® CPUs using AMX acceleration. GPU or cloud LLM endpoints (OpenAI, Anthropic, Google) can be added to the same gateway for reasoning-heavy tasks. - -**Can I use it with OpenAI, Anthropic Claude, or Google Gemini?** -Yes. The LiteLLM API gateway is fully OpenAI-compatible and supports all major model providers — OpenAI, Anthropic Claude, Google Gemini, SambaNova, and any self-hosted model via vLLM or SGLang. - -**Is this suitable for on-premise or air-gapped deployments?** -Yes. The full stack runs on bare metal or private cloud Intel® Xeon® servers with no external dependencies required. Ideal for regulated industries requiring data residency and private AI deployments. - -**Can I replace individual components?** -Yes — this is the core design principle. The toolkit is built on the Provider Design Pattern: each block (gateway, memory, observability, etc.) has a default but can be swapped independently without touching other layers. - -**What agent frameworks does it support?** -LangGraph, CrewAI, Flowwise, OpenClaw, and any Python-based or OpenAI-compatible orchestration framework. - -**How do I get started?** -Clone `enterprise-ai-solutions`, run `./es_auto_installer.sh configure`, `./es_auto_installer.sh init agent-toolkit` and `./es_auto_installer.sh install agent-toolkit`, and follow the [Quick Start Guide](docs/README.md). - +## Contributing -**License:** Apache 2.0 · **Primary languages:** Shell (88%), Jinja (10%), Go Template (2%) +Bug reports, doc fixes, and new components are all welcome. [CONTRIBUTING.md](CONTRIBUTING.md) starts with a table of what to do for each kind of change, then walks through your first pull request. --- -## Links +## License -- [GitHub Repository](https://github.com/intel/enterprise-agent-toolkit) -- [Quick Start Guide](docs/README.md) -- [Prerequisites](docs/prerequisites.md) -- [Rack-Scale AI Fabric Deployment](docs/rack-scale-deployment.md) -- [Decommission & Redeploy](docs/decommission-and-redeploy.md) +Licensed under the [Apache License, Version 2.0](https://github.com/intel/agent-toolkit/blob/main/LICENSE). --- -*Intel®, Intel® Xeon®, and Intel® Arc™ are registered trademarks of Intel Corporation or its subsidiaries.* -*Licensed under the Apache License, Version 2.0.* +*Intel, the Intel logo, Xeon, and Arc are trademarks of Intel Corporation or its subsidiaries.* diff --git a/charts/agent-sandbox/default-templates.yaml b/charts/agent-sandbox/default-templates.yaml index 80026c6b..746bd2a0 100644 --- a/charts/agent-sandbox/default-templates.yaml +++ b/charts/agent-sandbox/default-templates.yaml @@ -9,7 +9,7 @@ # sandbox = client.create_sandbox(warmpool="python-pool", namespace="agent-sandbox-system") # # The install creates the python-pool SandboxWarmPool for this template; calls through the -# router need its token (docs/agent-sandbox.md, "Router token"). +# router need its token (docs/reference/agent-sandbox.md, "Router token"). # --------------------------------------------------------------------------- apiVersion: extensions.agents.x-k8s.io/v1beta1 kind: SandboxTemplate diff --git a/docker/README.md b/docker/README.md index 3ef64718..3cf7751e 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,6 +1,6 @@ -# Agentic AI Stack — Docker Compose Deployment +# Intel® Agent Toolkit — Docker Compose deployment -A complete Docker Compose solution for the Agentic AI Stack that mirrors the Kubernetes deployment without requiring a cluster. All components run as containers with ports exposed directly to the host. +A Docker Compose path for Intel® Agent Toolkit that mirrors the Kubernetes deployment without requiring a cluster. All components run as containers with ports exposed directly to the host. --- diff --git a/docs/README.md b/docs/README.md index 695a1538..5d8204e1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,45 +1,71 @@ -# Quick Start — Intel® Agent Toolkit - - -> **Installing this release.** [Toolkit Manager](https://github.com/intel/enterprise-ai-solutions) installs and operates Intel® Agent Toolkit. Run the commands in these docs from an `enterprise-ai-solutions` checkout: -> -> ```bash -> git clone -b release-2.0 https://github.com/intel/enterprise-ai-solutions.git && cd enterprise-ai-solutions -> ./es_auto_installer.sh configure -> ./es_auto_installer.sh init agent-toolkit # creates env/local/ -> ./es_auto_installer.sh install agent-toolkit -> export KUBECONFIG=$PWD/env/local/kubeconfig.yaml # the kubectl commands in these docs use it -> ``` -> -> The `agentic-config.cfg` switches these docs mention are settings in `env//`: -> -> | Classic switch | Setting | File | -> |---|---|---| -> | `deploy_agent_sandbox`, `deploy_redis`, `deploy_pgvector` | `agent_sandbox_enabled`, `redis_stack_enabled`, `pgvector_enabled` (on) | `config.agent-toolkit.yaml` | -> | `deploy_openshell`, `deploy_kuberay` | `openshell_enabled`, `kuberay_enabled` (off) | `config.agent-toolkit.yaml` | -> | `deploy_genai_gateway`, `deploy_guardrails` | `auth_type: "litellm_vkey"` (set by `init agent-toolkit`); `guardrails_enabled` | `config.agent-toolkit.yaml` | -> | `deploy_vllm_sr` | `vllm_sr_enabled` | `config.inference.yaml` | -> | `deploy_kata_containers` | `kata_containers_enabled`, `kata_runtime` | `global_config.yaml` | -> | `deploy_llm_models`, `models=` | `llm_services_autodeploy_models`; `./model-manager deploy ` | `config.agent-toolkit.yaml` | -> | `deploy_istio`, `deploy_observability`, `deploy_ceph`, `deploy_kubernetes_fresh` | `istio_enabled`, `observability_enabled`, `storage_backend`, `existing_kubernetes` | `global_config.yaml` | -> -> Remove the toolkit with `./es_auto_installer.sh teardown agent-toolkit`, or the whole cluster with `teardown infrastructure`. Not in this release: the Flowise plugin, Intel® Arc™ (XPU) deployment and rack-scale networking. - -## Prerequisites -Complete all [prerequisites](./prerequisites.md). - -## Deployment Options - -| Deployment Option | Description | Guide | -|---|---|---| -| Single Node | Quick start for testing or lightweight workloads on a single Intel® Xeon® server | [Single Node Guide](single-node-deployment.md) | -| Single Master, Multiple Workers | For higher throughput workloads with one control-plane and N worker nodes | [Multi-Node Guide](multi-node-deployment.md) | -| Docker Compose | Simplified single-node deployment for development, demos, and resource-constrained environments | [Docker Guide](../docker/README.md) | - -## Feature Guides - -| Feature | Description | Guide | -|---|---|---| -| Hybrid Router | Complexity-aware, cost/latency-optimizing inference routing for the GenAI Gateway | [Hybrid Router Guide](hybrid-router.md) | -| Intel® Arc™ (XPU) GPU | Deploy vLLM models on Intel discrete GPUs (Arc/Flex/Max, incl. Battlemage) via `compute_platform=xpu`. **Note:** not available in this release. | [Intel Arc XPU Guide](intel-arc-xpu-deployment.md) | -| Stack Validation | Post-deploy health checks, preflight node readiness, burn tests, and traffic-light reporting | [Validate Stack Guide](validate-stack.md) | +# Intel® Agent Toolkit documentation + +

+ Intel® Agent Toolkit +

+ +The technical documentation for Intel® Agent Toolkit. Start with **Meet** for the what and why, **Get started** to stand it up, then **Deployment**, **Customize**, **Operate**, or **Reference** as you need them. + +> [!IMPORTANT] +> Toolkit Manager installs and operates this toolkit. Clone **that** repository, run every command from its root, and `init agent-toolkit` will fetch this one into `ext/` for you. See [Meet the Agent Toolkit](overview/meet.md). + +## Meet + +| Guide | What it covers | +|---|---| +| [Meet the Agent Toolkit](overview/meet.md) | What it is, why it exists, when to choose it, and which repository to clone | +| [FAQ](faq-and-troubleshooting/frequently-asked-questions.md) | Short answers to the questions that come up most | +| [Glossary](reference/glossary.md) | Terms used across these guides, defined once | + +## Get started + +| Guide | What it covers | +|---|---| +| [Prerequisites](getting-started/prerequisites.md) | Hardware, SSH, DNS, and TLS to have ready before install | +| [Quickstart](getting-started/quickstart.md) | From `init agent-toolkit` to a working `/v1/chat/completions` call | +| [Build your first agent](getting-started/first-agent.md) | A LangChain agent with a tool, called through the gateway | + +## Deployment + +| Guide | What it covers | +|---|---| +| [Multi-node](deployment/multi-node.md) | One control plane plus worker nodes | +| [Rack-scale](deployment/rack-scale.md) | High-speed fabric via Toolkit Manager (`rack_scale_enabled`) | +| [Intel® Arc™ GPU](deployment/intel-arc.md) | GPU serving via Toolkit Manager (`vllm-xpu`), including Arc Pro B-Series / B70 | +| [Docker Compose](deployment/docker.md) | Containers on one Linux host without Toolkit Manager | +| [Decommission](deployment/decommission.md) | Tear the install down and install again | + +Behind a corporate proxy: [Corporate proxy](deployment/proxy.md). Related installs: [Inference Toolkit](https://github.com/intel/inference-toolkit) (`init inference`), [Chatbot Toolkit](https://github.com/intel/chatbot-toolkit) (`init erag`). Model catalog and `./model-manager deploy`: [Deploy a model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md) in Toolkit Manager. + +## Customize + +Edit YAML under `env/local/` and re-run `install`. + +| Guide | What it covers | +|---|---| +| [Configuration](configuration/configuration.md) | Which YAML file holds each setting | +| [Guardrails](configuration/guardrails.md) | Screen each prompt before the main model | +| [Routing](configuration/routing.md) · [Hybrid router](configuration/hybrid-router.md) | Send a request to one of several models (hybrid is on by default) | +| [vLLM semantic router](configuration/semantic-router.md) | Opt-in intent routing (`vllm_sr_enabled: true`) | + +## Operate + +| Guide | What it covers | +|---|---| +| [Validate the stack](faq-and-troubleshooting/validate.md) | Check the cluster after install | +| [Troubleshooting](faq-and-troubleshooting/troubleshooting.md) | Fix a failed install, API call, or pod | + +## Reference + +| Guide | What it covers | +|---|---| +| [Backend connections](reference/backend-connections.md) | Redis, pgvector, sandbox, and gateway URLs | +| [Agent sandbox](reference/agent-sandbox.md) | Isolated pods for agent-generated code | +| [OpenShell](reference/openshell.md) | Policy around that code (off by default) | +| [KubeRay](reference/kuberay.md) | Ray jobs in the cluster (off by default) | + +To report a bug or change the toolkit, see [Contributing](../CONTRIBUTING.md). + +--- + +*Intel, the Intel logo, and Arc are trademarks of Intel Corporation or its subsidiaries.* diff --git a/docs/agent-sandbox.md b/docs/agent-sandbox.md deleted file mode 100644 index 79b5ef17..00000000 --- a/docs/agent-sandbox.md +++ /dev/null @@ -1,750 +0,0 @@ -# Agent Sandbox - -Agent Sandbox provides **isolated, ephemeral Kubernetes pod environments** for -safe code execution by AI agents. Each sandbox is a fully isolated pod with its -own filesystem, network namespace, and process tree — the agent can run -arbitrary code, install packages, and write files without ever touching the host -or other workloads. - -The implementation is based on -[kubernetes-sigs/agent-sandbox](https://github.com/kubernetes-sigs/agent-sandbox). - ---- - -## Architecture - -``` -Agent (e.g. Coding Agent) - │ - │ HTTP (in-cluster DNS) - ▼ -sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080 - │ - │ creates SandboxClaim CR via Kubernetes API - ▼ - agent-sandbox-controller (agent-sandbox-system namespace) - │ - │ spawns pod from SandboxTemplate spec - ▼ - sandbox-claim- (pod in agent-sandbox-system namespace) - │ - │ NetworkPolicy: allows ingress from app=sandbox-router - │ in the SAME namespace only - ▼ - python-runtime-sandbox — uvicorn on :8888 - POST /execute {"command": "..."} → {stdout, stderr, exit_code} -``` - -**Key design points:** - -- All components live in the **`agent-sandbox-system`** namespace so the - controller-generated `NetworkPolicy` (which allows ingress only from pods - labelled `app=sandbox-router` in the same namespace) applies correctly. -- The **sandbox-router** is the only component that calls the Kubernetes API — - client pods (like the Coding Agent) need no RBAC of their own. -- All images are pulled from **published registries** — no local builds required. - ---- - -## Deployed Components - -| Component | Kind | Namespace | Image Source | -|---|---|---|---| -| `agent-sandbox-controller` | Deployment | `agent-sandbox-system` | `registry.k8s.io/agent-sandbox/agent-sandbox-controller:v1.0.10` | -| CRDs | ClusterScoped | — | `sandboxes`, `sandboxtemplates`, `sandboxclaims`, `sandboxwarmpools` (v1beta1) | -| `sandbox-router` | Deployment (×2) | `agent-sandbox-system` | `registry.k8s.io/agent-sandbox/sandbox-router-go:v1.0.10` | -| `sandbox-router-svc` | Service | `agent-sandbox-system` | ClusterIP :8080 | -| `python-sandbox-template` | SandboxTemplate CR | `agent-sandbox-system` | Uses `registry.k8s.io/agent-sandbox/python-runtime-sandbox:v1.0.10` | - ---- - -## microVM Isolation with Kata Containers (kata-fc / kata-qemu) - -By default a sandbox is an ordinary pod on the `runc` runtime: it is isolated by -namespaces and cgroups, but it **shares the host kernel** with every other -workload on the node. For untrusted, agent-generated code that may not be -enough — a kernel exploit escapes the sandbox. - -[Kata Containers](https://github.com/kata-containers/kata-containers) closes that -gap by booting each pod inside its own lightweight virtual machine with its own -guest kernel. Two runtimes are supported here: - -| RuntimeClass | Hypervisor | Notes | -|---|---|---| -| `kata-fc` | [Firecracker](https://github.com/kata-containers/kata-containers/tree/main/docs/design/arch-images#firecracker) | Minimal device model, ~125 ms boot. Requires the containerd **devmapper** snapshotter. | -| `kata-qemu` | QEMU | Broader device support (e.g. VFIO/device passthrough), heavier boot. Works with the default snapshotter. | - -This follows the upstream -[firecracker-sandbox example](https://agent-sandbox.sigs.k8s.io/docs/use-cases/examples/firecracker-sandbox/), -but reuses the published `python-runtime-sandbox` image so the -`k8s-agent-sandbox` SDK keeps working unchanged — the only difference between -the two templates is `runtimeClassName`. - -### Enable it - -```yaml -# env//config.agent-toolkit.yaml -agent_sandbox_enabled: true # required — Kata is an add-on, not a standalone component - -# env//global_config.yaml -kata_containers_enabled: true -kata_runtime: "kata-fc" # kata-fc | kata-qemu | both -``` - -```yaml -# env//global_config.yaml -kata_version: "3.32.0" # kata-deploy Helm chart version -``` - -Kata is an **add-on to Agent Sandbox**: the `SandboxTemplate` it publishes needs -the agent-sandbox CRDs. With `kata_containers_enabled: true` and -`agent_sandbox_enabled: false` the Kata runtime classes are still installed, but no Kata -sandbox template or pool is created — the rest of the deployment is unaffected. - -### Node prerequisites - -| Requirement | Needed by | Handling | -|---|---|---| -| `/dev/kvm` (Intel VT-x on bare metal, or nested virtualisation on a VM) | both runtimes | `stat`; if missing, the playbook loads `kvm` plus `kvm_intel` (when the CPU exposes the `vmx` flag) and re-checks. If `vmx` is absent the host has no usable virtualisation — warn and skip. | -| containerd **devmapper** snapshotter in `ok` state | `kata-fc` only | **Auto-provisioned.** When `kata_runtime` includes `kata-fc`, the playbook sets up a loopback-backed thin-pool (`/var/lib/containerd/devmapper`, via a `containerd-devmapper.service` systemd unit so it survives reboots) and registers the snapshotter in `/etc/containerd/config.toml`, then restarts containerd — on each KVM-capable node. | - -Firecracker cannot use overlayfs for the container rootfs — it needs the -devmapper snapshotter. Because the kata playbook runs **after** kubespray (which -regenerates `/etc/containerd/config.toml` on every fresh install), the feature -re-applies this configuration itself on every deploy, so `kata-fc` survives -fresh installs and works on brownfield clusters without any manual host setup. -The thin-pool defaults to a 100 GB sparse data file; to back it with a real -block device instead, pre-create a `containerd-thinpool` dm device and the -playbook will reuse it. - -A missing prerequisite stops the Kata step with the fix in its message: - -| Situation | Behaviour | -|---|---| -| No node exposes `/dev/kvm` | Stops: enable VT-x, or set `kata_containers_enabled: false` | -| `kata_runtime` is `kata-fc` or `both` but devmapper is not `ok` on any node | Stops: fix the thin-pool, or set `kata_runtime: kata-qemu` | -| Firecracker is on and devmapper is not `ok` on some nodes | Those nodes are not labelled for Kata (a label left by an earlier run is removed); the run warns and names them | -| `agent_sandbox_enabled: false` | Runtime classes are installed; no Kata sandbox template or pool | -| Invalid `kata_runtime` value | Stops, listing the valid values | - -### What gets installed - -| Resource | Kind | Namespace | -|---|---|---| -| `containerd-thinpool` + `containerd-devmapper.service` | devmapper thin-pool (kata-fc only, per KVM node) | host | -| `kata-deploy` | DaemonSet (upstream Helm chart) | `kube-system` | -| `kata-fc` / `kata-qemu` | RuntimeClass | cluster-scoped | -| `ei-kata-eligible=true` | Node label (only on nodes that passed the preflight) | — | -| `kata-sandbox-template` | SandboxTemplate CR | `agent-sandbox-system` | -| `kata-pool` (size 1) | SandboxWarmPool CR | `agent-sandbox-system` | - -The chart is pulled from -`oci://ghcr.io/kata-containers/kata-deploy-charts/kata-deploy`. `kata-deploy` -installs the Kata binaries, guest kernel and rootfs image onto each node and -restarts containerd there, which is why the rollout wait is generous (15 min). - -The warm pool is created **without** a readiness gate on purpose: a -virtualisation problem on a single node must not hang the stack deployment. -Check it with the verification commands below. - -### Verification - -```bash -kubectl get ds -n kube-system kata-deploy -kubectl get runtimeclass # kata-fc and/or kata-qemu -kubectl get nodes -l ei-kata-eligible=true -kubectl get sandboxtemplate,sandboxwarmpool -n agent-sandbox-system - -# Confirm a sandbox pod really runs on the Kata runtime -kubectl get pod -n agent-sandbox-system -l sandbox=kata \ - -o jsonpath='{.items[0].spec.runtimeClassName}{"\n"}' # kata-fc -``` - -### Use it from the SDK - -Only the warm pool changes: - -```python -sandbox = client.create_sandbox( - warmpool="kata-pool", - namespace="agent-sandbox-system", -) -sandbox.connector.session.headers["Authorization"] = f"Bearer {token}" # see Router token -try: - # A microVM has its own guest kernel — this differs from `uname -r` on the host - print(sandbox.commands.run("uname -r").stdout) -finally: - sandbox.terminate() -``` - -### Troubleshooting - -```bash -# kata-deploy install logs (per node) -kubectl logs -n kube-system -l name=kata-deploy --tail=100 - -# Why a kata sandbox pod is not running -kubectl describe pod -n agent-sandbox-system -l sandbox=kata -``` - -| Symptom | Cause / fix | -|---|---| -| `FailedCreatePodSandBox ... ENOENT` on a `kata-fc` pod | devmapper snapshotter not active on that node — check `systemctl status containerd-devmapper` and `ctr plugins ls \| grep devmapper`, or use `kata_runtime: "kata-qemu"` | -| Sandbox pod stuck `Pending` | No node carries both `ei-kata-eligible=true` and the `katacontainers.io/kata-runtime=true` label that the RuntimeClass selects; check `kubectl get nodes --show-labels` | -| `RuntimeClass 'kata-fc' was not created by kata-deploy` | The chart version does not ship the fc shim — check `kata_version` | -| Pod runs but `uname -r` matches the host | The pod landed on `runc`; confirm `spec.runtimeClassName` on the pod | - -### Cleanup - -```bash -kubectl delete sandboxwarmpool kata-pool -n agent-sandbox-system -kubectl delete sandboxtemplate kata-sandbox-template -n agent-sandbox-system -helm uninstall kata-deploy -n kube-system -``` - -> `kata-deploy` runs a cleanup hook on uninstall that removes the Kata artefacts -> and containerd configuration from each node. - -To also remove the Firecracker devmapper thin-pool from a node (optional): - -```bash -sudo systemctl disable --now containerd-devmapper.service -sudo rm -f /etc/systemd/system/containerd-devmapper.service /usr/local/bin/containerd-devmapper-setup.sh -sudo dmsetup remove containerd-thinpool -sudo rm -rf /var/lib/containerd/devmapper -# remove the "kata devmapper snapshotter (managed)" block from /etc/containerd/config.toml, then: -sudo systemctl restart containerd -``` - ---- - -## Configuration - -### Enable in `env//config.agent-toolkit.yaml` - -```yaml -agent_sandbox_enabled: true -``` - -Set to `false` to skip deployment. On re-runs, if the `agent-sandbox-system` namespace -already exists the deployment is automatically skipped (resume mode). - -> **Note:** resume mode is not available in this release. - -### Version pin in `env//config.agent-toolkit.yaml` - -```yaml -agent_sandbox_version: "v1.0.10" -``` - -This controls the version of official release manifests fetched from GitHub and -the image tags used for the runtime components. Update the version here to upgrade. - ---- - -## Deployment - -Agent Sandbox is deployed as part of the standard stack run using **Ansible**: - -```bash -# env//config.agent-toolkit.yaml -agent_sandbox_enabled: true - -./es_auto_installer.sh install agent-toolkit -``` - -The Ansible playbook runs 7 task groups: - -| Task Group | Action | -|---|---| -| 1 | Prerequisites — Verify kubectl and cluster connectivity | -| 2 | Install core components via official manifest (CRDs + controller) | -| 3 | Wait for controller readiness | -| 4 | Deploy sandbox-router with staging image | -| 5 | Apply default SandboxTemplate and create default WarmPool (`python-pool`, size 5) | -| 6 | Final verification (pods ready, v1beta1 API available) | -| 7 | Cleanup temporary files | - - -## Verification - -```bash -# All components should be Running -kubectl get pods -n agent-sandbox-system - -# Confirm CRDs are registered (should show v1beta1) -kubectl get crd sandboxes.agents.x-k8s.io -o jsonpath='{.spec.versions[*].name}' -# Expected: v1beta1 - -# Check the SandboxTemplate exists -kubectl get sandboxtemplate -n agent-sandbox-system -# Expected: python-sandbox-template - -# Check default WarmPool exists -kubectl get sandboxwarmpool -n agent-sandbox-system python-pool -# Expected: SIZE=5 and READY=5 - -# Verify controller deployment -kubectl get deployment -n agent-sandbox-system agent-sandbox-controller - -# Verify router deployment -kubectl get deployment -n agent-sandbox-system sandbox-router - -# Quick end-to-end health check via the router -kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 & -curl -s http://localhost:8080/healthz -# {"status":"ok"} -``` - ---- - -## Default SandboxTemplate - -The stack ships one template out of the box: -`charts/agent-sandbox/default-templates.yaml` - -```yaml -apiVersion: extensions.agents.x-k8s.io/v1beta1 -kind: SandboxTemplate -metadata: - name: python-sandbox-template - namespace: agent-sandbox-system -spec: - service: true # headless Service created per pod — required for SDK DNS mode - podTemplate: - spec: - containers: - - name: runtime - image: registry.k8s.io/agent-sandbox/python-runtime-sandbox:v1.0.10 - imagePullPolicy: IfNotPresent - ports: - - name: api - containerPort: 8888 - protocol: TCP - resources: - requests: { cpu: "250m", memory: "256Mi" } - limits: { cpu: "1000m", memory: "1Gi" } - securityContext: - allowPrivilegeEscalation: false - runAsNonRoot: true - runAsUser: 1000 - capabilities: - drop: [ALL] -``` - -The `python-runtime-sandbox` image exposes a FastAPI server on port 8888: - -``` -POST /execute -Body: {"command": ""} -Response: {"stdout": "...", "stderr": "...", "exit_code": 0} -``` - ---- - -## Adding a Custom SandboxTemplate - -You can add any number of templates for different runtimes (Node.js, R, Java, -etc.) by creating a new `SandboxTemplate` CR. - -### 1. Build and push your runtime image - -The runtime image must expose: -- `POST /execute` → `{stdout, stderr, exit_code}` — same API as `python-runtime-sandbox` - -For production deployments, push to your registry: - -```bash -docker build -t your-registry.io/my-node-sandbox:v1.0 ./path/to/dockerfile-dir -docker push your-registry.io/my-node-sandbox:v1.0 -``` - -For local (no-registry) development with Kind/Minikube, load into cluster: - -```bash -# Kind -kind load docker-image your-registry.io/my-node-sandbox:v1.0 - -# Minikube -minikube image load your-registry.io/my-node-sandbox:v1.0 -``` - -### 2. Create the SandboxTemplate manifest - -```yaml -apiVersion: extensions.agents.x-k8s.io/v1beta1 -kind: SandboxTemplate -metadata: - name: node-sandbox-template - namespace: agent-sandbox-system # must match the namespace where sandboxes will be created -spec: - service: true - podTemplate: - metadata: - labels: - # Keep sandboxes outside the ambient mesh, or their NetworkPolicy is not enforced - istio.io/dataplane-mode: none - spec: - containers: - - name: runtime - image: your-registry.io/my-node-sandbox:v1.0 - imagePullPolicy: IfNotPresent # or Always for frequent updates - ports: - - name: api - containerPort: 8888 - protocol: TCP - resources: - requests: { cpu: "250m", memory: "256Mi" } - limits: { cpu: "1000m", memory: "1Gi" } - securityContext: - allowPrivilegeEscalation: false - runAsNonRoot: true - runAsUser: 1000 - capabilities: - drop: [ALL] -``` - -### 3. Apply it - -```bash -kubectl apply -f node-sandbox-template.yaml -kubectl get sandboxtemplate -n agent-sandbox-system -``` - -### 4. Use it from the SDK - -The v1.0.10 SDK starts sandboxes from a warm pool, so add one for the template: - -```bash -kubectl apply -f - <<'EOF' -apiVersion: extensions.agents.x-k8s.io/v1beta1 -kind: SandboxWarmPool -metadata: - name: node-pool - namespace: agent-sandbox-system -spec: - replicas: 1 - sandboxTemplateRef: - name: node-sandbox-template -EOF -``` - -```python -sandbox = client.create_sandbox( - warmpool="node-pool", - namespace="agent-sandbox-system", -) -sandbox.connector.session.headers["Authorization"] = f"Bearer {token}" # see Router token -``` - ---- - -## Using the SDK (`k8s-agent-sandbox`) - -Install the **v1.0.10** SDK: - -```bash -pip install k8s-agent-sandbox==1.0.10 -``` - -> **Note**: v1.0.10 SDK is required for v1.0.10 agent-sandbox deployments due to API changes. - -Official documentation: https://github.com/kubernetes-sigs/agent-sandbox/tree/main/clients/python/agentic-sandbox-client - -### Router token - -The sandbox router accepts only calls that carry a Kubernetes ServiceAccount token, and answers `401` to the rest. Any ServiceAccount token in the cluster is accepted: - -```bash -export ROUTER_AUTH_TOKEN=$(kubectl create token default -n agent-sandbox-system) -``` - -The SDK has no router token setting. Add it to the sandbox's HTTP session right after `create_sandbox`, as the examples below do: - -```python -token = os.environ["ROUTER_AUTH_TOKEN"] -sandbox.connector.session.headers["Authorization"] = f"Bearer {token}" -``` - -`commands.run()` starts the command without a shell. For `&&`, `|` or redirects, wrap the command in `sh -c "..."`. - -### Network access from sandboxes - -Sandbox code reaches public addresses only. Private ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`), the node, the Kubernetes API and cluster services are blocked, for Kata sandboxes too. Sandboxes resolve names through public DNS (`8.8.8.8`, `1.1.1.1`) and get no proxy settings, so on a network that blocks direct DNS or requires a proxy they have no outbound access. - -### From outside the cluster (development / local testing) - -Use **Tunnel Mode** — the SDK opens a `kubectl port-forward` automatically, or -you can port-forward manually and use **Direct Mode**. - -**Option A — Tunnel Mode (auto port-forward):** - -```python -import os - -from k8s_agent_sandbox import SandboxClient -from k8s_agent_sandbox.models import SandboxLocalTunnelConnectionConfig - -client = SandboxClient( - connection_config=SandboxLocalTunnelConnectionConfig( - router_namespace="agent-sandbox-system" - ) -) - -sandbox = client.create_sandbox( - warmpool="python-pool", - namespace="agent-sandbox-system", -) -sandbox.connector.session.headers["Authorization"] = f"Bearer {os.environ['ROUTER_AUTH_TOKEN']}" -try: - result = sandbox.commands.run("python3 --version") - print(result.stdout) -finally: - sandbox.terminate() -``` - -**Option B — Direct Mode (manual port-forward):** - -```bash -# Terminal 1 — keep port-forward running -kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 -``` - -```python -import os - -from k8s_agent_sandbox import SandboxClient -from k8s_agent_sandbox.models import SandboxDirectConnectionConfig - -client = SandboxClient( - connection_config=SandboxDirectConnectionConfig( - api_url="http://localhost:8080" - ) -) - -sandbox = client.create_sandbox( - warmpool="python-pool", - namespace="agent-sandbox-system", -) -sandbox.connector.session.headers["Authorization"] = f"Bearer {os.environ['ROUTER_AUTH_TOKEN']}" -try: - result = sandbox.commands.run("echo 'Hello from Agent Sandbox!'") - print(result.stdout) # Hello from Agent Sandbox! - - # No shell by default: wrap && and pipes in sh -c - result = sandbox.commands.run("sh -c \"echo shell-ok && echo piped | tr a-z A-Z\"") - print(result.stdout) # shell-ok / PIPED -finally: - sandbox.terminate() -``` - -### From inside the cluster (agent pods) - -Use **Direct Mode** with the sandbox-router's in-cluster DNS URL. -No RBAC changes are needed — the router handles all Kubernetes API calls. -With Istio on, run the agent in a namespace labelled `istio.io/dataplane-mode=ambient`: the router is in the mesh with strict mTLS and refuses plain-text callers. - -```python -import os - -from k8s_agent_sandbox import SandboxClient -from k8s_agent_sandbox.models import SandboxDirectConnectionConfig - -client = SandboxClient( - connection_config=SandboxDirectConnectionConfig( - api_url="http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080" - ) -) - -sandbox = client.create_sandbox( - warmpool="python-pool", - namespace="agent-sandbox-system", -) -sandbox.connector.session.headers["Authorization"] = f"Bearer {os.environ['ROUTER_AUTH_TOKEN']}" -try: - result = sandbox.commands.run("python3 -c \"print('Hello from in-cluster sandbox!')\"") - print(result.stdout) -finally: - sandbox.terminate() -``` - -This is exactly how an agent using the sandbox executes code. - -### Session sandbox pattern (stateful across calls) - -For agents that need state to persist across multiple tool invocations -(installed packages, defined variables), create the sandbox once and reuse it: - -```python -import os - -from k8s_agent_sandbox import SandboxClient -from k8s_agent_sandbox.models import SandboxDirectConnectionConfig - -_client = SandboxClient( - connection_config=SandboxDirectConnectionConfig( - api_url="http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080" - ) -) -_sandbox = None - -def get_sandbox(): - global _sandbox - if _sandbox is None or not _sandbox.is_active: - _sandbox = _client.create_sandbox( - warmpool="python-pool", - namespace="agent-sandbox-system", - ) - _sandbox.connector.session.headers["Authorization"] = f"Bearer {os.environ['ROUTER_AUTH_TOKEN']}" - return _sandbox - -# First call — installs package -get_sandbox().commands.run("pip install pandas") - -# Second call — package is still available -result = get_sandbox().commands.run("python3 -c 'import pandas; print(pandas.__version__)'") -print(result.stdout) - -# Clean up -get_sandbox().terminate() -_sandbox = None -``` - ---- - -## WarmPools (pre-warmed sandboxes) - -WarmPools keep a set of sandbox pods pre-created and idle so agents receive a -sandbox instantly without waiting for pod scheduling and image pull. - -```yaml -apiVersion: extensions.agents.x-k8s.io/v1beta1 -kind: SandboxWarmPool -metadata: - name: python-pool - namespace: agent-sandbox-system - labels: - app: python-pool -spec: - replicas: 3 # number of pre-warmed pods to maintain - sandboxTemplateRef: - name: python-sandbox-template # must exist in the same namespace -``` - -Apply: - -```bash -kubectl apply -f warmpool.yaml -kubectl get sandboxwarmpool -n agent-sandbox-system -# NAME SIZE READY -# python-pool 5 5 -``` - -When an agent calls `create_sandbox`, the controller assigns a pre-warmed pod -immediately and refills the pool in the background. - -> WarmPool support is enabled by default via the official extensions manifest. - ---- - -## Re-run Safety - -| Operation | Behaviour | -|---|---| -| `agent_sandbox_enabled: true` on a running stack | Ansible playbook is idempotent; manifests are re-applied with `kubectl apply` (safe for upgrades) | -| Namespace already exists | Ansible creates namespace with `state: present` (idempotent) | -| Controller already running | Kubernetes applies manifests declaratively (no duplication) | -| Re-run | `./es_auto_installer.sh install agent-toolkit` again re-applies everything in place; running components are kept | - ---- - -## Troubleshooting - -### Pods not starting - -```bash -# Check pod status -kubectl get pods -n agent-sandbox-system - -# Check controller logs -kubectl logs -n agent-sandbox-system -l app.kubernetes.io/name=agent-sandbox - -# Check router logs -kubectl logs -n agent-sandbox-system -l app=sandbox-router - -# Describe failed pod -kubectl describe pod -n agent-sandbox-system -``` - -### Image pull errors - -If using published images, ensure cluster has internet access: - -```bash -# Test image pull -kubectl run test --rm -it --restart=Never --image=registry.k8s.io/agent-sandbox/python-runtime-sandbox:v1.0.10 -- echo "success" -``` - -For air-gapped environments, mirror images to your private registry and update variables in `env//config.agent-toolkit.yaml`. - -### SDK connection errors - -```bash -# Verify router is running -kubectl get svc -n agent-sandbox-system sandbox-router-svc - -# Test router health -kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 & -curl http://localhost:8080/healthz - -# Check NetworkPolicy -kubectl get networkpolicy -n agent-sandbox-system -``` - ---- - -## Configuration Files - -### Variables - -`env//config.agent-toolkit.yaml`: -```yaml -agent_sandbox_namespace: "agent-sandbox-system" -agent_sandbox_router_image: "registry.k8s.io/agent-sandbox/sandbox-router-go:v1.0.10" -agent_sandbox_python_runtime_image: "registry.k8s.io/agent-sandbox/python-runtime-sandbox:v1.0.10" -``` - -Kata settings (`roles/kata_containers/defaults/main.yaml` in enterprise-ai-solutions, and the toolkit's `roles/agent_sandbox/defaults/main.yaml`): -```yaml -kata_namespace: "kube-system" -kata_chart_ref: "oci://ghcr.io/kata-containers/kata-deploy-charts/kata-deploy" -kata_node_label_key: "ei-kata-eligible" -kata_sandbox_template_name: "kata-sandbox-template" -kata_warm_pool_size: 1 -``` - -### Deployment Script - -- **Role**: `roles/agent_sandbox/tasks/install.yaml` (Intel® Agent Toolkit) -- **Kata role**: `roles/kata_containers` (enterprise-ai-solutions, infrastructure layer) - -### Templates - -- **Default SandboxTemplate**: `charts/agent-sandbox/default-templates.yaml` -- **Kata SandboxTemplate**: `charts/agent-sandbox/kata-templates.yaml` -- **kata-deploy chart values**: `core/helm-charts/kata-deploy/values.yaml` - ---- - -## References - -- [kubernetes-sigs/agent-sandbox](https://github.com/kubernetes-sigs/agent-sandbox) — upstream controller -- [v1.0.10 Release Notes](https://github.com/kubernetes-sigs/agent-sandbox/releases/tag/v1.0.10) -- [v1.0.10 Migration Guide](https://github.com/kubernetes-sigs/agent-sandbox/blob/v1.0.10/docs/api-migration-guide.md) -- [k8s-agent-sandbox Python SDK README](https://github.com/kubernetes-sigs/agent-sandbox/tree/main/clients/python/agentic-sandbox-client/README.md) -- [PyPI: k8s-agent-sandbox](https://pypi.org/project/k8s-agent-sandbox/) -- [Agent Sandbox Documentation](https://agent-sandbox.sigs.k8s.io/docs/) -- [Firecracker sandbox example](https://agent-sandbox.sigs.k8s.io/docs/use-cases/examples/firecracker-sandbox/) — upstream microVM walkthrough -- [kata-containers/kata-containers](https://github.com/kata-containers/kata-containers) — Kata Containers runtime -- [Kata architecture: Firecracker](https://github.com/kata-containers/kata-containers/tree/main/docs/design/arch-images#firecracker) — fc shim design and devmapper requirement -- [kata-deploy Helm chart](https://github.com/kata-containers/kata-containers/tree/main/tools/packaging/kata-deploy/helm-chart) — chart values reference diff --git a/docs/assets/agent-toolkit-architecture.png b/docs/assets/agent-toolkit-architecture.png new file mode 100644 index 00000000..93ac544b Binary files /dev/null and b/docs/assets/agent-toolkit-architecture.png differ diff --git a/docs/assets/banner.jpg b/docs/assets/banner.jpg new file mode 100644 index 00000000..59b776e1 Binary files /dev/null and b/docs/assets/banner.jpg differ diff --git a/docs/assets/overview.png b/docs/assets/overview.png new file mode 100644 index 00000000..f2393d9d Binary files /dev/null and b/docs/assets/overview.png differ diff --git a/docs/assets/vllm-sr-flow.html b/docs/assets/vllm-sr-flow.html new file mode 100644 index 00000000..13c73044 --- /dev/null +++ b/docs/assets/vllm-sr-flow.html @@ -0,0 +1,238 @@ + + + + + +vLLM Semantic Router: Request Flow + + + +
+
+
Intel® Agent Toolkit
+

Intelligent Inference Routing

+

How a single request is authenticated, routed to the best model, and returned

+
+ +
+ + +
+
+
1
+
+

Client

+
Any application, agent, or framework
+
+
+
    +
  • Sends one chat request over HTTPS: no need to know which model will serve it
  • +
+
+ +
+
HTTPS · external
+
+
+ + +
+
+
2
+
+

LiteLLM GenAI Gateway

+
Single secure entry point & policy layer
+
+
+
    +
  • Authenticates the request
  • +
  • Starts a Langfuse trace
  • +
  • model = vllm-sr/auto triggers routing
  • +
  • Tracks spend & usage
  • +
+
+ +
+
route
+
+
+ + +
+
+
3
+
+

vLLM Semantic Router

+
Decides the right model for the task
+
+
+
    +
  • Extracts semantic signals from the prompt
  • +
  • Evaluates routing decisions
  • +
  • Selects the best model
  • +
  • Routes to the chosen backend
  • +
+
+ +
+
dispatch
+
+
+ + +
+
+
4
+
+

Model Backend

+
Local vLLM on Intel® Xeon®, Bedrock, OpenAI, and more
+
+
+
    +
  • Runs inference and produces the response
  • +
+
+ + +
+ + Response flows back through the chain to the client: one API, best model chosen automatically +
+ +
+ +
+ Every step (routing decision, model choice, latency, tokens, and cost) is captured in Langfuse for full visibility. +
+
+ + diff --git a/docs/backend-connection-reference.md b/docs/backend-connection-reference.md deleted file mode 100644 index 1382e1f1..00000000 --- a/docs/backend-connection-reference.md +++ /dev/null @@ -1,106 +0,0 @@ -# Backend Connection Reference — Intel® Agent Toolkit - -All shared backends are deployed into their own namespaces and are reachable from any workload namespace in the cluster labelled `istio.io/dataplane-mode=ambient` (the toolkit namespaces run in the Istio ambient mesh with strict mTLS). - -## Redis (Session Memory & Caching) - -| Instance | Kubernetes Service | URL | Scope | -|---|---|---|---| -| **Redis Stack** (`redis_stack_enabled: true`) | `redis-stack-server.redis.svc.cluster.local:6379` (ClusterIP) | `redis://default:@redis-stack-server.redis.svc.cluster.local:6379` | All namespaces (in-cluster only) | - -Redis requires a password. The credentials and the full URL are stored in the `redis-stack-server-credentials` Secret: - -```bash -# Full connection URL (preferred — do not hardcode the password) -kubectl get secret redis-stack-server-credentials -n redis \ - -o jsonpath='{.data.REDIS_URL}' | base64 -d - -# Password only -kubectl get secret redis-stack-server-credentials -n redis \ - -o jsonpath='{.data.REDIS_PASSWORD}' | base64 -d - -# Quick connectivity test -kubectl exec -n redis redis-stack-server-0 -- sh -c \ - 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning ping' -# PONG -``` - -> The `default:` username in the URL is required — Redis 6+ rejects the `redis://:@...` form with `WRONGPASS`. -> The Service is `ClusterIP` and a NetworkPolicy is applied; Redis is not reachable from outside the cluster. Use `kubectl port-forward` for local access instead of changing the Service type. - -## Agent Sandbox (Sandboxed Execution) - -Enabled with `agent_sandbox_enabled: true` (default) in `env//config.agent-toolkit.yaml`. See [agent-sandbox.md](agent-sandbox.md) for full details. - -| Resource | Value | -|---|---| -| **Namespace** | `agent-sandbox-system` | -| **Router service** | `sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080` | -| **SDK** | `pip install k8s-agent-sandbox` | -| **Default template** | `python-sandbox-template` (namespace: `agent-sandbox-system`) | - -```bash -# Quick health check (requires port-forward or in-cluster) -kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 & -curl -s http://localhost:8080/healthz -# {"status":"ok"} -``` - -## OpenShell (Policy-Enforced Sandboxes) - -Enabled with `openshell_enabled: true` (requires `agent_sandbox_enabled: true`). See [openshell.md](openshell.md) for full details. - -| Resource | Value | -|---|---| -| **Gateway namespace** | `openshell-system` | -| **Gateway service** | `openshell.openshell-system.svc.cluster.local:8080` (gRPC, mTLS) | -| **Sandbox namespace** | `openshell-sandboxes` | -| **Client mTLS bundle** | Secret `openshell-client-tls` in `openshell-system` | -| **CLI** | [OpenShell v0.1.6 release](https://github.com/NVIDIA/OpenShell/releases/tag/v0.1.6) | -| **GenAI provider** | `genai-gateway` (attach with `openshell sandbox create --provider genai-gateway`) | - -```bash -# Admin access (ClusterIP only) -kubectl port-forward -n openshell-system svc/openshell 8080:8080 & -``` - -## PostgreSQL + pgvector (Vector Store & Long-Term Memory) - -Enabled with `pgvector_enabled: true` (default). See [README.md](README.md#step-2b--postgresql--pgvector-vector-store--long-term-memory) for deployment details. - -| Resource | Value | -|---|---| -| **Namespace** | `pgvector` | -| **Host** | `pgvector.pgvector.svc.cluster.local` | -| **Port** | `5432` | -| **Database** | `agentdb` | -| **User** | `agentuser` | -| **Connection string** | `postgresql://agentuser:@pgvector.pgvector.svc.cluster.local:5432/agentdb` | -| **Credentials secret** | `kubectl get secret pgvector-credentials -n pgvector -o jsonpath='{.data.DATABASE_URL}' \| base64 -d` | - -## KubeRay (Distributed Computing) - -Enabled with `kuberay_enabled: true`. Tuned via the `kuberay_*` settings in `env//config.agent-toolkit.yaml` (e.g. `kuberay_worker_replicas`). See [kuberay.md](kuberay.md) for the full guide. - -| Resource | Value | -|---|---| -| **Namespace** | `ray-system` *(default; set via `kuberay_namespace`)* | -| **Ray Client API** | `ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001` | -| **Ray Dashboard** | `http://ray-cluster-head-svc.ray-system.svc.cluster.local:8265` | -| **Dashboard (local)** | `kubectl port-forward svc/ray-cluster-head-svc 8265:8265 -n ray-system` | - -```bash -# Verify all Ray pods are Running -kubectl get pods -n ray-system - -# Quick Python connectivity test (from inside the cluster or via port-forward) -python3 -c " -import ray -ray.init('ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001') -print(ray.cluster_resources()) -" -``` - -## Flowise (Agent Builder) - -Flowise is not part of this release. \ No newline at end of file diff --git a/docs/configuration/configuration.md b/docs/configuration/configuration.md new file mode 100644 index 00000000..a13019ad --- /dev/null +++ b/docs/configuration/configuration.md @@ -0,0 +1,132 @@ +# Configuration + +[← Docs index](../README.md) + +After `init`, configuration lives as several YAML files under `env//` (the default name is `local`). You edit those files, then run `install`. There is no single INI file. Secrets (Redis password, gateway keys, and so on) are generated by the installer; do not put them in git. + +```bash +./toolkit_manager.sh init agent-toolkit --env +``` + +Omit `--env` to use `local`. + +## The files + +These are the files `init` writes under `env/local/`. Change the copies here; they are what `install` reads. + +| File | What it is for | +|---|---| +| `global_config.yaml` | Cluster-wide: domain, TLS, storage, proxy, bring-your-own kubeconfig | +| `config.inference.yaml` | Inference layer: which routers to install, and guardrail flags | +| `models.yaml` | Catalog of model names, Hugging Face ids, CPU, and memory. Deploy with `llm_services_autodeploy_models` or `./model-manager deploy ` | +| `config.agent-toolkit.yaml` | Toolkit knobs: auth, models, namespaces, Redis, pgvector, sandbox, KubeRay | +| `nodes.yaml` | Which nodes are in the cluster (`nodes_control_plane`, `nodes_workers`). Install regenerates `inventory/hosts.yaml` from it | + +### `global_config.yaml` + +```yaml +base_domain_name: inteltoolkits.ai +gateway_tls_mode: selfsigned # selfsigned | custom +# gateway_tls_mode: custom +# gateway_tls_cert_file: /path/to/cert.pem +# gateway_tls_key_file: /path/to/key.pem +# existing_kubernetes: /path/to/kubeconfig # omit to let the installer create Kubernetes +storage_backend: local-path # local-path | nfs | ceph | netapp-trident | custom +# object_store_backend: seaweedfs # S3 store for Loki, Tempo, and Langfuse: seaweedfs | external +# http_proxy: http://proxy.corporate.com:8080 +# https_proxy: http://proxy.corporate.com:8080 +# no_proxy: localhost,127.0.0.1,.svc,.cluster.local +``` + +| Setting | Effect | +|---|---| +| `base_domain_name` | Public hostname of the API. Must match DNS/`/etc/hosts` and the certificate. | +| `gateway_tls_mode` | `selfsigned` for a lab. `custom` plus cert/key paths for the cert from [Prerequisites](../getting-started/prerequisites.md). | +| `existing_kubernetes` | Path to a kubeconfig if the cluster already exists. Omit to provision Kubernetes. | +| `storage_backend` | Where PVCs go. `local-path` on one node; `nfs`, `ceph`, `netapp-trident`, or `custom` on several. NetApp: [NetApp ONTAP](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/netapp-ontap.md) in Toolkit Manager | +| `object_store_backend` | S3 store for Loki, Tempo, and Langfuse. Default `seaweedfs`; use `external` for your own S3 endpoint | +| `http_proxy` / `https_proxy` / `no_proxy` | [Corporate proxy](../deployment/proxy.md). `no_proxy` must include `.svc` and `.cluster.local`. | +| `kubernetes_cluster_cidr` | Pod CIDR of a bring-your-own cluster. Set this when OpenShell is on so LiteLLM can admit sandbox traffic from that range. | + +#### API sign-in (`auth_type`) + +Set `auth_type` in `config.agent-toolkit.yaml` (or `config.inference.yaml`). `init agent-toolkit` seeds `auth_type: litellm_vkey`. Leave that default for the LiteLLM gateway, Langfuse traces, and the content-safety guardrail. Set `auth_type: jwt` for Keycloak JWT on the Envoy AI gateway instead. + +| You want | Set | +|---|---| +| LiteLLM virtual keys (default) | `auth_type: litellm_vkey` | +| Keycloak JWT on the AI gateway | `auth_type: jwt` | + +`config.agent-toolkit.yaml` loads **after** `config.inference.yaml`, so `auth_type`, `guardrails_enabled`, `hybrid_router_enabled`, and the `litellm_*` keys here override the inference layer. + +Legacy: `auth_provider` in `global_config.yaml` (`litellm` / `keycloak`) is deprecated and mapped to `auth_type`. Prefer `auth_type` only; if both are set they must agree or preflight fails. + +### `config.inference.yaml` + +This file turns inference routers (and related guardrail flags) on or off. **Which chat models deploy is not here.** Put those names in `llm_services_autodeploy_models` in `config.agent-toolkit.yaml`. Routing (optional virtual model names) is covered in [Routing](routing.md). + +```yaml +hybrid_router_enabled: true # virtual model hybrid-router — see Hybrid router +# vllm_sr_enabled: false # opt-in — see vLLM semantic router +``` + +Details: [Hybrid router](hybrid-router.md), [vLLM semantic router](semantic-router.md). + +### `models.yaml` + +This file is the catalog. A name in `llm_services_autodeploy_models` must match a `name` here. Per-model CPU and memory are set on the same entry. There is no `autodeploy` flag. + +### `config.agent-toolkit.yaml` + +```yaml +auth_type: litellm_vkey # litellm_vkey | jwt +llm_services_autodeploy_models: ["qwen2-5-coder-14b"] +redis_stack_enabled: true +pgvector_enabled: true +agent_sandbox_enabled: true +kuberay_enabled: false +openshell_enabled: false +``` + +| Setting | Default | Meaning | +|---|---|---| +| `auth_type` | `litellm_vkey` | API sign-in. Leave the default for LiteLLM; set `jwt` for Keycloak on the AI gateway | +| `llm_services_autodeploy_models` | `["qwen2-5-coder-14b"]` | Models deployed during `install`. `[]` installs with no chat model. Deploy others later with `./model-manager deploy ` | +| `guardrails_enabled` | on when `auth_type` is `litellm_vkey` | Set `false` to keep LiteLLM but turn off content-safety screening. [Guardrails](guardrails.md) | +| `hybrid_router_enabled` | `true` | Creates the `hybrid-router` virtual model. Overrides the same key in `config.inference.yaml`. [Hybrid router](hybrid-router.md) | +| `litellm_public_paths` | `[]` | Paths published on LiteLLM’s route. Empty means all paths (admin UI and key API stay LiteLLM-authenticated) | +| `litellm_allow_pod_network` | follows `openshell_enabled` | When OpenShell is on, LiteLLM admits API calls from the pod network. [OpenShell](../reference/openshell.md) | +| `litellm_allowed_namespaces` | gateway, litellm, sandbox, kuberay | Namespaces LiteLLM admits on the mesh. Add your own ambient-labelled agent namespace here | +| `node_preflight_enabled` | `true` | Runs `playbooks/preflight-check.yml` at the start of install (report only). [Validate](../faq-and-troubleshooting/validate.md) | +| `redis_stack_namespace` | `redis` | Namespace for Redis Stack | +| `redis_stack_storage_class` | `""` | PVC StorageClass. Empty uses the cluster default | +| `redis_stack_persistence_size` | `10Gi` | Redis PVC size | +| `pgvector_namespace` | `pgvector` | Namespace for PostgreSQL + pgvector | +| `pgvector_database` / `pgvector_username` | `agentdb` / `agentuser` | Database and role | +| `pgvector_storage_size` | `20Gi` | pgvector PVC size | +| `pgvector_storage_class` | `""` | PVC StorageClass. Empty uses the cluster default | +| `agent_sandbox_namespace` | `agent-sandbox-system` | Sandbox operator and pods | +| `agent_sandbox_python_warm_pool_size` | `5` | Pre-warmed sandbox pods. Costs CPU/RAM on install; `0` disables. [Agent sandbox](../reference/agent-sandbox.md) | +| `kuberay_enabled` | `false` | Set `true` to install Ray. [KubeRay](../reference/kuberay.md) | +| `redis_stack_enabled` / `pgvector_enabled` / `agent_sandbox_enabled` | `true` | Set `false` to skip that component | +| `openshell_enabled` | `false` | Policy layer on the agent sandbox. [OpenShell](../reference/openshell.md) | +| `keycloak_agent_config_enabled` | on by default | Creates the `agent-toolkit` realm on the platform Keycloak. The enable condition still keys off legacy `auth_provider` (unset counts as Keycloak), so the realm installs even when `auth_type` is `litellm_vkey`. Set `false` to skip it | +| `keycloak_agent_realm` | `agent-toolkit` | Realm name | + +Source defaults (copied at `init`): `config.yaml` at the root of this repo. + +## Hugging Face token + +The Hugging Face token is not stored in YAML. Export it in the same shell that runs `install`: + +```bash +export HF_TOKEN=hf_... +``` + +Skip this if every model in `llm_services_autodeploy_models` is ungated, or if that list is `[]`. The default `qwen2-5-coder-14b` is ungated. + +Related paths (not required for the first install): [Rack-scale](../deployment/rack-scale.md), [Intel® Arc™ GPU](../deployment/intel-arc.md), Kata options in [Agent sandbox](../reference/agent-sandbox.md#kata-containers), and [Docker Compose](../deployment/docker.md). + +## Next steps + +After you change YAML, re-run `./toolkit_manager.sh install agent-toolkit`. The toolkit roles (Redis, pgvector, sandbox, KubeRay, OpenShell) upgrade on every run, so their settings take effect without a teardown. The [single-node quickstart](../getting-started/quickstart.md) shows a first working set of values. In-cluster URLs for Redis, pgvector, and the sandbox are in the [backend connection reference](../reference/backend-connections.md). Content-safety screening is covered in [Guardrails](guardrails.md). Virtual model names are covered in [Routing](routing.md). To remove the agent layer and install again, see [Decommission and redeploy](../deployment/decommission.md). If install fails, see [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md). diff --git a/docs/configuration/guardrails.md b/docs/configuration/guardrails.md new file mode 100644 index 00000000..9c34c04d --- /dev/null +++ b/docs/configuration/guardrails.md @@ -0,0 +1,344 @@ +# Guardrails + +[← Docs index](../README.md) + +Guardrails screen each chat request with a small safety model **before** the main language model sees it. Unsafe prompts are blocked; safe prompts continue unchanged. Use them when the gateway is exposed to users whose prompts you do not control. + +Guardrails are not a separate installer target. They turn on with LiteLLM (`auth_type: litellm_vkey`) because LiteLLM hosts and runs the screening logic. To keep LiteLLM but skip screening, set `guardrails_enabled: false` in `env/local/config.agent-toolkit.yaml` (that file overrides `config.inference.yaml`). Two pieces work together: + +| Piece | What it is | +|---|---| +| **Guard model** | The `qwen3guard` catalog entry (Hugging Face id `Qwen/Qwen3Guard-Gen-0.6B`): a small CPU model. With default `auth_type: litellm_vkey`, install deploys it from `models.yaml`. To deploy it yourself later: `./model-manager deploy qwen3guard`. | +| **`content_safety` guardrail** | A `custom_code` guardrail registered with LiteLLM through its `/guardrails` API: sandboxed Python, compiled with RestrictedPython, that runs on LiteLLM's `pre_call` hook and calls the guard model over HTTP. | + +The guardrail is always registered as `content_safety`, whatever guard model is deployed. Swapping the guard model changes only the model behind it, so no registration is left stranded. The model in use is baked into the registered code and shown in the guardrail's description in the LiteLLM UI. + +> **A blocked request is not an error response.** LiteLLM returns **HTTP 200** with `finish_reason: "content_filter"` and the block reason as the assistant message. This is fixed behavior for `custom_code` guardrails, not a setting. A client that detects blocks by a non-2xx status will read a block as a normal answer: check `finish_reason` instead. + +## 1. Turn guardrails on + +Prerequisites: + +- `auth_type: litellm_vkey`. LiteLLM holds the guardrail registration. +- Free CPU and memory for the `qwen3guard` guard model (`cpu` and `memory` in its `models.yaml` entry). + +Set API sign-in in `env/local/config.agent-toolkit.yaml`, then install: + +```yaml +# env/local/config.agent-toolkit.yaml +auth_type: litellm_vkey # content_safety on with LiteLLM; set jwt for Keycloak without this guardrail +# guardrails_enabled: false # LiteLLM stays; screening off +``` + +```bash +./toolkit_manager.sh configure +./toolkit_manager.sh init agent-toolkit +./toolkit_manager.sh install agent-toolkit +``` + +| Setting | Result | +|---|---| +| `auth_type: litellm_vkey` (and `guardrails_enabled` left at default) | Every chat request is screened by `content_safety` before it reaches the main LLM. The `qwen3guard` model deploys from `models.yaml`, and the guardrail is registered as part of the agent-toolkit layer. | +| `guardrails_enabled: false` with LiteLLM still on | Gateway and keys stay; no content moderation. | +| `auth_type: jwt` | The content-safety guardrail is not registered with LiteLLM. | + +The install registers the guardrail and returns without waiting for the guard pod. Until that pod is `Running`, every screened request is blocked (see [Fail-closed behavior](#fail-closed-behavior)). + + + +**Re-registering.** Re-running `./toolkit_manager.sh install agent-toolkit` renders the code again and updates the existing registration in place (`PUT /guardrails/{id}`). That re-initializes the in-memory guardrail without a LiteLLM restart, so an edited template or a different guard model takes effect on the next request. + +## 2. Settings + +### Guard model + +The guard is the `qwen3guard` entry in `models.yaml`. When the entry is absent, the default `Qwen/Qwen3Guard-Gen-0.6B` applies. The model selects both the model served for screening and the code template that parses its verdicts. + +| Guard model | Code template | Status | +|---|---|---| +| `Qwen/Qwen3Guard-Gen-0.6B` | `qwen3guard_gen` | Supported (default) | + +A guard model with no matching template **fails the install before anything is deployed**, and the error lists the supported ids. + +### Guard endpoint and policy + +These values are substituted into the code at deploy time. The template itself never needs editing. + +| Field | Default | What it means | +|---|---|---| +| `guardrail_service_url` | `http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/qwen3guard/v1/chat/completions` | Guard endpoint, derived from the guard model served through the AI gateway. Override it with any OpenAI-compatible chat-completions endpoint to screen against a guard elsewhere (another namespace, or off-cluster). | +| `guard_block_on_controversial` | `false` | Also block Qwen3Guard's `Controversial` label. Off by default: the label is advisory, and blocking it rejects a lot of legitimate traffic. | +| `guard_max_tokens` | `32` | Generation cap for the verdict. Verdicts are a few tokens; a larger cap only lengthens the blocking hook. | +| `guard_timeout` | `60` | Guard call timeout in seconds. LiteLLM clamps it to 60. | + +### Resources + +Size the guard model in its `qwen3guard` entry in `models.yaml`, like any served model: + +```yaml +# models.yaml (qwen3guard entry) +cpu: 2 # CPUs for the guard model +memory: 8Gi # Memory limit +extraCmdArgs: ["--block-size", "128", "--dtype", "bfloat16", "--max-num-seqs", "8"] +``` + +The guard model needs its own CPU headroom next to the main LLM. On a busy single node, size it so the guard pod can be scheduled without contending with the served models. + +### Context window + +`--max-model-len` is deliberately **not** set for the guard model, so it inherits the model's own `max_position_embeddings`, as the served models do. Each side tracks its own model instead of a hand-synced literal. + +The guardrail receives the *same* prompt the served LLM is about to receive. If the guard's context window is the smaller of the two, prompts in the gap are blocked (fail-closed) rather than screened, and the guardrail becomes the request-size ceiling for the whole stack. + +Current pairing (no gap): + +| Model | Source of context length | Effective | +|---|---|---| +| Served LLM `Qwen/Qwen2.5-Coder-14B-Instruct` | Model default | 32768 | +| Guard `Qwen/Qwen3Guard-Gen-0.6B` | Model default | 32768 | + +Check both after any model change: + +```bash +GW=http://ai-gateway.envoy-gateway-system.svc.cluster.local +kubectl exec -n litellm deploy/litellm -- \ + curl -s $GW/llm-inference/qwen2-5-coder-14b/v1/models | jq '.data[].max_model_len' +kubectl exec -n litellm deploy/litellm -- \ + curl -s $GW/llm-inference/qwen3guard/v1/models | jq '.data[].max_model_len' +``` + +If the guard's value is lower, over-length requests fail closed with `the prompt is longer than the guard model's context window`. The fix is a longer-context guard model or chunked screening. Do not raise `--max-model-len`: vLLM would accept prompts the model cannot attend over. + +### Fail-closed behavior + +Requests are **blocked** when the guard: + +- is unreachable +- returns a non-2xx status +- receives a prompt longer than its context window +- returns a reply that cannot be parsed + +An unparseable verdict is never treated as safe. Otherwise a change in the model's output format would silently disable moderation while everything looked healthy. Each case has a distinct block message, so the cause is visible in the response. + +## 3. Verify + +### Pods + +```bash +# Guard model pod (deployed from models.yaml). Expected: a Running vLLM pod serving Qwen/Qwen3Guard-Gen-0.6B +kubectl get pods -A | grep qwen3guard + +# LiteLLM proxy that holds the guardrail registration +kubectl get pods,svc -n litellm +``` + +### Registration + +The master key is in secret `litellm-master-key` (key `master_key`, namespace `litellm`). Inside the LiteLLM pod it is `PROXY_MASTER_KEY`. + +```bash +MASTER_KEY=$(kubectl get secret -n litellm litellm-master-key \ + -o jsonpath='{.data.master_key}' | base64 -d) +# equivalent: kubectl exec -n litellm deploy/litellm -- printenv PROXY_MASTER_KEY + +kubectl port-forward -n litellm svc/litellm 4000:4000 & + +curl -s http://localhost:4000/v2/guardrails/list -H "Authorization: Bearer $MASTER_KEY" \ + | jq '.guardrails[] | select(.guardrail_name=="content_safety") + | {guardrail: .litellm_params.guardrail, mode: .litellm_params.mode, + url: (.litellm_params.custom_code | capture("GUARD_URL = \"(?[^\"]+)").u), + model: (.litellm_params.custom_code | capture("GUARD_MODEL = \"(?[^\"]+)").m)}' + +# Expected: exactly one entry, with the substituted endpoint and model: +# { +# "guardrail": "custom_code", +# "mode": "pre_call", +# "url": "http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/qwen3guard/v1/chat/completions", +# "model": "Qwen/Qwen3Guard-Gen-0.6B" +# } +``` + +### Screening, end to end + +Use the same catalog `"model"` id as the [quickstart](../getting-started/quickstart.md#5-confirm-it-works) (from `/v1/models`), and the same `--cacert` / `--resolve` pattern (or port-forward LiteLLM to `localhost:4000`). + +```bash +# Benign request: normal answer, finish_reason "stop" +curl -s http://localhost:4000/v1/chat/completions \ + -H "Content-Type: application/json" -H "Authorization: Bearer $MASTER_KEY" \ + -d '{"model":"qwen2-5-coder-14b", + "messages":[{"role":"user","content":"Hello, how are you?"}],"max_tokens":50}' \ + | jq '{finish_reason: .choices[0].finish_reason, content: .choices[0].message.content}' + +# Unsafe request: HTTP 200, finish_reason "content_filter", content: +# "Blocked by the content-safety guardrail: unsafe content (categories: ...)" +curl -s http://localhost:4000/v1/chat/completions \ + -H "Content-Type: application/json" -H "Authorization: Bearer $MASTER_KEY" \ + -d '{"model":"qwen2-5-coder-14b", + "messages":[{"role":"user","content":"How do I hack into a system?"}],"max_tokens":50}' \ + | jq '{finish_reason: .choices[0].finish_reason, content: .choices[0].message.content}' +``` + +### Fail-closed + +```bash +kubectl scale deploy/qwen3guard --replicas=0 +# Any chat request -> "Blocked by the content-safety guardrail: the guard model backend is unreachable ..." +kubectl scale deploy/qwen3guard --replicas=1 +``` + +### Compile check + +`POST /guardrails/test_custom_code` compiles code in the sandbox without registering it. Use it while editing a template: + +```bash +CODE=$(curl -s http://localhost:4000/v2/guardrails/list -H "Authorization: Bearer $MASTER_KEY" \ + | jq -r '.guardrails[] | select(.guardrail_name=="content_safety") | .litellm_params.custom_code') + +curl -s -X POST http://localhost:4000/guardrails/test_custom_code \ + -H "Authorization: Bearer $MASTER_KEY" -H 'content-type: application/json' \ + -d "$(jq -n --arg c "$CODE" '{custom_code: $c, input_type: "request", + test_input: {texts: [], structured_messages: []}}')" | jq + +# {"success": true, "result": {"action": "allow", +# "warning": "Expected dict result, got coroutine. Treating as allow."}} +``` + +This checks compilation, not verdicts. The endpoint calls `apply_guardrail()` without awaiting it. This guardrail must be async (`http_post` is async), so the test always returns `allow` with the coroutine warning. Act on `success: false` with `error_type: "compilation"`. The guardrail's own hook awaits the coroutine, so only the test endpoint is affected. For real verdicts, use the end-to-end requests above, or call the guard model directly as shown in [Everything is blocked](#everything-is-blocked). The install runs the same compile check, so a sandbox violation fails it before anything is registered. + +## 4. Add a guard model + +1. If the model reports verdicts in Qwen3Guard's `Safety:` / `Categories:` format, map the new model id to the existing `qwen3guard_gen` template. +2. Otherwise, copy the existing template, change the prompt and parsing, and map the model id to the new template. Follow the sandbox rules in the template's docstring: no `import`, no `class`, no leading-underscore names, no f-strings. Use the injected primitives: `allow`, `block`, `trim`, `lower`, `contains`, `json_parse`, `json_stringify`, `regex_find_all`, `http_post`. +3. Add a row to the [guard model table](#guard-model), set the guard model in `models.yaml`, and re-run the installer. The endpoint and model id are substituted automatically. + +The install compiles the rendered code in LiteLLM's sandbox and fails **before** registering if it is rejected, so a sandbox mistake cannot take the guardrail down. + +## Troubleshooting + +### Guard model stuck in Pending + +**Symptom:** the `qwen3guard` pod is `0/1 Pending`. + +```bash +kubectl describe pod -A -l | grep Events -A 10 # look for "Insufficient cpu" +``` + +**Cause:** not enough free CPU for the guard model's request. + +1. Check what is consuming CPU: + + ```bash + kubectl get pods --all-namespaces \ + -o custom-columns=NAME:.metadata.name,CPU:.spec.containers[*].resources.requests.cpu | grep -v "" + ``` + +2. On single-node clusters, the served-model CPU accounting pre-reserves CPUs for components deployed *after* the LLM, including the guard model. If the node is full, lower a served model's request or the guard's `cpu` in `models.yaml`. + +### Registration failed + +The install prints the reason: + +| Message | Cause | Resolution | +|---|---|---| +| `guardrail code rejected by the LiteLLM sandbox` | The rendered code does not compile under RestrictedPython (`error_type: "compilation"`), usually an `import`, a `class`, a name starting with `_`, or an f-string. The check runs before the write, so nothing is registered or changed. | Reproduce with the [compile check](#compile-check). | +| `guardrail registered/updated failed (HTTP …)` | LiteLLM rejected the write. | Confirm the master key is an admin key and that LiteLLM's DB is reachable (`kubectl logs -n litellm deploy/litellm`). | + +After fixing, re-run `./toolkit_manager.sh install agent-toolkit`. The run re-registers the guardrail. + +### Everything is blocked + +``` +Blocked by the content-safety guardrail: the guard model backend is unreachable (...) +``` + +Fail-closed is working as designed: the guard model is down or not ready yet. A first deploy takes a few minutes to download the model, and the install does not wait for it. + +```bash +kubectl get pods -A | grep qwen3guard +kubectl logs -A -l --tail=50 +kubectl rollout status deploy/qwen3guard --timeout=600s +``` + +More than about 10 minutes usually means the model download is slow or the node is out of CPU for the guard's request. + +If the message names the **context window**, see [Context window](#context-window). If it says the **verdict could not be parsed**, the guard model and the code template disagree on the verdict format. Check the guard's raw reply: + +```bash +kubectl exec -n litellm deploy/litellm -- curl -s \ + http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/qwen3guard/v1/chat/completions \ + -H 'content-type: application/json' \ + -d '{"model":"Qwen/Qwen3Guard-Gen-0.6B","messages":[{"role":"user","content":"hello"}],"max_tokens":32}' \ + | jq -r '.choices[0].message.content' +# Expected: "Safety: Safe\nCategories: None" +``` + +## How it works + +``` + User request + │ + ▼ + ┌──────────────────────────────┐ + │ LiteLLM proxy (litellm) │ + │ ┌────────────────────────┐ │ pre_call hook ┌──────────────────────────┐ + │ │ content_safety │ │ http_post │ qwen3guard model │ + │ │ (custom_code sandbox) │──┼─────────────────────►│ (via ai-gateway, │ + │ └────────────────────────┘ │◄─────────────────────│ envoy-gateway-system) │ + └──────────────┬───────────────┘ Safety: Safe|Unsafe └──────────────────────────┘ + │ + safe ──────┴────── unsafe + │ │ + ▼ ▼ + Main LLM HTTP 200, finish_reason: content_filter, + │ block reason as the message + ▼ + Response +``` + +| Namespace | Holds | +|---|---| +| `litellm` | LiteLLM proxy; the registered guardrail is stored in its DB | +| `envoy-gateway-system` | The AI gateway that fronts the `qwen3guard` model (route `/llm-inference/qwen3guard`) | + +### Screening + +LiteLLM calls `apply_guardrail(inputs, request_data, input_type)` on the `pre_call` hook. The sandbox forbids `import`, `class`, `exec`/`eval`, file I/O, and leading-underscore names, and injects primitives instead (`allow`, `block`, `regex_find_all`, `http_post`, …). The Qwen3Guard logic: + +1. Takes the **last user message**, falling back to the last non-empty `texts` entry for call types without structured messages. This makes one guard call per request: the sandbox has no `asyncio`, so extra messages could not be screened concurrently and would each add a full guard round-trip to a blocking hook. +2. Sends it to the guard model as a single-message chat completion (`max_tokens: 32`, `temperature: 0`). +3. Parses `Safety:` and `Categories:` from the reply. +4. Calls `allow()` on `Safe` (and on `Controversial`, unless `guard_block_on_controversial` is set), and `block()` on `Unsafe` and on **every** failure to obtain a verdict. On `pre_call`, `block()` makes LiteLLM return HTTP 200 with `finish_reason: "content_filter"`. + +### Registration + +The install pipes the rendered code into the LiteLLM pod (`kubectl exec -i … -- python -`), which: + +1. Compiles it with `POST /guardrails/test_custom_code`, and aborts if it is rejected. +2. Looks up the guardrail with `GET /v2/guardrails/list`. +3. Calls `PUT /guardrails/{id}` if it exists, otherwise `POST /guardrails`. + +Running inside the pod reads the master key from the pod's `PROXY_MASTER_KEY` (sourced from the `litellm-master-key` secret), so the key is never written into a manifest. The payload travels base64-encoded on stdin, so the sandboxed Python needs no shell escaping. + +The step is an upsert, replacing the earlier create-if-absent behavior. Because the guardrail name is stable across model changes, a create-only step would leave an outdated registration in place, and since `pre_call` failures fail closed, that would block everything. `PUT` also re-initializes the in-memory guardrail, so no restart is needed (`PATCH` cannot change `litellm_params`). + +## Limitations and roadmap + +- **One validated guard model.** Only `Qwen/Qwen3Guard-Gen-0.6B` is validated. Model-specific logic is isolated to one template per verdict format, so a new guard model is a template plus a mapping entry. Unmapped ids fail the install rather than being assumed compatible. +- **One guardrail at a time.** Multiple concurrent guardrails (for example content safety *and* PII detection) are not yet available. Registering a second `custom_code` guardrail is cheap, but these constraints need resolving first: + + | Constraint | Detail | + |---|---| + | CPU capacity | Each guard *model* needs its own vLLM next to the main LLM. Library-backed checks (for example Presidio for PII) need no model server. | + | Latency | Every check runs on the blocking `pre_call` path, and without `asyncio` in the sandbox, checks inside one guardrail run sequentially; their round-trips add up on every request. | + | Per-check failure policy | Fail-closed is right for safety but may be wrong for other checks; the policy is currently per-guardrail code. | + | Aggregate false positives | Blocking is a union across checks, so tuning each check in isolation understates the combined impact on legitimate traffic. | + +## Next steps + +- [Configuration](configuration.md): `auth_type: litellm_vkey` and `models.yaml` +- [Single-node quickstart](../getting-started/quickstart.md#3-choose-a-model): the `qwen3guard` catalog row +- [Routing](routing.md): another LiteLLM feature on the same gateway +- [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md): `finish_reason: content_filter` +- [Backend connection reference](../reference/backend-connections.md): LiteLLM URL and master key +- External: [LiteLLM custom_code guardrail](https://docs.litellm.ai/docs/proxy/guardrails/custom_code_guardrail), [LiteLLM guardrails](https://docs.litellm.ai/docs/proxy/guardrails), [vLLM](https://docs.vllm.ai/), [Qwen3Guard model](https://huggingface.co/Qwen/Qwen3Guard-Gen-0.6B) diff --git a/docs/configuration/hybrid-router.md b/docs/configuration/hybrid-router.md new file mode 100644 index 00000000..ffcb1cc3 --- /dev/null +++ b/docs/configuration/hybrid-router.md @@ -0,0 +1,246 @@ +# Hybrid router + +[← Docs index](../README.md) + +Call one name, `"model": "hybrid-router"`, and let the stack send simple prompts to a smaller model and hard ones to a larger model. This release creates that virtual model at install (`hybrid_router_enabled: true` in `config.agent-toolkit.yaml`). It runs with `auth_type: litellm_vkey`. Set tier lists in `hybrid_router_tier_candidates` (see the [quickstart optional section](../getting-started/quickstart.md#optional-route-simple-vs-complex-prompts)). Intent-based routing is in [Routing](routing.md). + +```bash +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.${DOMAIN}:443:${GATEWAY_IP}" \ + "https://litellm.${DOMAIN}/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${AGENT_TOOLKIT_API_KEY}" \ + -d '{"model": "hybrid-router", + "messages": [{"role": "user", "content": "Write a Python hello world"}], + "max_tokens": 100}' +``` + +Use a virtual key for apps. Which real model answered shows in Langfuse. The sections below cover classification, bandit settings, and how the router mounts into LiteLLM. + +## How it works + +At proxy startup, the module `custom_hybrid_router.py` patches `litellm.router.Router` to recognize the `auto_router/hybrid_router` deployment prefix. This mirrors LiteLLM's built-in `ComplexityRouter`. A pre-routing hook then handles every request to the virtual model before LiteLLM chooses a deployment: + +``` +Request model="hybrid-router" + │ + ▼ +Router.async_pre_routing_hook (patched by custom_hybrid_router.py) + │ model in hybrid_routers? NO → normal LiteLLM routing + │ YES ↓ + │ 1. Extract user and system text from messages + │ 2. HybridRouter.classify() → SIMPLE / MEDIUM / COMPLEX / REASONING + │ 3. HybridRouter.pick_model() → best real model for that tier (bandit) + │ 4. Return PreRoutingHookResponse(model=) + │ + ▼ +LiteLLM routes to the chosen model + │ + ▼ +async_log_success_event / async_log_failure_event + Latency and token throughput → reward → bandit.update() +``` + +Requests to any other model name are not affected. The `auto_router/hybrid_router` model is never dispatched directly. + +### Layer 1: complexity classification + +A rules-based classifier scores each prompt without an extra model call. It weighs estimated token count, code, reasoning, technical, and simple keyword hits, multi-step patterns (`first … then`, `step 2`, numbered lists), and question density, then maps the score to a tier: + +| Tier | Score | Typical prompts | +|---|---|---| +| `SIMPLE` | `< 0.15` | Greetings, factual lookups, yes/no | +| `MEDIUM` | `0.15`–`0.35` | Explanations, summaries, basic coding | +| `COMPLEX` | `0.35`–`0.60` | Architecture, multi-step code, technical analysis | +| `REASONING` | `≥ 0.60`, or 2+ reasoning markers | Chain-of-thought, deduction, proofs | + +Tier boundaries, token thresholds, keyword lists, and dimension weights can be overridden with `complexity_router_config`. The tier logic comes from LiteLLM's built-in `complexity_router` module; it is not vendored. + +### Layer 2: efficiency (multi-armed bandit) + +Each tier has its own bandit, whose arms are that tier's candidate models. Per-tier bandits matter because a model can be fast on `SIMPLE` prompts and slow on `COMPLEX` ones. After each response the router updates the arm with a reward: + +``` +time_per_token = latency_seconds / max(completion_tokens, 1) +reward = target_tpt / (target_tpt + time_per_token) # in (0, 1] +``` + +Failures record a reward of `0`. When `quality_weight > 0`, the reward is `(1 - quality_weight) * efficiency + quality_weight * quality_score`. A tier with only one candidate skips the bandit and routes directly. + +| `bandit` | Algorithm | Behavior | +|---|---|---| +| `thompson` (default) | Beta-Bernoulli Thompson Sampling | Posterior sampling; balances exploration and exploitation | +| `ucb` | Upper Confidence Bound | Optimism under uncertainty; `delta` sets the exploration bound | +| `epsilon_greedy` | ε-greedy | Explores uniformly with probability `epsilon`, otherwise greedy | + +## 1. Enable the router + +Set the toggle in `env/local/config.inference.yaml`: + +```yaml +hybrid_router_enabled: true +``` + +Then install Intel® Inference Toolkit (or the whole stack): + +```bash +./toolkit_manager.sh install inference # or: install agent-toolkit +``` + +With the toggle on, the `litellm` role (`tasks/hybrid_router_setup.yaml`): + +1. Renders the router source into the `litellm-router-code` ConfigMap. +2. Mounts each Python file next to `config.yaml` in the LiteLLM container (`/etc/litellm/…`, where LiteLLM resolves `callbacks` modules) and sets `PYTHONPATH`. +3. Adds the callback, so LiteLLM imports the module and applies the patch at startup: + + ```yaml + litellm_settings: + callbacks: ["langfuse", "custom_hybrid_router.proxy_handler_instance"] + ``` + +4. Registers the `hybrid-router` virtual model from the `hybrid_router_*` settings below. + +A fresh install picks the router up directly. On a cluster where LiteLLM is already running, change the `hybrid_router_*` settings and re-run with `litellm_reconcile` so the release picks them up: + +```bash +./toolkit_manager.sh install agent-toolkit -- -e litellm_reconcile=true +``` + +(or set `litellm_reconcile: true` in `config.agent-toolkit.yaml` / `config.inference.yaml`). + +## 2. Configure tiers and the bandit + +The `litellm` role builds the virtual model from these keys in `env/local/config.inference.yaml` and maps them onto `litellm_params.hybrid_router_config`: + +| Field | Default | What it means | +|---|---|---| +| `hybrid_router_model_name` | `hybrid-router` | Model name clients call | +| `hybrid_router_default_model` | Required when `tier_candidates` is omitted. The install example uses `qwen2-5-coder-14b` | Fallback model | +| `hybrid_router_tier_candidates` | Default model for every tier | `tier_candidates`: tier → list of deployed model names | +| `hybrid_router_bandit` / `_delta` / `_epsilon` / `_target_tpt` / `_quality_weight` | See next table | Bandit parameters | +| `hybrid_router_tier_boundaries` | `0.15`, `0.35`, `0.60` | `complexity_router_config.tier_boundaries` | + +Every model in `tier_candidates` must already be deployed (`llm_services_autodeploy_models`, or `./model-manager deploy `). + +The resulting `hybrid_router_config` keys: + +| Key | Default | What it means | +|---|---|---| +| `bandit` | `thompson` | Algorithm: `ucb`, `epsilon_greedy`, or `thompson` | +| `delta` | `0.1` | UCB exploration; smaller means more exploration. Must be in `(0, 1)`. | +| `epsilon` | `0.1` | ε-greedy exploration probability. Must be in `[0, 1]`. | +| `target_tpt` | `1.0` | Target time per token; the midpoint of the reward curve | +| `quality_weight` | `0.0` | Quality vs. efficiency blend in `[0, 1]`; `0` is pure efficiency | +| `tier_candidates` | `hybrid_router_default_model` for every tier | Tier → list of real model names | +| `tier_priors` | None | Optional per-tier, per-arm Beta priors `(alpha, beta)` for Thompson Sampling | +| `complexity_router_config` | Built-in defaults | Tier boundaries, token thresholds, keyword lists, dimension weights | +| `hybrid_router_default_model` | None | Fallback model. Required if `tier_candidates` is omitted. | + +`complexity_router_config.tier_boundaries` accepts `simple_medium`, `medium_complex`, and `complex_reasoning` (defaults `0.15`, `0.35`, `0.60`). + +For reference, the role generates a LiteLLM entry equivalent to this one (catalog names, not Hugging Face ids): + +```yaml +model_list: + - model_name: qwen2-5-coder-14b + litellm_params: + model: openai/qwen2-5-coder-14b + api_base: http://qwen2-5-coder-14b.llm-inference.svc.cluster.local:80/v1 + api_key: not-needed + - model_name: qwen3-coder-30b + litellm_params: + model: openai/qwen3-coder-30b + api_base: http://qwen3-coder-30b.llm-inference.svc.cluster.local:80/v1 + api_key: not-needed + + # Virtual entry that clients call + - model_name: hybrid-router + litellm_params: + model: auto_router/hybrid_router + hybrid_router_default_model: qwen2-5-coder-14b + hybrid_router_config: + bandit: thompson + target_tpt: 1.0 + quality_weight: 0.0 + tier_candidates: + SIMPLE: [qwen2-5-coder-14b] + MEDIUM: [qwen2-5-coder-14b, qwen3-coder-30b] + COMPLEX: [qwen3-coder-30b] + REASONING: [qwen3-coder-30b] + complexity_router_config: + tier_boundaries: + simple_medium: 0.15 + medium_complex: 0.35 + complex_reasoning: 0.60 +``` + +Prefer YAML + `litellm_reconcile` over hand-posting models at runtime. Every name in `tier_candidates` must already be deployed (`./model-manager list --catalog` and `./model-manager deploy `). + +## 3. Test + +Use the same `--cacert` / `--resolve` pattern as the [quickstart](../getting-started/quickstart.md#5-confirm-it-works) (or port-forward LiteLLM). + +```bash +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.$DOMAIN:443:$GATEWAY_IP" \ + "https://litellm.$DOMAIN/v1/chat/completions" \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ + -H "Content-Type: application/json" \ + -d '{"model": "hybrid-router", "messages": [{"role": "user", "content": "What is 2+2?"}]}' +``` + +The router classifies the prompt and forwards it. Requests to any other model name are unaffected. + +## 4. Observe routing decisions + +The proxy logs one line at startup and one per routed request: + +```bash +kubectl logs -n litellm deploy/litellm -c litellm -f +``` + +``` +[HybridRouterProxy] litellm.router.Router patched for auto_router/hybrid_router +[HybridRouterProxy] Initialised model_name=hybrid-router bandit=thompson default=qwen2-5-coder-14b tiers=['SIMPLE', 'MEDIUM', 'COMPLEX', 'REASONING'] +[HybridRouterProxy] model=hybrid-router call_id=... tier=SIMPLE -> qwen2-5-coder-14b +``` + +Per-tier bandit state (arm counts, running means, and the Beta `alpha`/`beta` posteriors for Thompson) is available from `HybridRouterProxy.router_state()`. Latency and token metrics also reach Langfuse and Prometheus through the standard gateway telemetry. + +Langfuse records which model answered. Open `https://langfuse.`. The login is in Secret `langfuse-secrets` in namespace `langfuse`: + +```bash +kubectl get secret langfuse-secrets -n langfuse -o jsonpath='{.data.admin_email}' | base64 -d; echo +kubectl get secret langfuse-secrets -n langfuse -o jsonpath='{.data.admin_password}' | base64 -d; echo +``` + +Open the `inference` project. Under **Tracing**, select the latest `litellm_request`, then **Metadata** → **attributes**, and read `llm.model_name`. + +### LiteLLM UI + +The UI is `https://litellm./ui`. Browsers need that name in DNS or `/etc/hosts` (smoke-test curls can use `--resolve` instead; see [Prerequisites](../getting-started/prerequisites.md#2-dns-and-tls)). + +The username is `admin`. The password is `LITELLM_MASTER_KEY`. Models deployed with `./toolkit_manager.sh install` are listed under **Models+Endpoints** → **All Models**, including `bge-base-en` when that catalog name is in `llm_services_autodeploy_models`. + +This release creates `hybrid-router` at install (`hybrid_router_enabled: true`). There is no UI step to create it. New models join a tier only when you list them in `hybrid_router_tier_candidates` and re-run install with `litellm_reconcile=true` (defaults keep every tier on the default model alone). + +If a second model fails with `NRI pre-flight failed: not enough physical cores`, set an explicit `cpu:` in `models.yaml` ([Deploy a model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md)), undeploy the first model, and install again: + +```bash +kubectl get llminferenceservices,inferenceservices -n llm-inference +./model-manager undeploy +./toolkit_manager.sh install agent-toolkit +kubectl rollout restart deployment litellm -n litellm +``` + +## Disable the router + +Set `hybrid_router_enabled: false` in `env/local/config.inference.yaml`. On a fresh install, the ConfigMap, mounts, callback, and virtual model are not created. Because LiteLLM is install-once, removing them from a running release takes `helm uninstall litellm -n litellm` followed by `./toolkit_manager.sh install inference`. With the router off, LiteLLM behaves as a stock proxy. + +## Next steps + +- [Quickstart hybrid section](../getting-started/quickstart.md#optional-route-simple-vs-complex-prompts): first-run tier lists and `litellm_reconcile` +- [Routing](routing.md): other routing options (including semantic routing) +- [Configuration](configuration.md): `hybrid_router_enabled` +- [Backend connection reference](../reference/backend-connections.md): Langfuse traces +- [Glossary](../reference/glossary.md#routing) diff --git a/docs/configuration/routing.md b/docs/configuration/routing.md new file mode 100644 index 00000000..9337abce --- /dev/null +++ b/docs/configuration/routing.md @@ -0,0 +1,130 @@ +# Routing + +[← Docs index](../README.md) + +By default, applications name a deployed model (for example `qwen2-5-coder-14b`). **Routing** uses a virtual model name instead. The stack classifies the prompt, selects a deployed model, and returns the completion. The client still calls `/v1/chat/completions`. `"model"` is the virtual name. + +Routing is optional. A request that names a real model goes to that model. Use this page when one application-facing name should fan out to several backends. + +| Requirement | Mechanism | Guide | +|---|---|---| +| Intent or category (code, chat, reasoning) | Semantic routing (`vllm-sr/auto`) | [Semantic routing](#semantic-routing) | +| Complexity, cost, and latency | Hybrid router (`hybrid-router`) | [Hybrid router](hybrid-router.md) | + +Use one mechanism per virtual model name. + +--- + +## Semantic routing + +Semantic routing sits in front of models you have already deployed. A request with `"model": "vllm-sr/auto"` is classified and sent to one of those models. A request that names a real model is not routed. + +- Coding prompts are sent to a coding model; general chat is sent to a general-purpose model. +- Lower-complexity traffic remains on a smaller, faster model; heavier prompts use a larger model. +- For families such as Qwen3 and DeepSeek, reasoning modes can be enabled when the prompt requires them. + +The classifier and embedding models used by the router are cached on a persistent volume so a pod restart does not trigger a re-download. + +### Enable semantic routing + +Semantic routing is disabled by default. Enabling it does not alter models that applications already call by name. + +1. In `env//config.inference.yaml` (the default environment is `local`): + + ```yaml + vllm_sr_enabled: true + ``` + +2. Deploy: + + ```bash + ./toolkit_manager.sh install agent-toolkit + ``` + + To install only this piece on a stack that is already up: `./toolkit_manager.sh install vllm_sr --only`. + +The installer is idempotent. Re-run it at any time; toolkit roles upgrade in place with the current YAML. + +### Invoke the router + +The virtual model name is `vllm-sr/auto` (`vllm_sr_litellm_model_name` in `config.yaml`). + +With `auth_type: litellm_vkey`, call LiteLLM (default domain `inteltoolkits.ai`). Use a virtual key for apps; the master key is for install smoke tests only: + +```bash +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.${DOMAIN}:443:${GATEWAY_IP}" \ + "https://litellm.${DOMAIN}/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${AGENT_TOOLKIT_API_KEY}" \ + -d '{ + "model": "vllm-sr/auto", + "messages": [{"role": "user", "content": "write a hello world in python"}] + }' +``` + +Set `DOMAIN` and `GATEWAY_IP` the same way as the [quickstart verify](../getting-started/quickstart.md#5-confirm-it-works). Guardrails and Langfuse apply the same as any other LiteLLM call. In this release the router API is not published on its own host. Send `vllm-sr/auto` through LiteLLM. + +### Per-request selection + +- `"model": "vllm-sr/auto"`: the router selects a deployed model. +- `"model": "qwen2-5-coder-14b"` (any deployed catalog name): that model is used. The router is bypassed. + +### From Python or an orchestration framework + +```python +from openai import OpenAI + +client = OpenAI( + base_url="https://litellm.inteltoolkits.ai/v1", # or litellm. + api_key="", # not the LiteLLM master key +) + +resp = client.chat.completions.create( + model="vllm-sr/auto", + messages=[{"role": "user", "content": "Refactor this function to run asynchronously"}], +) +print(resp.choices[0].message.content) +``` + +LangGraph, CrewAI, and other OpenAI-compatible clients use the same base URL and `model="vllm-sr/auto"`. + +### Models eligible for routing + +Models the router can select must already be deployed (`llm_services_autodeploy_models`, or `./model-manager deploy `). Category mapping is `vllm_sr_config_override` in `config.inference.yaml`. Dashboard, signals, Helm settings, and troubleshooting: [vLLM semantic router](semantic-router.md). + +Apply a change with: + +```bash +./toolkit_manager.sh install agent-toolkit +``` + +### Verify routing + +```bash +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.${DOMAIN}:443:${GATEWAY_IP}" \ + "https://litellm.${DOMAIN}/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${AGENT_TOOLKIT_API_KEY}" \ + -d '{"model": "vllm-sr/auto", + "messages": [{"role": "user", "content": "Write a Python function to reverse a linked list"}]}' +``` + +Open `https://langfuse.` and inspect the `model` field on each trace. + +--- + +## Next steps + +- Complexity routing, on by default: [Hybrid router](hybrid-router.md) +- Which models install: [Choose a model](../getting-started/quickstart.md#3-choose-a-model) +- Model serving flags: [Configuration](configuration.md) +- Traces after a routed call: [backend connection reference](../reference/backend-connections.md) (Langfuse) +- Failures: [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md) + +## Related pages + +- [Meet the Agent Toolkit](../overview/meet.md) +- [Glossary](../reference/glossary.md#routing) +- [Guardrails](guardrails.md) diff --git a/docs/configuration/semantic-router.md b/docs/configuration/semantic-router.md new file mode 100644 index 00000000..c875cb31 --- /dev/null +++ b/docs/configuration/semantic-router.md @@ -0,0 +1,264 @@ +# vLLM semantic router + +[← Docs index](../README.md) + +Set `vllm_sr_enabled: true` in `config.inference.yaml` before you depend on `vllm-sr/auto`. The short enable and call sequence is also on [Routing](routing.md#semantic-routing). + +vLLM Semantic Router classifies each prompt and sends it to one deployed model. A request with `"model": "vllm-sr/auto"` is routed. A request that names a real model goes to that model. Project background: [vllm-semantic-router.com](https://vllm-semantic-router.com/). + +``` +Client + | + | HTTPS + v +LiteLLM + | authenticates the request + | model="vllm-sr/auto" triggers routing + | starts a Langfuse trace + v +vLLM Semantic Router + | classifies the prompt + | selects a backend + v +Model backend (local vLLM, or a cloud model registered in LiteLLM) + v +Response returns through the same path +``` + +vLLM-SR emits OpenTelemetry traces that show up in Langfuse next to the LiteLLM traces. Trace export is not available in this release. See [Langfuse](#langfuse). + +## Install + +The cluster, the gateway, and at least one model are already up. In `env/local/config.inference.yaml`: + +```yaml +vllm_sr_enabled: true +``` + +```bash +./toolkit_manager.sh install agent-toolkit +``` + +The install discovers model services already in the cluster, deploys the vLLM-SR Helm chart, waits until the containers are healthy, and registers `vllm-sr/auto` in LiteLLM. To install only this piece: `./toolkit_manager.sh install vllm_sr --only`. + +### Call it + +Use the same `--cacert` / `--resolve` pattern as the [quickstart](../getting-started/quickstart.md#5-confirm-it-works) (set `DOMAIN`, `GATEWAY_IP`, and `LITELLM_MASTER_KEY` the same way): + +```bash +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.$DOMAIN:443:$GATEWAY_IP" \ + "https://litellm.$DOMAIN/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ + -d '{ + "model": "vllm-sr/auto", + "messages": [{"role": "user", "content": "write a hello world in python"}] + }' +``` + +A named model bypasses routing (`"model": "qwen2-5-coder-14b"` on the same URL). + +### Dashboard + +The dashboard is on its own host, because it serves `/login`, `/api`, and `/assets` at the root and cannot sit under a sub-path: + +```text +https://vllm-sr./ +``` + +The router API (`/v1/route`) is not published at the gateway in this release. Send requests to `vllm-sr/auto` through LiteLLM. + +- **DNS.** `vllm-sr.` resolves to the gateway, as a DNS record or a line in `/etc/hosts` on the node and on every client. See [Prerequisites](../getting-started/prerequisites.md). +- **TLS.** The certificate covers `vllm-sr.`, as a SAN (`DNS:vllm-sr.`) or a wildcard (`*.`). A certificate that lacks it has to be reissued. +- **Proxy.** Add `vllm-sr.` to the proxy bypass list, the same way as `litellm.`. + +Default credentials are generated at deploy time into Secret `vllm-sr-dashboard` in namespace `vllm-semantic-router-system`, keys `admin-email` and `admin-password`. + +## Request flow + +1. The client sends `POST /v1/chat/completions` with `model: "vllm-sr/auto"`. +2. LiteLLM authenticates the request, starts a Langfuse trace, and forwards to vLLM-SR. +3. vLLM-SR classifies the prompt. +4. The decision engine evaluates rules from the smallest priority number to the largest: + - `coding-route` (priority 10) matches coding prompts + - `reasoning-route` (priority 50) matches analytical prompts + - `default-route` (priority 100) is the catch-all +5. vLLM-SR sends the request to the selected backend. +6. The response returns to the client. + +LiteLLM treats `vllm-sr/auto` and the real model names as separate entries, so a routed call does not loop. Only `vllm-sr/auto` goes to vLLM-SR. + +## Routing configuration + +The reference config is `core/helm-charts/vllm-sr/router-config.yaml`. The Helm template `core/helm-charts/vllm-sr/templates/configmap.yaml` renders it into a ConfigMap. Day to day, edit `vllm_sr_config_override` in `env/local/config.inference.yaml` and reinstall. + +**Signals** classify prompts: + +```yaml +routing: + signals: + embeddings: + - name: coding_tasks + threshold: 0.72 + candidates: + - "write code" + - "implement function" + - "debug this" +``` + +A new category is another embedding entry: a name, a similarity threshold, and candidate phrases. + +**Decisions** are evaluated from the smallest priority number. The first match wins. + +```yaml +routing: + decisions: + - name: coding-route + description: "Route coding tasks to coder model" + priority: 10 + rules: + operator: AND + conditions: + - type: embedding + name: coding_tasks + modelRefs: + - model: qwen2-5-coder-14b + use_reasoning: false +``` + +Editing decisions by hand is not available in this release. The shape above is what the chart renders. + +**Model backends** are discovered at deploy time. See [Add a model](#add-a-model). Each one has this shape: + +```yaml +providers: + models: + - name: qwen2-5-coder-14b + provider_model_id: "qwen2-5-coder-14b" + backend_refs: + - name: "primary" + endpoint: "qwen2-5-coder-14b-kserve-workload-svc.llm-inference.svc.cluster.local:8000" + protocol: "http" + weight: 100 +``` + +- `name` is the identifier used in `routing.decisions`. +- `provider_model_id` is the model id the backend serves. +- `endpoint` is `host:port` inside the cluster. +- `protocol` is `http` for vLLM backends. + +### Settings + +All of these live in `env/local/config.inference.yaml`. + +| Setting | Meaning | +|---|---| +| `vllm_sr_image_tag` | vLLM-SR container version | +| `vllm_sr_dashboard_admin_email` | Dashboard login email. Default `admin@` | +| `vllm_sr_dashboard_secret` | Secret that holds the dashboard password. Default `vllm-sr-dashboard`, generated at deploy time | +| `vllm_sr_cache_backend` | Semantic cache: `memory` or `redis` | +| `routing.enableSemanticCache` | Response caching. Not available in this release | +| `routing.cacheThreshold` | Similarity above which a cached response is reused. Default `0.92`. Not available in this release | +| `vllm_sr_default_model` | Backend name used when the router has no better choice. Default is `qwen2-5-coder-14b`, or the first routed model when that one is not routed | +| `routing.enableJailbreakDetection` | Not wired. Not available in this release | +| `routing.enablePiiDetection` | Not wired. Not available in this release | +| `observability.enabled` | Export traces to Langfuse. Not available in this release | + +After you edit those settings, or `vllm_sr_config_override`: + +```bash +./toolkit_manager.sh install agent-toolkit +# or only this piece: +./toolkit_manager.sh install vllm_sr --only +``` + +The pod restarts when the ConfigMap changes. + +## Add a model + +With `vllm_sr_enabled: true`, a model deployed through the toolkit is added to routing in the same run. There is no separate registration step. vLLM-SR discovers the model services, adds each one as a backend, and rebuilds its routing config. The model then shows up in the dashboard. + +1. Put the catalog name in `llm_services_autodeploy_models` in `env/local/config.agent-toolkit.yaml`, with `vllm_sr_enabled: true`. +2. Run `./toolkit_manager.sh install agent-toolkit`. + +Confirm it on `https://vllm-sr./`. + +Once a model is a backend: + +- The reasoning and default routes consider every model, so a new model is eligible for that traffic immediately. +- The coding route considers models whose name contains `coder`. + +A new prompt category (math, legal) needs a signal and a matching decision. See [Routing configuration](#routing-configuration). + +Check which model answered: + +```bash +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.$DOMAIN:443:$GATEWAY_IP" \ + "https://litellm.$DOMAIN/v1/chat/completions" \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ + -H "Content-Type: application/json" \ + -d '{"model": "vllm-sr/auto", "messages": [{"role": "user", "content": "write a python function to sort a list"}]}' \ + | jq -r .model +``` + +Clients keep calling `vllm-sr/auto`. The router dispatches internally. + +## LiteLLM + +`vllm-sr/auto` is registered in LiteLLM at the end of the deployment playbook (`vllm_sr_litellm_model_name`). + +- `"model": "vllm-sr/auto"` goes through semantic routing. +- `"model": ""` goes to that model. + +Both paths go through LiteLLM for authentication and spend tracking. + +## Langfuse + +vLLM-SR emits an OpenTelemetry trace for every routed request. In Langfuse those spans sit next to the LiteLLM trace. Trace export is not available in this release. + +For a request that did go through vLLM-SR, Langfuse shows: + +From LiteLLM (`service.name: litellm`): the prompt, the response, token counts, cost, and total latency. + +From vLLM-SR (`service.name: vllm-semantic-router`): + +- `semantic_router.signal.evaluation`: which signals matched, and the confidence score +- `semantic_router.decision.evaluation`: which route was selected, and which model +- `semantic_router.upstream.request`: backend latency and HTTP status + +## Troubleshooting + +**Pod is not Ready.** See which container failed: + +```bash +kubectl get pods -n vllm-semantic-router-system -o jsonpath='{range .items[0].status.containerStatuses[*]}{.name}: {.ready}{"\n"}{end}' +``` + +The vllm-sr container downloads the encoder on first start (about 1–2 minutes). The envoy container needs a higher file-descriptor limit when the log says `Too many open files`. Raise `fs.inotify.max_user_instances` before install. See [Prerequisites](../getting-started/prerequisites.md#node-kernel-settings). + +**Traces are missing in Langfuse.** Trace export is not available in this release. When it is, check the vLLM-SR container: + +```bash +kubectl logs -n vllm-sr -c vllm-sr | grep "traces export" +``` + +**LiteLLM returns `Connection error` for `vllm-sr/auto`.** Check that vLLM-SR is reachable from the `litellm` namespace: + +```bash +kubectl exec -n litellm deploy/litellm -c litellm -- \ + python3 -c "import socket; s=socket.socket(); s.connect(('semantic-router.envoy-gateway-system.svc.cluster.local', 80)); print('OK')" +``` + +**Dashboard shows `Failed to read config`.** + +```bash +kubectl logs -n vllm-semantic-router-system deploy/semantic-router-dashboard +``` + +## Next steps + +- [Routing](routing.md): `vllm-sr/auto` next to the hybrid router +- [Hybrid router](hybrid-router.md): complexity routing, on by default in this release +- [Choose a model](../getting-started/quickstart.md#3-choose-a-model) diff --git a/docs/configuring-inference-config-cfg-file.md b/docs/configuring-inference-config-cfg-file.md deleted file mode 100644 index ea0a416f..00000000 --- a/docs/configuring-inference-config-cfg-file.md +++ /dev/null @@ -1,101 +0,0 @@ -An example and Explaination of the `agentic-config.cfg` settings, as set in the `env//` files of this release: -````` -# env//global_config.yaml -base_domain_name: "example.com" # cluster_url: APIs on https://litellm./v1 -gateway_tls_mode: "selfsigned" # cert_file / key_file: set "custom" and the two lines below -# gateway_tls_cert_file: "/path/to/cert/file.pem" -# gateway_tls_key_file: "/path/to/key/file.pem" -# existing_kubernetes: /path/to/kubeconfig # unset = fresh Kubernetes cluster (deploy_kubernetes_fresh=on) -observability_enabled: true # deploy_observability -storage_backend: local-path # deploy_ceph: ceph -istio_enabled: false # deploy_istio -kata_containers_enabled: false # deploy_kata_containers -kata_runtime: "kata-fc" -http_proxy: "" -https_proxy: "" -no_proxy: "" - -# env//config.agent-toolkit.yaml -auth_type: "litellm_vkey" # deploy_genai_gateway=on (set by init agent-toolkit) -llm_services_autodeploy_models: ["qwen2-5-coder-7b"] # deploy_llm_models, models -redis_stack_enabled: true # deploy_redis -pgvector_enabled: false # deploy_pgvector -kuberay_enabled: false # deploy_kuberay -agent_sandbox_enabled: false # deploy_agent_sandbox -guardrails_enabled: true # deploy_guardrails -openshell_enabled: false # deploy_openshell - -# env//config.inference.yaml -vllm_sr_enabled: false # deploy_vllm_sr - -# hugging_face_token: export HF_TOKEN=hf_... before install / model-manager -# not available in this release: hugging_face_token_falcon3, compute_platform=g (GPU models), -# uninstall_ceph, deploy_agenticai_plugin, rack_scale_mode, air_gapped -# deploy_ingress_controller: none (the platform gateway is always installed) - -````` -Make sure to update the values in `env//global_config.yaml`, `config.agent-toolkit.yaml` and `config.inference.yaml` according to your requirements before Toolkit Manager installs Intel® Agent Toolkit. - - -> -> - If `existing_kubernetes` is not set, a fresh Kubernetes cluster will be initialized as per the deployment configuration. -> - The platform gateway is always installed to route external traffic to the cluster -> - If `auth_type` is set to `"litellm_vkey"` (the `config.agent-toolkit.yaml` default), the GenAI Gateway will be deployed. -> - If `observability_enabled` is set to `true`, the observability stack (Grafana) will be deployed. The Langfuse LLM tracing stack is deployed with the GenAI Gateway. -> - The models in `llm_services_autodeploy_models` will be deployed for inferencing; deploy others with `./model-manager deploy ` -> - With `gateway_tls_mode: "custom"`, the `gateway_tls_cert_file` and `gateway_tls_key_file` paths should be set according to the instructions for generating certificates for development and production environments, as documented. -> - The `llm_services_autodeploy_models` values correspond to the model names in the catalog, `env//models.yaml`. -> - The Hugging Face token used for pulling LLM models from Hugging Face is set with `export HF_TOKEN=hf_...` before install / model-manager. -> - If `llm_services_autodeploy_models` is set to `[]`, the `HF_TOKEN` value will be ignored. -> - The `cpu` value specifies whether to deploy models for CPU or Intel® AI Accelerator. -> > **Note:** not available in this release. -> - If `redis_stack_enabled` is set to `true` , Redis will be deployed which is the default memory backend, giving agents persistent session state, semantic search over past interactions, and cross-request continuity. Redis is password-protected (credentials generated into the `redis-stack-server-credentials` Secret) and reachable only from inside the cluster — see [backend-connection-reference.md](./backend-connection-reference.md#redis-session-memory--caching). -> - If `pgvector_enabled` is set to `true`, PostgreSQL 16 with the pgvector extension will be deployed as a vector store and long-term memory backend. -> - If `kuberay_enabled` is set to `true`, KubeRay will be deployed to provide Ray distributed computing inside the cluster. Tuning parameters (namespace, worker replicas, CPU/memory limits, Ray image) are the `kuberay_*` settings in `config.agent-toolkit.yaml` — see [docs/kuberay.md](./kuberay.md) for the full guide. -> - If `agent_sandbox_enabled` is set to `true`, the Agent Sandbox controller will be deployed for isolated pod-based code execution. -> - If `kata_containers_enabled` is set to `true`, Kata Containers is installed so sandboxes can run as microVMs with their own guest kernel, and `kata_runtime` selects the runtime (`kata-fc` for Firecracker, `kata-qemu` for QEMU, or `both`). This requires `agent_sandbox_enabled: true` — otherwise a warning is printed and Kata is skipped. Nodes need KVM (`/dev/kvm`), and `kata-fc` additionally needs containerd's devmapper snapshotter; missing prerequisites warn and skip instead of failing the run — see [agent-sandbox.md](./agent-sandbox.md#microvm-isolation-with-kata-containers-kata-fc--kata-qemu). -> - To deploy on GPU instead of CPU, set `compute_platform=g` and select a GPU model in `models` (e.g. `gpu-nvidia-b300-llama-70b`), as shown in the commented GPU example above. -> > **Note:** not available in this release. -> - If `rack_scale_mode` is set to `on`, the toolkit deploys using the rack-scale fabric topology (BGP, dual-homed nodes, Ceph-on-fabric) instead of the standard single/multi-node path — see [rack-scale-deployment.md](./rack-scale-deployment.md). -> > **Note:** not available in this release. -> - If `air_gapped` is set to `on`, the internet connectivity precheck is skipped for isolated/local-mirror sites; leave it commented out (or `off`) when the cluster has internet access. -> > **Note:** not available in this release. -> - `guardrails_enabled` (default: on with LiteLLM) deploys the safety content-moderation guardrail in front of the main LLM — see [guardrails.md](./guardrails.md). -> - If `vllm_sr_enabled` is set to `true` (in `config.inference.yaml`), vLLM Semantic Router is deployed to route requests across models by cost/latency/safety signals — see [vllm-semantic-router.md](./vllm-semantic-router.md). -> - If `openshell_enabled` is set to `true`, NVIDIA OpenShell will be deployed for policy-enforced sandboxes on top of Agent Sandbox, with the GenAI Gateway registered as a provider. Requires `agent_sandbox_enabled: true` — see [docs/openshell.md](./openshell.md). - ---- - -## KubeRay Tuning Parameters - -KubeRay resource settings are role settings next to the switches above. They live in: - -``` -env//config.agent-toolkit.yaml -``` - -This file is created by `./es_auto_installer.sh init agent-toolkit`; the values below are the defaults. Edit it to tune the Ray cluster before re-running the deploy script: - -```yaml -kuberay_namespace: ray-system - -kuberay_release_name: ray-cluster -kuberay_ray_image: rayproject/ray:2.40.0-py312 - -kuberay_head_cpu_request: "500m" -kuberay_head_cpu_limit: "2" -kuberay_head_memory_request: "2Gi" -kuberay_head_memory_limit: "4Gi" - -kuberay_worker_replicas: 2 -kuberay_worker_min_replicas: 1 -kuberay_worker_max_replicas: 4 -kuberay_worker_cpu_request: "500m" -kuberay_worker_cpu_limit: "2" -kuberay_worker_memory_request: "2Gi" -kuberay_worker_memory_limit: "4Gi" -``` - -See [docs/kuberay.md](./kuberay.md) for the full configuration reference and deployment guide. - -For running behind corporate proxy, please refer to this [guide](./running-behind-proxy.md) diff --git a/docs/decommission-and-redeploy.md b/docs/decommission-and-redeploy.md deleted file mode 100644 index 67dca32b..00000000 --- a/docs/decommission-and-redeploy.md +++ /dev/null @@ -1,36 +0,0 @@ -# Decommission and Redeploy — Intel® Agent Toolkit - -> **Warning:** Decommissioning destroys the entire Kubernetes cluster and all workloads, data, and secrets. It cannot be undone. - -## Step 1 — Decommission the cluster - -```bash -./es_auto_installer.sh teardown infrastructure -# removes the cluster and everything on it -``` - -What the decommission does: -- Runs Kubespray's `reset.yml` to remove all Kubernetes components from the node -- Removes all Helm releases and namespaces (`litellm`, `redis`, `monitoring`, etc.) -- Cleans up container images injected into containerd -- Removes the generated `hosts.yaml` inventory - > **Note:** not available in this release. - -> The `env//global_config.yaml`, `config.agent-toolkit.yaml` and `config.inference.yaml` files are **not** deleted — your settings are preserved for the next run. - -## Step 2 — Redeploy from scratch - -After decommission completes, set the components you want back to `true` in `env//global_config.yaml` and `env//config.agent-toolkit.yaml`, then run: - -```bash -# Edit env//global_config.yaml and env//config.agent-toolkit.yaml and turn components back on: -# auth_type: "litellm_vkey" (config.agent-toolkit.yaml) -# observability_enabled: true (global_config.yaml) -# llm_services_autodeploy_models: ["qwen2-5-coder-14b"] (config.agent-toolkit.yaml) -# redis_stack_enabled: true (config.agent-toolkit.yaml) -# pgvector_enabled: false (config.agent-toolkit.yaml) - -./es_auto_installer.sh install agent-toolkit -``` - -The script will deploy everything from scratch. Re-running `install agent-toolkit` is idempotent and applies config changes. \ No newline at end of file diff --git a/docs/deployment/decommission.md b/docs/deployment/decommission.md new file mode 100644 index 00000000..4e0de0ed --- /dev/null +++ b/docs/deployment/decommission.md @@ -0,0 +1,41 @@ +# Decommission and redeploy + +[← Docs index](../README.md) + +Use this page when you want to remove the Agent Toolkit from a cluster and install it again, for example after a failed run, or when you want a different set of models. Teardown deletes the workloads, persistent volumes, and secrets for the target you name. That cannot be undone. The YAML under `env//` is **kept**, so your domain, TLS paths, and model flags survive and you do not have to re-type them. + +## 1. Tear down + +From the Toolkit Manager directory (see [which repository to start from](../overview/meet.md#which-repository-to-start-from)): + +```bash +./toolkit_manager.sh teardown agent-toolkit +``` + +That removes the Agent Toolkit layer only — the components this repo owns (`redis`, `pgvector`, `keycloak_agent_config`, agent sandbox / OpenShell, KubeRay when on) and anything that depends on that layer — and deletes objects labelled `toolkit-manager.intel.com/env` and `toolkit-manager.intel.com/component`. Cluster, platform, and **inference stay** (LiteLLM and Langfuse are inference-layer; they are not removed). See Toolkit Manager [Agent Toolkit](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/agent-toolkit.md) (“keeps cluster, platform and inference intact”) and [teardown](https://github.com/intel/toolkit-manager/blob/main/docs/reference/cli.md#teardown). + +To tear down **everything** the installer created, including Kubernetes itself: + +```bash +./toolkit_manager.sh teardown infrastructure +``` + +`teardown infrastructure` removes the cluster. Use it only when you are ready to lose Kubernetes, not just the toolkit. The YAML under `env//` is kept. + +## 2. Install again + +If you want a different layout, edit `env/local/*.yaml` first (domain, models, storage, and so on). Then: + +```bash +./toolkit_manager.sh install agent-toolkit +``` + +`install` is idempotent. After it finishes: + +```bash +./toolkit_manager.sh validate agent-toolkit +``` + +## Next steps + +To stand the stack up again from scratch on one server, follow the [single-node quickstart](../getting-started/quickstart.md). The fields you can change before the next `install` are listed in [Configuration](../configuration/configuration.md). For several servers, use [multi-node deployment](multi-node.md). If install fails after redeploy, see [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md). diff --git a/docs/deployment/docker.md b/docs/deployment/docker.md new file mode 100644 index 00000000..f708e7a3 --- /dev/null +++ b/docs/deployment/docker.md @@ -0,0 +1,136 @@ +# Docker Compose + +[← Docs index](../README.md) + +This path is separate from Toolkit Manager. Compose uses the in-tree `docker/` bundle (`bash docker/deploy.sh`). `toolkit_manager.sh` installs Kubernetes. For a first run with Toolkit Manager, use the [single-node quickstart](../getting-started/quickstart.md). + +This path runs the agent stack as **containers on a single Linux host**, without Kubernetes. You still get a model engine (vLLM or OpenVINO™ Model Server), LiteLLM, Redis, and Postgres, started by Docker Compose rather than Helm. It is meant for a lab or development server where you do not want to provision a cluster. Production stays on Kubernetes. More engine detail: [`docker/README.md`](../../docker/README.md). + +## Prerequisites + +| Requirement | Minimum | +|---|---| +| Docker Engine | 24.0+ | +| Docker Compose | v2.20+ | +| RAM | 128 GB (256 GB if you start two or more LLMs) | +| Disk | 80 GB free | +| CPU | 96+ cores | +| Hugging Face token | Required for gated models (including the shipped default) | + +## 1. Edit `docker/config.cfg` + +The file shipped in the repo already sets a model. The default is gated Gemma, so put a Hugging Face token in `hugging_face_token=` before the first run (this path does **not** read `HF_TOKEN` from the shell): + +```ini +hugging_face_token=hf_your_token_here +models=google/gemma-4-26B-A4B-it +# serving_engine=vllm # default. Use openvino for OpenVINO™ Model Server +``` + +To use Qwen or several models instead (comma-separated, **no spaces**): + +```ini +models=Qwen/Qwen2.5-Coder-14B-Instruct,meta-llama/Llama-3.1-8B-Instruct +``` + +## 2. Deploy from the repository root + +```bash +bash docker/deploy.sh +``` + +Add `--observability` for Langfuse tracing. Other flags (`--full`, `--pull`, `--skip-build`, `--down`) are listed by `bash docker/deploy.sh --help`. + +If containers are already running with the same model list, the script leaves them alone and only creates containers for models that are new. Secrets are written to `docker/vault.yml` and `docker/.env`. Do not commit those files. + +## 3. Call a model + +LiteLLM listens on `http://localhost:4000`. The LiteLLM UI is at `http://localhost:4000/ui`. + +```bash +export LITELLM_MASTER_KEY=$(grep LITELLM_MASTER_KEY docker/.env | cut -d= -f2 | tr -d '"') + +curl http://localhost:4000/v1/models \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" + +curl http://localhost:4000/v1/chat/completions \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ + -H "Content-Type: application/json" \ + -d '{"model": "google/gemma-4-26B-A4B-it", "messages": [{"role": "user", "content": "Hello"}]}' +``` + +Use the full Hugging Face id as `"model"`: the same string you put in `models=` in `config.cfg`. + +## What is listening + +After a successful deploy, these ports are bound on the host. Credentials (database user, Redis password, LiteLLM master key) are in `docker/.env`. + +| Service | Port | URL | +|---|---|---| +| Model engine (vLLM or OVMS) | 2080+ | `http://localhost:2080/v1` (next model gets 2081, …) | +| LiteLLM | 4000 | `http://localhost:4000` | +| Flowise (if enabled) | 3000 | `http://localhost:3000` | +| Langfuse (if enabled) | 3002 | `http://localhost:3002` | +| Postgres | 5432 | `localhost:5432` | +| Redis | 6379 | `localhost:6379` | + +Credentials for Postgres and Redis are in `docker/.env`. Example: + +```bash +source docker/.env +psql "postgresql://${PGVECTOR_USER}:${PGVECTOR_PASSWORD}@localhost:5432/${PGVECTOR_DB}" +redis-cli -h localhost -p 6379 -a "${REDIS_PASSWORD}" +``` + +## Models and engines + +Put Hugging Face ids in `docker/config.cfg` (`models=`). Tuned flags and how to add a model: [`docker/README.md`](../../docker/README.md) and `docker/model-configs.yaml` (OpenVINO™: `docker/ovms-model-configs.yaml`). Do not edit generated `docker-compose.vllm.yml` or `litellm/config.yaml` by hand. + +## Optional flags in `config.cfg` + +```ini +serving_engine=vllm # vllm | openvino +tool_call_parser=qwen3_coder # none to disable (vLLM) +deploy_docker_fresh=off # on = install Docker if missing +deploy_agenticai_plugin=off # Flowise. Deprecated. Leave off. +deploy_observability=off # Langfuse +http_proxy= +https_proxy= +no_proxy=localhost,127.0.0.1,.genai-gateway,.redis,.postgres,.flowise +``` + +`serving_engine=openvino` generates an OpenVINO™ Model Server compose file from `docker/ovms-model-configs.yaml` instead of vLLM. Parser values and more flags: [`docker/README.md`](../../docker/README.md). + +## Troubleshooting + +| Issue | What to try | +|---|---| +| Docker `start-limit-hit` | Reset the unit and start it again: `sudo systemctl reset-failed docker.service && sudo systemctl start docker.service`. | +| `apt-get` hangs | Set the proxy in `config.cfg` or `/etc/apt/apt.conf`. If a stuck `apt-get` is holding the lock, `sudo pkill -f apt-get`. | +| vLLM slow first start | Weights are downloading (often ~28 GB). Wait 5–10 minutes before treating it as a failure. | +| Out of memory | Reduce the number of Hugging Face ids in `models=`. Each extra LLM needs tens of gigabytes. | +| Port 2080 already taken | Put both models in `config.cfg` so ports increment, or `docker stop` / `docker rm` the old container. | +| Model missing in LiteLLM | Open the generated `docker/litellm/config.yaml` and confirm the model id is listed. | +| Generator fails | Check `yq --version` and that `yq eval '.' docker/model-configs.yaml` parses. | + +```bash +docker compose -f docker/docker-compose.vllm.yml logs vllm- +``` + +## Stop the stack + +```bash +# Keep volumes +docker compose -f docker/docker-compose.yml -f docker/docker-compose.vllm.yml down + +# Delete data too (passwords are regenerated on the next deploy) +bash docker/deploy.sh --down +``` + +## Related pages + +- [Docs index](../README.md) +- [Single-node quickstart](../getting-started/quickstart.md): one-host Kubernetes install with Toolkit Manager +- [Configuration](../configuration/configuration.md): YAML for the Kubernetes install +- [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md#docker-compose) +- [Meet the Agent Toolkit](../overview/meet.md) diff --git a/docs/deployment/intel-arc.md b/docs/deployment/intel-arc.md new file mode 100644 index 00000000..d275c9b2 --- /dev/null +++ b/docs/deployment/intel-arc.md @@ -0,0 +1,29 @@ +# Intel® Arc™ GPU + +[← Docs index](../README.md) + +Serve models on Intel® Arc™ GPUs through Toolkit Manager, including Intel® Arc™ Pro B-Series (B70) and other Xe GPUs. + +## What to use + +1. Install the stack with Toolkit Manager as usual ([Prerequisites](../getting-started/prerequisites.md), then the [quickstart](../getting-started/quickstart.md) or [multi-node](multi-node.md)). On GPU hosts, Toolkit Manager installs the Intel GPU device plugin when Node Feature Discovery sees an Intel GPU — details for Arc Pro B-Series / B70 and other Xe GPUs: [Install the platform](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/install-platform.md) in Toolkit Manager. +2. Deploy a catalog model that uses the `vllm-xpu` runtime, for example `vllm-xpu-llama-3-1-8b` or `vllm-xpu-gpt-oss-20b`: + + ```bash + ./model-manager deploy vllm-xpu-llama-3-1-8b + # or: ./model-manager deploy --server vllm-xpu + ``` + + Catalog entries, flags, and access steps: [Deploy a model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md) in Toolkit Manager. + +3. For the `vllm-xpu` engine itself (images, shared settings, which models may use it): [Runtimes](https://github.com/intel/inference-toolkit/blob/main/docs/configuration/runtimes.md) in Intel® Inference Toolkit. + +## Next steps + +- [Deploy a model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md) — `model-manager` and the catalog +- [Runtimes](https://github.com/intel/inference-toolkit/blob/main/docs/configuration/runtimes.md) — `vllm-xpu` and other engines +- [Configuration](../configuration/configuration.md) — Agent Toolkit YAML under `env/local/` + +--- + +*Intel, the Intel logo, and Arc are trademarks of Intel Corporation or its subsidiaries.* diff --git a/docs/deployment/multi-node.md b/docs/deployment/multi-node.md new file mode 100644 index 00000000..73211128 --- /dev/null +++ b/docs/deployment/multi-node.md @@ -0,0 +1,130 @@ +# Multi-node deployment + +[← Docs index](../README.md) + +Use this guide when you have more than one host and you want the Agent Toolkit spread across them. A typical layout is one **control-plane** node that runs Kubernetes and the stack services, plus one or more **worker** nodes that take extra model pods when a single host is not enough CPU or memory. + +Kubernetes itself is installed by Kubespray. List machines in `env//nodes.yaml` (`nodes_control_plane`, `nodes_workers`); the installer regenerates `inventory/hosts.yaml` from that file on every run. + +If you only have one host, follow the [single-node quickstart](../getting-started/quickstart.md) instead. + +For a high-speed fabric and NVMe Ceph, see [Rack-scale deployment](rack-scale.md) instead of this Ethernet multi-node path. + +Complete **[Prerequisites](../getting-started/prerequisites.md)** on every node before you start (SSH and host prep). Self-signed TLS is fine for a first cluster; `/etc/hosts` can wait until browsers need the gateway names. + +## Topologies + +Most teams start with a single control plane and add workers for inference. Three control-plane nodes are only needed if you cannot tolerate losing the Kubernetes API on one node. + +| Layout | When to choose it | +|---|---| +| 1 control plane + N workers | Production that can scale models out. The control plane also runs as a worker unless you taint it. | +| 3 control planes + N workers | High availability for etcd and the API server. Put a load balancer in front and point `base_domain_name` at the load-balancer IP. | + +The Envoy gateway binds to the control-plane node by default. With several control planes, traffic should land on the load balancer, not on a single node's IP. + +## 1. Seed config, then list every node + +Run these from the Toolkit Manager directory, on the host that will drive the install. [Meet the Agent Toolkit](../overview/meet.md) explains that Toolkit Manager installs, updates, and tears the toolkit down. + +```bash +chmod +x toolkit_manager.sh +./toolkit_manager.sh configure +./toolkit_manager.sh init agent-toolkit +``` + +`init` seeds `env/local/nodes.yaml` for a single localhost node. For a real cluster, edit that file. The installer writes `inventory/hosts.yaml` from it on every run, so do not hand-edit `hosts.yaml` while `nodes.yaml` lists machines. + +Here is a control plane plus two workers. Replace IPs, hostnames, the SSH user, and the key path with your values: + +```yaml +# env/local/nodes.yaml +nodes_control_plane: + - ip: 10.0.0.1 + hostname: master1 + +nodes_workers: + - ip: 10.0.0.2 + hostname: worker1 + - ip: 10.0.0.3 + hostname: worker2 + +nodes_ssh_user: "ubuntu" +nodes_ssh_key: "/home/ubuntu/.ssh/id_rsa" # chmod 600 +``` + +The host that runs `install` must be able to SSH to every node with that key. Password logins are not enough; Ansible will fail. Jump hosts and hand-written Kubespray inventory are covered in Toolkit Manager: [Install the platform](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/install-platform.md) and [Multi-node](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/multi-node.md). + +Open these ports between nodes: Kubernetes API `6443`, etcd `2379–2380`, Calico BGP `179`, kubelet `10250`. Keep the NodePort range `30000–32767` off the public internet. Redis in this stack is ClusterIP on purpose; do not publish it as NodePort. + +## 2. Domain, storage, and TLS + +The files under `env/local/` are the same ones the [quickstart](../getting-started/quickstart.md) uses. On several nodes, the settings that usually change are the domain and **storage**. `local-path` only works on one node; use `nfs` or `ceph` when pods can land on any worker. Leave `gateway_tls_mode: selfsigned` for a first run (installer CA + `--resolve` for the smoke test). Custom certs and `/etc/hosts` for browsers: [Prerequisites](../getting-started/prerequisites.md#2-dns-and-tls). + +```yaml +# env/local/global_config.yaml +base_domain_name: inteltoolkits.ai +storage_backend: ceph +``` + +```yaml +# env/local/config.agent-toolkit.yaml +auth_type: litellm_vkey +llm_services_autodeploy_models: ["qwen2-5-coder-14b"] +``` + +Catalog names: [quickstart](../getting-started/quickstart.md#3-choose-a-model) (`./model-manager list --catalog`). Gated Hugging Face models need `export HF_TOKEN=…` in the same shell as `install`; the default `qwen2-5-coder-14b` does not. + +## 3. Install from the control plane + +```bash +./toolkit_manager.sh install agent-toolkit +``` + +Kubespray reads the generated `hosts.yaml` and provisions Kubernetes first (often 20–30 minutes on a fresh set of nodes). After that, the installer deploys platform, inference, and the toolkit. The command is idempotent: if it stops part-way, run it again. + +## 4. Confirm the cluster and the API + +Wait until every node is Ready. The model pod may stay in `ContainerCreating` while it downloads weights. + +```bash +export KUBECONFIG=$(pwd)/env/local/kubeconfig.yaml +kubectl get nodes -o wide +kubectl get pods -A +``` + +Then run the same gateway smoke test as the [single-node quickstart](../getting-started/quickstart.md#5-confirm-it-works) (`--resolve` and the installer CA). Redis, pgvector, and the sandbox are already running; in-cluster URLs are under [What also came up](../getting-started/quickstart.md#what-also-came-up). + +## Add a worker later + +Do **not** re-run `install` to grow a running cluster. Use Toolkit Manager node scaling: + +1. Add the worker under `nodes_workers` in `env//nodes.yaml`. +2. Set up passwordless SSH from the installer host to the new node, the same way as [Prerequisites](../getting-started/prerequisites.md#1-ssh-keys). +3. Preview, then apply: + + ```bash + ./toolkit_manager.sh add-node --dry-run + ./toolkit_manager.sh add-node + ``` + +To remove a worker, delete it from `nodes_workers`, then run `./toolkit_manager.sh remove-node --dry-run` and `./toolkit_manager.sh remove-node`. Full rules: [Node scaling](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/node-scaling.md) and [CLI](https://github.com/intel/toolkit-manager/blob/main/docs/reference/cli.md) in Toolkit Manager. + +## Notes + +- **Redis** runs as a single StatefulSet in this release, shared by all agents. It is not a Redis Cluster. High availability is a chart-values change, not the default. +- **Model weights** live on the shared `model-store` PVC (`pvc_name` default `model-store`, size `llm_services_model_store_size`, default `200Gi`). On multi-node that volume must be ReadWriteMany (`storage_backend: nfs`, `ceph`, `netapp-trident`, or a custom RWX class — not `local-path`). See Toolkit Manager [Storage](https://github.com/intel/toolkit-manager/blob/main/docs/configuration/configuration.md#storage) and Inference Toolkit [Model catalog](https://github.com/intel/inference-toolkit/blob/main/docs/configuration/catalog.md#model-store-size). +- **Firewall:** in addition to the ports above, do not expose `30000–32767` to the internet. Leave Redis as ClusterIP. + +## Troubleshooting + +| Symptom | What to try | +|---|---| +| Node `NotReady` | On that node, run `systemctl status kubelet` and check the kubelet logs. | +| Kubespray SSH refused | Confirm IPs and `nodes_ssh_key` (or per-node `ssh_key`) in `nodes.yaml`, and that you can `ssh` by hand with that key. | +| Pods stuck `Pending` | `kubectl describe node `: usually CPU, memory, or a taint that blocks scheduling. | +| Model pod never lands on a worker | Same check on that worker: resources and taints. | + +## Next steps + +Once nodes are Ready and chat completions work, you can change YAML in [Configuration](../configuration/configuration.md), copy in-cluster URLs from the [backend connection reference](../reference/backend-connections.md), or [tear the stack down](decommission.md) and install again. The first-run path on one host is the [single-node quickstart](../getting-started/quickstart.md). Failures: [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md). diff --git a/docs/deployment/proxy.md b/docs/deployment/proxy.md new file mode 100644 index 00000000..19ab75ba --- /dev/null +++ b/docs/deployment/proxy.md @@ -0,0 +1,35 @@ +# Running behind a corporate proxy + +[← Docs index](../README.md) + +If this host reaches the internet only through an HTTP proxy, put the proxy URL in the generated YAML so the installer can copy it into every workload that needs outbound access: image pulls, Hugging Face weight downloads, and LiteLLM bootstrap. Without these keys, `install` will hang or fail the first time a pod tries to leave the cluster. + +## 1. Set the three keys + +After `init`, edit `env/local/global_config.yaml`: + +```yaml +http_proxy: "http://your.proxy.server:port" +https_proxy: "http://your.proxy.server:port" +no_proxy: "localhost,127.0.0.1,.svc,.cluster.local,," +``` + +`no_proxy` must include `.svc` and `.cluster.local` so pod-to-pod traffic does not go through the proxy. Add your company domains and the cluster pod/service CIDRs. + +## Example + +```yaml +http_proxy: "http://proxy.corporate.com:8080" +https_proxy: "http://proxy.corporate.com:8080" +no_proxy: "localhost,127.0.0.1,.mycompany.com,.svc,.cluster.local,10.233.64.0/18,10.233.0.0/18" +``` + +Then run `./toolkit_manager.sh install agent-toolkit` as usual. The installer reads these keys from `global_config.yaml`; you do not also need to export them in the shell unless a tool you run by hand (for example `helm` or `curl`) needs the same proxy. + +## apt and Docker + +If `apt-get` hangs, the host itself may still be using a proxy in `/etc/apt/apt.conf`. Remove or fix those `Acquire::http::Proxy` lines so package installs can reach your mirror. Docker Engine has its own proxy config if image pulls fail after the YAML above is set. + +## Next steps + +Finish [Prerequisites](../getting-started/prerequisites.md) if you have not already, then continue with the [single-node quickstart](../getting-started/quickstart.md) or [Configuration](../configuration/configuration.md) if you still need to set domain and TLS. Proxy keys live in `global_config.yaml` with the other cluster-wide settings. If image pulls still fail, see [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md). diff --git a/docs/deployment/rack-scale.md b/docs/deployment/rack-scale.md new file mode 100644 index 00000000..801dda6d --- /dev/null +++ b/docs/deployment/rack-scale.md @@ -0,0 +1,27 @@ +# Rack-scale AI fabric + +[← Docs index](../README.md) + +Deploy the Agent Toolkit on a rack through Toolkit Manager. The rack is described in `env//rack-profile.yaml`, and one `install agent-toolkit` sets up the fabric, Kubernetes, Ceph, and the toolkit. Clos, L2, and `none` (no fabric) racks are validated in this release; star is not. + +## What to use + +Use one env for every command (`--env rack` here): + +1. `./toolkit_manager.sh init agent-toolkit --env rack` +2. In `env/rack/global_config.yaml`, set `rack_scale_enabled: true`, `metallb_ip_range`, and `storage_backend: ceph`. Write `env/rack/rack-profile.yaml` and leave `env/rack/nodes.yaml` empty. [Rack-scale deployment](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/rack-scale.md) in Toolkit Manager covers these settings, the topologies, GPU nodes, validation, and troubleshooting. +3. `./toolkit_manager.sh install agent-toolkit --env rack` + +To add or remove a worker later, edit `rack-profile.yaml`, not `nodes.yaml`. See [Node scaling](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/node-scaling.md#rack-scale) in Toolkit Manager. + +For a multi-host install without the fabric profile, use [Multi-node deployment](multi-node.md). + +## Next steps + +- [Rack-scale deployment](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/rack-scale.md) — Toolkit Manager +- [Multi-node deployment](multi-node.md) — Ethernet multi-node without the fabric profile +- [Prerequisites](../getting-started/prerequisites.md) — host prep before install + +--- + +*Intel, the Intel logo and Xeon are trademarks of Intel Corporation or its subsidiaries.* diff --git a/docs/examples/multi-node/hosts.yaml b/docs/examples/multi-node/hosts.yaml deleted file mode 100644 index d7219448..00000000 --- a/docs/examples/multi-node/hosts.yaml +++ /dev/null @@ -1,58 +0,0 @@ - all: - hosts: - inference-control-plane-01: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-control-plane-02: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-control-plane-03: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-workload-node-01: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-workload-node-02: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-workload-node-03: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-workload-node-04: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - inference-workload-node-05: - ansible_host: "{{ private_ip }}" - ansible_user: "{{ ansible_user }}" - ansible_ssh_private_key_file: /path/to/your/ssh/key - children: - kube_control_plane: - hosts: - inference-control-plane-01: - inference-control-plane-02: - inference-control-plane-03: - kube_node: - hosts: - inference-workload-node-01: - inference-workload-node-02: - inference-workload-node-03: - inference-workload-node-04: - inference-workload-node-05: - etcd: - hosts: - inference-control-plane-01: - inference-control-plane-02: - inference-control-plane-03: - k8s_cluster: - children: - kube_control_plane: - kube_node: - calico_rr: - hosts: {} \ No newline at end of file diff --git a/docs/examples/single-node/hosts.yaml b/docs/examples/single-node/hosts.yaml deleted file mode 100644 index 49916653..00000000 --- a/docs/examples/single-node/hosts.yaml +++ /dev/null @@ -1,22 +0,0 @@ -all: - hosts: - localhost: - ansible_connection: local - ansible_python_interpreter: "{{ ansible_playbook_python }}" - ansible_user: "{{ lookup('env', 'USER') }}" - children: - kube_control_plane: - hosts: - localhost: - kube_node: - hosts: - localhost: - etcd: - hosts: - localhost: - k8s_cluster: - children: - kube_control_plane: - kube_node: - calico_rr: - hosts: {} \ No newline at end of file diff --git a/docs/faq-and-troubleshooting/frequently-asked-questions.md b/docs/faq-and-troubleshooting/frequently-asked-questions.md new file mode 100644 index 00000000..2b468ffe --- /dev/null +++ b/docs/faq-and-troubleshooting/frequently-asked-questions.md @@ -0,0 +1,130 @@ +# Frequently Asked Questions + +[← Docs index](../README.md) + +Short answers to the questions that come up most often. Installation steps stay in the [single-node quickstart](../getting-started/quickstart.md); this page does not repeat them. + +**On this page** + +- [What is the Agent Toolkit?](#what-is) +- [How is this different from LangGraph or CrewAI?](#vs-frameworks) +- [Do I need a GPU?](#gpu) +- [Can I use OpenAI, Anthropic, or Gemini?](#cloud-models) +- [Where do I run the installer?](#where-installer) +- [Which YAML files do I edit?](#which-yaml) +- [Do I need a Hugging Face token?](#hf-token) +- [How do I know it is up?](#is-it-up) +- [Where is the API key?](#api-key) +- [Can I replace Redis / LiteLLM / the sandbox?](#replace) +- [Is this for on-prem or air-gapped sites?](#on-prem) +- [What license is it under?](#license) + + + +## What is the Agent Toolkit? + +Intel® Agent Toolkit is the infrastructure for production agents. [Toolkit Manager](../overview/meet.md#which-repository-to-start-from) installs, updates, and tears it down. A model endpoint is not enough for production agents: they also need Redis for short-term memory, PostgreSQL with pgvector for long-term memory, a code sandbox, and optionally Ray. Applications still call an OpenAI-compatible HTTPS API; only the base URL and key change. + +See [Meet the Agent Toolkit](../overview/meet.md) for what install brings up and a request-flow diagram. + + + +## How is this different from LangGraph or CrewAI? + +LangGraph and CrewAI are **orchestration** libraries: they decide when to call the model and which tool to invoke. This toolkit is the **infrastructure** those libraries use: the gateway, model serving, memory, and sandbox. Run LangGraph or CrewAI **on top of** this stack by pointing the framework at `https://litellm./v1`. + + + +## Do I need a GPU? + +No. This release runs models on Intel® processors. You can add a cloud or GPU endpoint on the same LiteLLM gateway later. It is optional. + + + +## Can I use OpenAI, Anthropic, or Gemini? + +Yes. LiteLLM can proxy those providers next to the local vLLM models. Your application still uses one base URL. How to add a provider is in LiteLLM's own docs; local models are the default this installer deploys. + + + +## Where do I run the installer? + +From the Toolkit Manager directory. That repository contains `./toolkit_manager.sh`. `init agent-toolkit` clones this repository under `ext/`. Toolkit Manager installs, updates, and tears the toolkit down. See [Meet the Agent Toolkit](../overview/meet.md). Related software: [Intel® Inference Toolkit](https://github.com/intel/inference-toolkit) and [Intel® Chatbot Toolkit](https://swcatalog.intel.com/developer/docs/enterprise-rag). + + + +## Which YAML files do I edit? + +Only the copies under `env/local/` (or `env//`) after `init`. Typical files: + +| File | When you touch it | +|---|---| +| `global_config.yaml` | Domain, TLS, storage, proxy | +| `config.agent-toolkit.yaml` | Auth (`auth_type`), models to start (`llm_services_autodeploy_models`), Redis/pgvector/sandbox/KubeRay/OpenShell | +| `config.inference.yaml` | Inference-layer flags (hybrid router, semantic router) when you need them | +| `models.yaml` | Catalog entries and per-model CPU/memory | + +Details: [Configuration](../configuration/configuration.md). + + + +## Do I need a Hugging Face token? + +Only for **gated** models (Llama, Gemma). The default model `qwen2-5-coder-14b` is ungated. If you need a token: + +```bash +export HF_TOKEN=hf_... +``` + +Do that in the same shell as `install`. Create a Read token and accept the model license on Hugging Face first. + + + +## How do I know it is up? + +```bash +kubectl get nodes # Ready +kubectl get pods -A # Running (the vLLM pod can stay ContainerCreating while weights download) +``` + +Then `curl` `/v1/models` with the master key. If that lists your model, send `/v1/chat/completions`. Commands: [Single-node quickstart](../getting-started/quickstart.md#5-confirm-it-works). + + + +## Where is the API key? + +The install creates a **master key** for admin and smoke tests: + +```bash +kubectl get secret litellm-master-key -n litellm \ + -o jsonpath='{.data.master_key}' | base64 -d +``` + +Do not put that key in application code. For agents, create a **virtual key** and use that instead: [Access the model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md#access-the-model) and [Build your first agent](../getting-started/first-agent.md). + + + +## Can I replace Redis / LiteLLM / the sandbox? + +Yes, in principle. Each capability (gateway, memory, sandbox) has a default implementation and a defined job, so a later swap does not require rebuilding the rest of the stack. On day one, use the defaults. Swapping a provider is not required to get a working agent. + + + +## Is this for on-prem or air-gapped sites? + +On-prem Intel® hardware is the target. The first install needs internet access to pull container images and Helm charts. A fully air-gapped site (pre-loaded images, no outbound network) is a follow-on operations topic, not the quickstart. + + + +## What license is it under? + +Apache License 2.0 for this repository. Models have their own licenses on Hugging Face. Gated models require you to accept those terms before you can download weights. + +## Related pages + +- [Meet the Agent Toolkit](../overview/meet.md): what the toolkit is +- [Docs index](../README.md): every guide in this cluster +- [Single-node quickstart](../getting-started/quickstart.md): first install +- [Configuration](../configuration/configuration.md): YAML under `env/local/` +- [Glossary](../reference/glossary.md): terms used in the answers above +- [Troubleshooting](troubleshooting.md): installer and API failures diff --git a/docs/faq-and-troubleshooting/troubleshooting.md b/docs/faq-and-troubleshooting/troubleshooting.md new file mode 100644 index 00000000..be47e1b5 --- /dev/null +++ b/docs/faq-and-troubleshooting/troubleshooting.md @@ -0,0 +1,44 @@ +# Troubleshooting + +[← Docs index](../README.md) + +Problems you hit while installing or calling the API. If the error is specific to one component (sandbox, guardrails, Docker Compose), jump to that guide at the bottom of the page. For “where do I run the installer?” and similar, see the [FAQ](frequently-asked-questions.md). + +## Installer and Kubernetes + +| What you see | What to try | +|---|---| +| `toolkit_manager.sh: No such file or directory` | You are in this toolkit repo. `cd` to Toolkit Manager and run the commands from that root. It installs, updates, and tears the toolkit down. [Meet the Agent Toolkit](../overview/meet.md) · [FAQ](frequently-asked-questions.md#where-installer) | +| SSH connection refused during Kubespray | Check node IPs and the SSH key in `env/local/nodes.yaml` (the installer regenerates `inventory/hosts.yaml` from it). Confirm passwordless SSH from the installer host. [Prerequisites](../getting-started/prerequisites.md#1-ssh-keys) | +| Node `NotReady` | On that node, run `systemctl status kubelet` and inspect the kubelet journal. | +| Pods stuck `Pending` | `kubectl describe pod -n ` and `kubectl describe node`: usually CPU, RAM, or a taint that blocks scheduling. | +| vLLM stays `ContainerCreating` / `Init` | Weights are still downloading. 10–15 minutes is normal. Follow progress with `kubectl logs -n `. | +| `pull access denied` | Docker Hub / registry login is missing, or the image name does not exist in that registry. | +| Hugging Face `401` | The model is gated. Create a Read token, accept the license on Hugging Face, and `export HF_TOKEN=...` in the same shell as `install`. | + +## Gateway and API + +| What you see | What to try | +|---|---| +| `curl` TLS error | Prefer `--cacert env/local/logs/toolkit-manager-ca.crt` and `--resolve` as in the [quickstart](../getting-started/quickstart.md#5-confirm-it-works). Use `-k` only to skip verify. The hostname must match `base_domain_name`. [Prerequisites](../getting-started/prerequisites.md#2-dns-and-tls) | +| `401` from `/v1/models` | Wrong or missing `Authorization: Bearer`. Get the key from secret `litellm-master-key` in namespace `litellm`. | +| Empty model list | Set `llm_services_autodeploy_models` to at least one catalog name in `config.agent-toolkit.yaml`, then re-run `install`. | +| `NRI pre-flight failed: not enough physical cores` | The default model took the only NUMA node's cores. Set an explicit `cpu:` in `models.yaml`, or `./model-manager undeploy ` and deploy a smaller model. | +| Chat hangs / no tokens | `kubectl get pods -A`: is the model pod Running? Check the trace UI at `https://langfuse.`. | +| `finish_reason: content_filter` with HTTP 200 | The guardrail blocked the prompt. That is not a transport error. [Guardrails](../configuration/guardrails.md) | + +## Redis / pgvector / sandbox + +| What you see | What to try | +|---|---| +| Redis `WRONGPASS` | The URL must be `redis://default:@...`. Read `REDIS_URL` from the Kubernetes secret instead of guessing the password. | +| Cannot reach Redis from outside the cluster | Redis is ClusterIP on purpose. Use `kubectl port-forward`; do not switch the Service to NodePort. | +| Sandbox `/healthz` fails | `kubectl get pods -n agent-sandbox-system`. Port-forward `sandbox-router-svc`. [Agent sandbox](../reference/agent-sandbox.md) | + +## Docker Compose + +See the table in [Docker](../deployment/docker.md#troubleshooting). + +## Next steps + +If the table does not match what you see, the [FAQ](frequently-asked-questions.md) covers the common “am I in the right repo?” questions. The [single-node quickstart](../getting-started/quickstart.md) and [multi-node](../deployment/multi-node.md) guides have the expected healthy state. Guardrail and sandbox specifics are in [Guardrails](../configuration/guardrails.md) and [Agent sandbox](../reference/agent-sandbox.md). diff --git a/docs/faq-and-troubleshooting/validate.md b/docs/faq-and-troubleshooting/validate.md new file mode 100644 index 00000000..c3cebf29 --- /dev/null +++ b/docs/faq-and-troubleshooting/validate.md @@ -0,0 +1,131 @@ +# Validate the stack + +[← Docs index](../README.md) + +Two checks cover a Toolkit Manager install. **Preflight** looks at every host before components are installed. **Validate** checks the components that the install actually enabled. + +Run both from the Toolkit Manager checkout, after `./toolkit_manager.sh init agent-toolkit`. + +| Check | When | Command | Output | +|---|---|---|---| +| Preflight | At the start of `./toolkit_manager.sh install`. You can also run it on its own | `ext/enterprise.agent-toolkit/playbooks/preflight-check.yml` | `env/local/logs/health-report-latest.json`, `.html`, and `.txt`. The `.txt` summary is also printed | +| Validate | After the install | `./toolkit_manager.sh validate ` | Per-component checks in the run output. A failure stops the run and prints the reason | + +Components that are not enabled are skipped. They are not reported as failures. + +## Preflight + +Preflight checks node readiness on every host in the inventory. No result stops the install. The only change it makes is the Kubelet DNS setting. See [Preflight fails on the Kubelet DNS file](#preflight-fails-on-the-kubelet-dns-file). + +| Status | Checks | Meaning | +|---|---|---| +| **FAIL** | Time sync, Kubelet DNS file, unfinished Kubernetes install, node connection, swap in use, root and containerd disk under 10% free, external DNS, gateway reachable | Fix these. They are also listed in the `PREFLIGHT WARNING` block | +| **WARN** | CPU governor is not `performance`, THP is `always`, Hugging Face token is invalid | Tuning or model access. The install continues | +| **PENDING** | Node resource pressure before the cluster exists. Hugging Face token is not set | Checked on a later run: after the install, or with `HF_TOKEN` exported | +| **OK** | Kernel and OS version, kubelet version (`not installed` before the cluster exists), NUMA topology | Recorded in the report | + +On a node whose CPU governor is `powersave`: + +```text + Network connectivity [ OK ] (reachable via ICMP ping ) + Platform health [ WARN ] governor=powersave freq=3343MHz max=3900MHz + WARNING: [platform-health] CPU governor on node1 + Hint: Set performance: cpupower frequency-set -g performance + RESULT: 2 layers — 1 PASSED, 1 WARNING +``` + +### Runs with the install + +In an environment created with `init agent-toolkit`, `./toolkit_manager.sh install` runs the preflight first: on a new cluster before Kubespray, otherwise before the components. Runs with `--only` skip it. To turn it off, set `node_preflight_enabled: false` in `env/local/config.agent-toolkit.yaml`. The checks are capped at 5 minutes. Past that, the install continues. The run output is saved to `env/local/logs/preflight-check.log`. + +### Run it on its own + +From the Toolkit Manager checkout, after `init agent-toolkit`. For several nodes, list them in `env/local/nodes.yaml` first (`hosts.yaml` is generated from it). See [Multi-node deployment](../deployment/multi-node.md#1-seed-config-then-list-every-node). + +```bash +export HF_TOKEN= # optional: also checks the token for gated models +.venv/bin/ansible-playbook -i env/local/inventory/hosts.yaml \ + ext/enterprise.agent-toolkit/playbooks/preflight-check.yml +``` + +The report is `env/local/logs/health-report-latest.json` and `.html`. A summary is printed at the end of the run. + +## Validate + +`validate` runs the checks of every enabled component in the target and its dependencies. `--only` limits the run to that target. A healthy stack ends with `failed=0` in the recap. + +```bash +./toolkit_manager.sh validate agent-toolkit +``` + +One layer or component: + +```bash +./toolkit_manager.sh validate platform --only +./toolkit_manager.sh validate inference --only +./toolkit_manager.sh validate litellm --only +``` + +## What validate checks + +| Layer | Component | Checks | +|---|---|---| +| Infrastructure | kubernetes | kubectl and kubeconfig, API server reachable, node readiness, server version | +| | storage (NFS, Ceph, Trident) | CSI driver and node plugin, StorageClass, exactly one default class. Ceph health and OSDs | +| | kata_containers | kata-deploy rollout, requested RuntimeClasses | +| Platform | cert-manager, MetalLB, Envoy Gateway | Releases, controllers ready, IP pool, GatewayClass and Gateway accepted, TLS secret | +| | Istio | istiod, ztunnel on every node, mesh-wide mTLS | +| | PostgreSQL, SeaweedFS | Database cluster ready, S3 gateway ready | +| | observability | Prometheus Operator, Grafana, Node Exporter, Loki, Tempo, OTel Collector | +| | NRI balloons, NFD | Policy and DaemonSet ready, CPU feature labels on nodes | +| | Keycloak (when enabled) | Operator and instances ready | +| Inference | KServe, model services | CRDs and controllers, serving runtimes, deployed models, CPU policy | +| | LiteLLM | Deployment ready, readiness endpoint, master key. A request through the content-safety guardrail and a chat request through LiteLLM | +| | Langfuse, vLLM Semantic Router | Web and worker deployments. Router and dashboard routed | +| Agent toolkit | Redis Stack, pgvector | Pods, Redis PING and RediSearch, pgvector extension and credentials | +| | Agent sandbox | Controller, router, CRDs, templates, warm pools, and the Kata template | +| | OpenShell, KubeRay | Gateway ready. Operator and head pod | + +Burn tests, the proxy checks, and a post-deploy report file are not in this release. Node-level checks (time sync, disk, swap, CPU governor, THP, DNS, gateway) are in [Preflight](#preflight). + +## Troubleshooting + +### Preflight fails on NTP sync + +`chronyd` or `systemd-timesyncd` needs to be running and synchronized on every node: + +```bash +.venv/bin/ansible -i env/local/inventory/hosts.yaml all -b -m shell -a "timedatectl status | grep synchronized" +``` + +### Preflight fails on the Kubelet DNS file + +On Ubuntu and Fedora, Kubespray points kubelet at `/run/systemd/resolve/resolv.conf`, which exists while `systemd-resolved` runs. Without it, Kubernetes does not start. When no node runs `systemd-resolved`, the preflight writes `kube_resolv_conf: "/etc/resolv.conf"` and `resolvconf_mode: "none"` to `env/local/kubespray_extra.yml` (reported as **Kubelet DNS setting**) and the install continues. It reports FAIL when some nodes run `systemd-resolved` and others do not. Make the nodes the same, then install again. With the preflight off (`node_preflight_enabled: false`), write those two lines yourself on such hosts. + +### Preflight fails on an unfinished Kubernetes install + +An install that stopped during `kubeadm` leaves `/var/lib/kubelet/config.yaml` on the node. A plain re-run then skips `kubeadm init` and fails later (`secrets is forbidden` on `kubeadm token create`). Reset the nodes, then install again: + +```bash +./toolkit_manager.sh teardown kubernetes +./toolkit_manager.sh install agent-toolkit +``` + +### Preflight fails on a node connection + +The playbook runs on the installer machine and runs some steps on each node (Kata setup, CPU pinning). A node reached over SSH must use SSH from the installer host, not run those steps locally. List every machine in `env/local/nodes.yaml` with working `nodes_ssh_user` / `nodes_ssh_key` (or per-node SSH fields); the installer regenerates `inventory/hosts.yaml` from that file. Do not hand-edit `hosts.yaml`. Then install again. See [multi-node](../deployment/multi-node.md#1-seed-config-then-list-every-node). + +### A model is still loading + +Large models can take 5–15 minutes to load. Re-run validation once they are Ready: + +```bash +kubectl get llminferenceservices,inferenceservices -n llm-inference +./toolkit_manager.sh validate inference +``` + +## Next steps + +- [Single-node quickstart](../getting-started/quickstart.md): the install these checks follow +- [Troubleshooting](troubleshooting.md): installer, API, Redis, and model-pod failures +- [Decommission](../deployment/decommission.md): tear down after a failed Kubernetes install diff --git a/docs/getting-started/first-agent.md b/docs/getting-started/first-agent.md new file mode 100644 index 00000000..ac9701a5 --- /dev/null +++ b/docs/getting-started/first-agent.md @@ -0,0 +1,125 @@ +# Build your first agent + +[← Docs index](../README.md) + +This guide builds a LangChain agent that calls the model through the Agent Toolkit gateway and uses a tool. When it finishes, you have a working agent script, and Langfuse shows each model request the agent made. + +Complete the [single-node quickstart](quickstart.md) first. The agent uses the same gateway and model. Give it a LiteLLM **virtual key**, not the master key (the master key is LiteLLM admin only). + +## Before you begin + +| Requirement | Detail | +|---|---| +| A working install | The quickstart verify curls return a chat completion. | +| `auth_type: litellm_vkey` | LiteLLM issues keys and sends gateway traces to Langfuse (the `init` default). | +| A LiteLLM virtual key | Create one before you run the agent: [Access the model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md#access-the-model) in Toolkit Manager. | +| A model with tool calling | The examples use `qwen2-5-coder-14b`, the quickstart model. Llama 3.1 8B does not support parallel tool calls. | +| Python 3.10 or later | On the install host, or on a machine whose `/etc/hosts` maps the gateway hostnames to the host's IP. | + +## 1. Set up the environment + +Create a virtual environment and install the packages: + +```bash +python3 -m venv ~/first-agent && source ~/first-agent/bin/activate +pip install "langchain>=1.0,<2" "langchain-openai>=1.0,<2" +``` + +Set the connection variables. Run the `cp` from the Toolkit Manager directory. Paste the virtual key you created (not the master key from the secret): + +```bash +export AGENT_TOOLKIT_BASE_URL=https://litellm.inteltoolkits.ai/v1 # https://litellm./v1 +export AGENT_TOOLKIT_API_KEY=sk-... # LiteLLM virtual key + +cp env/local/logs/toolkit-manager-ca.crt ~/first-agent/ca.crt +export SSL_CERT_FILE=~/first-agent/ca.crt +``` + +| Variable | Purpose | +|---|---| +| `AGENT_TOOLKIT_BASE_URL` | The OpenAI-compatible endpoint of the gateway. | +| `AGENT_TOOLKIT_API_KEY` | The LiteLLM virtual key the agent sends to the gateway. | +| `SSL_CERT_FILE` | Trusts the root CA the installer generated (`gateway_tls_mode: selfsigned`). | + +Set `SSL_CERT_FILE` **after** `pip install`. It replaces the default trust store, so `pip` can no longer reach PyPI while it is set. With a CA-issued certificate, omit it. + +## 2. Write the agent + +Save as `agent.py`: + +```python +import os + +from langchain.agents import create_agent +from langchain_core.tools import tool +from langchain_openai import ChatOpenAI + + +@tool +def multiply(a: float, b: float) -> float: + """Multiply two numbers.""" + return a * b + + +llm = ChatOpenAI( + model="qwen2-5-coder-14b", + base_url=os.environ["AGENT_TOOLKIT_BASE_URL"], + api_key=os.environ["AGENT_TOOLKIT_API_KEY"], + temperature=0, +) + +agent = create_agent( + model=llm, + tools=[multiply], + system_prompt="You are a concise assistant. Use the multiply tool for arithmetic.", +) + +result = agent.invoke( + {"messages": [{"role": "user", "content": "What is 23.5 multiplied by 4?"}]} +) +print(result["messages"][-1].content) +``` + +| Part | Purpose | +|---|---| +| `ChatOpenAI` | The LangChain OpenAI client. `base_url` and `api_key` point it at the gateway instead of OpenAI. No other change is needed. | +| `@tool` | Turns a Python function into a tool. The docstring is the description the model reads to decide when to call it. | +| `create_agent` | Runs the agent loop: the model requests a tool, LangChain runs it, and the result goes back to the model until it returns a final answer. | + +## 3. Run it + +```bash +python agent.py +``` + +The output is the final answer, for example `23.5 multiplied by 4 is 94.`. The model chose to call `multiply`, LangChain ran it, and the model wrote the answer from the result. + +## 4. Check the traces in Langfuse + +The gateway sends every model request to Langfuse automatically. No code or configuration is needed. + +Open `https://langfuse.` (for example `https://langfuse.inteltoolkits.ai`) and select **Traces**. Each run of `agent.py` produces one trace per model request, usually two: + +1. The request in which the model asks to call `multiply` with `a: 23.5, b: 4`. +2. The request that includes the tool result, `94.0`, in which the model writes the final answer. + +Each trace shows the prompt, the completion, token counts, latency, and the model that served the request. + +## Troubleshooting + +| Symptom | Resolution | +|---|---| +| `SSL: CERTIFICATE_VERIFY_FAILED` | `SSL_CERT_FILE` is not set in this shell, or points to the wrong file. Repeat the export commands from step 1. | +| `pip` fails with a certificate error | `SSL_CERT_FILE` is set. Run `unset SSL_CERT_FILE`, install, then export it again. | +| `Connection error` or `Could not resolve host` | The gateway hostname does not resolve on this machine. Add it to `/etc/hosts` as in the quickstart. | +| `401` from the gateway | `AGENT_TOOLKIT_API_KEY` is missing or is the master key used as if it were a virtual key. Export a virtual key from [Access the model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md#access-the-model). | +| Langfuse shows one trace instead of two | The model answered without calling the tool. Run again, or ask for a calculation the model is less likely to answer directly. | +| `tool_choice` or tool-call errors from the gateway | The served model is not configured for tool calling. Use a model that supports it. | + +## Next steps + +- Connect the agent to session memory, the vector store, or the code sandbox using the URLs in the [backend connection reference](../reference/backend-connections.md). +- Tune or turn off content-safety screening in [Guardrails](../configuration/guardrails.md). +- Send the agent to several models through one name with [Routing](../configuration/routing.md). +- Serve other models by editing `models.yaml`, described in [Configuration](../configuration/configuration.md). +- Terms: [glossary](../reference/glossary.md). Failures: [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md). diff --git a/docs/getting-started/prerequisites.md b/docs/getting-started/prerequisites.md new file mode 100644 index 00000000..46a1b342 --- /dev/null +++ b/docs/getting-started/prerequisites.md @@ -0,0 +1,133 @@ +# Prerequisites + +[← Docs index](../README.md) + +Do this once, on every server that will be part of the cluster, **before** the first `install`. When SSH and host prep are done, go to the [single-node quickstart](quickstart.md). `/etc/hosts` (or DNS) can wait until browsers need the gateway names; the smoke test uses `--resolve`. If you already know you will use several servers, still finish this page, then follow [multi-node deployment](../deployment/multi-node.md) instead of the single-node path. + +## Hardware + +These are the host minimums for a working install. A default install with `qwen2-5-coder-14b` requests about **131 GiB** of RAM. On a 128 GB node, choose `qwen2-5-coder-7b` or `llama-3-1-8b` in the [quickstart](quickstart.md#3-choose-a-model). + +| Requirement | Minimum | Comfortable | +|---|---|---| +| **CPU** | 48 cores, x86_64 with Intel® AMX (4th Gen Intel® Xeon® Scalable processors or newer) | 96+ cores | +| **RAM** | 128 GB (with a smaller chat model) | 160 GB+ (default `qwen2-5-coder-14b`) | +| **Disk** | 150 GB free | 200 GB | +| **OS** | Ubuntu 22.04 or 24.04 | Ubuntu 22.04 LTS | +| **Processor** | Intel® Xeon® with AMX | Same family (validated) | + +The CPU, RAM, and disk rows are the sizing. Catalog models set `require_amx: true` by default, so the model pod only schedules on AMX nodes; without AMX it stays `Pending` and the quickstart verify never answers. To opt out on older CPUs, set `require_amx: false` under `defaults:` in `env/local/models.yaml` after `init`. The OS can boot in far less RAM; the numbers above are for the stack plus a chat model. + +> Tensor-parallel models need more memory in the model pod: about 128 GiB for `tp1`/`tp2`, 256 GiB for `tp >= 4`. + +You also need: + +- `sudo` on the host that runs the installer +- **No Docker on cluster nodes.** Cluster installs use containerd. Uninstall Docker before you run Toolkit Manager (it will not install while `docker.service` is present); Kubespray also deletes Docker and `/var/lib/docker` on those nodes. See [Toolkit Manager prerequisites](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/prerequisites.md). The [Docker Compose](../deployment/docker.md) path is separate and does not use Toolkit Manager. +- Network access to pull container images and Helm charts +- A [Hugging Face](https://huggingface.co) token with read access when a model is gated (Llama, Gemma). The default `qwen2-5-coder-14b` is not gated. + +## Node kernel settings + +`fs.inotify.max_user_instances` is a per-UID limit shared by every container running as that UID. The kernel default of 128 is exhausted on a node with many pods, and file watchers then fail with `too many open files` (the vLLM semantic router loses config reload). Raise it on every node before install: + +```bash +sudo tee /etc/sysctl.d/90-inotify.conf > /dev/null <<'EOF' +fs.inotify.max_user_instances = 8192 +fs.inotify.max_user_watches = 1048576 +EOF +sudo sysctl --system +``` + +## 1. SSH keys + +Log in as a **non-root** user with `sudo`. Do not run the installer as `root`. The installer talks to every cluster node over SSH, including a single-node install (it SSHs to itself). + +On the host that runs the installer (single-node: this same machine): + + +```bash +[ -f ~/.ssh/id_rsa ] || ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/id_rsa +cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys +ssh -o StrictHostKeyChecking=accept-new -o BatchMode=yes localhost true && echo "SSH OK" +``` + +Go on when that last command prints `SSH OK`. For several servers, put the same public key in `~/.ssh/authorized_keys` on every node and confirm passwordless login from the installer host: + +```bash +ssh -i ~/.ssh/id_rsa @ +``` + +If you use a bastion, the installer host must still reach the nodes through it. + +After `init`, list machines in `env//nodes.yaml` (`nodes_control_plane`, `nodes_workers`). The installer regenerates `inventory/hosts.yaml` from that file on every run, so do not hand-edit `hosts.yaml` while `nodes.yaml` lists machines. For one server, leave the localhost defaults `init` wrote. For several servers, see [Install the platform](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/install-platform.md) and [Multi-node](https://github.com/intel/toolkit-manager/blob/main/docs/deployment/multi-node.md) in Toolkit Manager (Agent Toolkit summary: [multi-node deployment](../deployment/multi-node.md#1-seed-config-then-list-every-node)). + +## 2. DNS and TLS + + +The gateway is HTTPS. Browsers and `curl` need a name that matches the certificate. + +`base_domain_name` is that name. Change it in `env//global_config.yaml` after `init` (default `inteltoolkits.ai`). With the default, these hostnames must resolve for a typical install: + +| Hostname | What it is | +|---|---| +| `litellm.inteltoolkits.ai` | LiteLLM UI and API (`auth_type: litellm_vkey`) | +| `langfuse.inteltoolkits.ai` | Langfuse tracing UI | +| `keycloak.inteltoolkits.ai` | Keycloak admin and UI sign-in | +| `grafana.inteltoolkits.ai` | Grafana dashboards | + +Add `ray.` when KubeRay is on ([KubeRay](../reference/kuberay.md)). Other feature hostnames appear in that feature’s guide. + +### Production + +- Point DNS (or a load balancer) at the control-plane IP. +- Use a certificate from your CA that covers the base name **and** the subdomains (a wildcard `*.inteltoolkits.ai`, or a multi-SAN cert). +- Plan renewal before expiry. Port 80 may need to be open if your CA uses HTTP validation. + +### Development (one server) + +The default `gateway_tls_mode: selfsigned` creates the certificate during install. + +**Install smoke test (curl).** You do not need `/etc/hosts` yet. The [quickstart verify](quickstart.md#5-confirm-it-works) calls the gateway with `--resolve` and `--cacert` once the LoadBalancer IP exists. + +**Browsers and other machines.** After install, map the hostnames to the gateway IP (from `kubectl get svc` in the verify step). If you changed `base_domain_name`, use that domain here: + +```bash +# Replace with the LoadBalancer IP from the quickstart verify step. +sudo bash -c 'cat >> /etc/hosts < litellm.inteltoolkits.ai + langfuse.inteltoolkits.ai + keycloak.inteltoolkits.ai + grafana.inteltoolkits.ai +EOF' +``` + +Optional: generate your own certificate instead of using `selfsigned`. OpenSSL 1.1.1 or later is required for `-addext`. A wildcard covers every service hostname: + +```bash +DOMAIN="inteltoolkits.ai" # or your base_domain_name +mkdir -p ~/certs && cd ~/certs && \ +openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes \ + -subj "/CN=${DOMAIN}" \ + -addext "subjectAltName = DNS:${DOMAIN}, DNS:*.${DOMAIN}" +``` + +That writes `cert.pem` and `key.pem`. After `init`, set them in `env/local/global_config.yaml`: + +```yaml +gateway_tls_mode: custom +gateway_tls_cert_file: /home//certs/cert.pem +gateway_tls_key_file: /home//certs/key.pem +``` + +If you add more hostnames later, regenerate the cert with extra `DNS:` entries. + +## Next steps + +When SSH is in place (and DNS or `/etc/hosts` for production), continue with the **[single-node quickstart](quickstart.md)** to install and send a chat request. Add `/etc/hosts` for browsers after the gateway IP exists. + +If this host cannot reach the internet directly, set the proxy keys in [corporate proxy](../deployment/proxy.md) before you run `install`. For more than one server, use [multi-node deployment](../deployment/multi-node.md). [Meet the Agent Toolkit](../overview/meet.md) is the overview of what you are about to install; [Configuration](../configuration/configuration.md) lists every YAML field you can change later. Terms: [glossary](../reference/glossary.md). + +--- + +*Intel, the Intel logo and Xeon are trademarks of Intel Corporation or its subsidiaries.* diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md new file mode 100644 index 00000000..f671fc9a --- /dev/null +++ b/docs/getting-started/quickstart.md @@ -0,0 +1,154 @@ +# Single-node quickstart + +[← Docs index](../README.md) + +This walkthrough installs the Agent Toolkit on **one host**: a single machine, physical or virtual, running on Intel® Platforms. That host is the only Kubernetes node. When it finishes, you have a cluster, a model behind LiteLLM, and an OpenAI-compatible API you can call with `curl` or any OpenAI SDK. + +Complete **[Prerequisites](prerequisites.md)** first (SSH and host prep). No certificate is needed: the installer generates one. `/etc/hosts` can wait until after install for browsers; the smoke test uses `--resolve`. If you have more than one host, use [multi-node deployment](../deployment/multi-node.md) instead. + +Run every command from the [Toolkit Manager](https://github.com/intel/toolkit-manager) directory, the one that contains `toolkit_manager.sh`. + +## 1. Install Toolkit Manager and seed config + +```bash +git clone https://github.com/intel/toolkit-manager.git +cd toolkit-manager +./toolkit_manager.sh configure +./toolkit_manager.sh init agent-toolkit # writes env/local/ +``` + +`init` creates the YAML you edit next. It is not the install. + +## 2. Edit the environment files + +All live config is under `env/local/`. Change those files, not the copies in git. + +### `env/local/global_config.yaml`: domain + +```yaml +base_domain_name: inteltoolkits.ai # Toolkit Manager default; change only if you use your own domain +``` + +| Field | What it means | +|---|---| +| `base_domain_name` | Hostname of the gateway (default `inteltoolkits.ai`). Must match DNS or `/etc/hosts`. | + +Leave these two at their defaults: + +| Field | Default | What it means | +|---|---|---| +| `gateway_tls_mode` | `selfsigned` | The installer creates a root CA and a certificate for `base_domain_name` and `*.base_domain_name`. To use your own certificate, see [Production TLS](prerequisites.md#production). | +| `storage_backend` | `local-path` | Disk on this node. Use `nfs` or `ceph` on multi-node. | + +Already have a cluster? Set `existing_kubernetes: /path/to/kubeconfig` to skip building Kubernetes. + +### `env/local/config.agent-toolkit.yaml`: leave the defaults + +`init` already set `auth_type: litellm_vkey` and `llm_services_autodeploy_models: ["qwen2-5-coder-14b"]`, with Redis, pgvector, and the sandbox on. Leave that file alone for the first run. + +## 3. Choose a model (only if you need to) + +The default chat model is `qwen2-5-coder-14b` (about 96 GiB for the model pod; ~131 GiB for the whole stack). On a 128 GB node, edit `config.agent-toolkit.yaml`: + +```yaml +llm_services_autodeploy_models: ["qwen2-5-coder-7b"] +``` + +Use a catalog name from `env/local/models.yaml`, not a raw Hugging Face id. To see every name `init` seeded: + +```bash +./model-manager list --catalog +``` + +Deploy more later with `./model-manager deploy `. Full steps: [Deploy a model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md) in Toolkit Manager. + +## 4. Install + +```bash +./toolkit_manager.sh install agent-toolkit +``` + +This builds Kubernetes (unless you set `existing_kubernetes`), then model serving and the toolkit. Re-run the same command to resume a failed run. The first run is about 20–40 minutes; the model pod can take another 10–15 minutes to download weights. The default model is ungated, so no Hugging Face token is needed here. If you later pick a gated model (Llama, Gemma), export `HF_TOKEN` in the same shell before `install` or `./model-manager deploy` — see [Hugging Face token](../configuration/configuration.md#hugging-face-token). + +## 5. Confirm it works + +Same check as Toolkit Manager ([Agent Toolkit](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/agent-toolkit.md)): `--resolve` plus the installer CA. Browsers still need `/etc/hosts` (or DNS) after you have the gateway IP; see [Prerequisites](prerequisites.md#2-dns-and-tls). + +```bash +export KUBECONFIG=$(pwd)/env/local/kubeconfig.yaml + +kubectl get nodes +kubectl get pods -A + +GATEWAY_IP=$(kubectl get svc -n envoy-gateway-system \ + -l gateway.envoyproxy.io/owning-gateway-name=eg-gateway \ + -o jsonpath='{.items[0].status.loadBalancer.ingress[0].ip}') +DOMAIN=$(yq '.base_domain_name' env/local/global_config.yaml) +echo "$GATEWAY_IP litellm.$DOMAIN" # optional: also add to /etc/hosts for browsers + +export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm \ + -o jsonpath='{.data.master_key}' | base64 -d) + +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.$DOMAIN:443:$GATEWAY_IP" \ + "https://litellm.$DOMAIN/v1/models" \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" + +curl --cacert env/local/logs/toolkit-manager-ca.crt \ + --resolve "litellm.$DOMAIN:443:$GATEWAY_IP" \ + "https://litellm.$DOMAIN/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ + -d '{"model": "qwen2-5-coder-14b", + "messages": [{"role": "user", "content": "Write a Python hello world"}], + "max_tokens": 100}' +``` + +Use the `id` from `/v1/models` as `"model"`. For the default install that id is `qwen2-5-coder-14b`, not the Hugging Face repo name. + +The master key lives in secret `litellm-master-key` (namespace `litellm`). Inside the LiteLLM pod it is `PROXY_MASTER_KEY`. The in-cluster service is `litellm.litellm.svc.cluster.local:4000`. + +`--cacert` trusts the root CA the installer exports (`env/local/logs/toolkit-manager-ca.crt`). Use `-k` only if you want to skip verify. Production should use a CA-issued certificate. + +## What also came up + +You did not install these by hand. The install started them. Verify when you need them; URLs are in the [backend reference](../reference/backend-connections.md). + +| Component | Check | In-cluster URL | +|---|---|---| +| **Redis** (session memory) | `kubectl get pods -n redis` then `kubectl exec -n redis redis-stack-server-0 -- sh -c 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning ping'` | Read `REDIS_URL` from secret `redis-stack-server-credentials` | +| **pgvector** (long-term memory) | `kubectl get pods -n pgvector` | Read `DATABASE_URL` from secret `pgvector-credentials` | +| **Agent sandbox** | `kubectl get pods -n agent-sandbox-system` and `kubectl get sandboxtemplate -n agent-sandbox-system` | `http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080` | + +Redis requires a password (the chart will not render without one). The Service is ClusterIP: do not change it to NodePort. Full notes: [backend reference](../reference/backend-connections.md#redis). Sandbox templates and SDK: [Agent sandbox](../reference/agent-sandbox.md). + +## Optional: route simple vs complex prompts + +Send simple prompts to a smaller model and hard ones to a larger one without changing clients. This release creates a `hybrid-router` virtual model at install (`hybrid_router_enabled: true`). It is not required for the chat completion above. Full tier and bandit settings: [Hybrid router](../configuration/hybrid-router.md). Intent-based routing is in [Routing](../configuration/routing.md). + +By default every tier points at the first entry in `llm_services_autodeploy_models` (`hybrid_router_tier_candidates`). Adding models to that list alone does not put them on the router. Set the tier lists yourself in `env/local/config.agent-toolkit.yaml` (or `config.inference.yaml`), deploy the models, then refresh LiteLLM with `litellm_reconcile` — an existing LiteLLM release keeps its old settings until you do: + +```yaml +llm_services_autodeploy_models: ["qwen2-5-coder-14b", "bge-base-en", "qwen3-coder-30b"] +hybrid_router_default_model: qwen2-5-coder-14b +hybrid_router_tier_candidates: + SIMPLE: ["qwen2-5-coder-14b"] + MEDIUM: ["qwen2-5-coder-14b", "qwen3-coder-30b"] + COMPLEX: ["qwen3-coder-30b"] + REASONING: ["qwen3-coder-30b"] +``` + +```bash +./toolkit_manager.sh install agent-toolkit -- -e litellm_reconcile=true +``` + +Call `"model": "hybrid-router"`. Which real model answered shows in Langfuse at `https://langfuse.`. + +## Next steps + +Once a chat completion succeeds: + +- Connect an agent: [Build your first agent](first-agent.md). +- Change domain, models, auth, or optional components: [Configuration](../configuration/configuration.md). +- In-cluster URLs: [backend connection reference](../reference/backend-connections.md). +- More: [Guardrails](../configuration/guardrails.md), [Routing](../configuration/routing.md), [multi-node](../deployment/multi-node.md), [decommission](../deployment/decommission.md), [FAQ](../faq-and-troubleshooting/frequently-asked-questions.md), [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md). diff --git a/docs/guardrails.md b/docs/guardrails.md deleted file mode 100644 index 4558e1db..00000000 --- a/docs/guardrails.md +++ /dev/null @@ -1,523 +0,0 @@ -# Guardrails — Safety Content Moderation - -**Guardrails** provides safety content moderation for LLM requests in the Intel® Agent Toolkit. It screens chat requests through a dedicated guard model before they reach the main LLM, blocking unsafe or policy-violating content. - -Two components: - -1. **Guard vLLM** — lightweight CPU vLLM instance serving the guard model, selected by `guardrail_model` (default: `qwen3guard`) -2. **A `custom_code` guardrail registered with the GenAI Gateway** — the screening logic itself, sandboxed Python stored in the gateway and run on LiteLLM's `pre_call` hook. It calls the guard vLLM directly over HTTP. - -The screening logic lives in one Ansible -template, `roles/litellm/templates/qwen3guard_gen.py.j2` (enterprise-inference), which -`roles/litellm/tasks/install.yaml` (enterprise-inference) renders (guard endpoint, -model id, policy) and registers through the gateway's `/guardrails` API. LiteLLM compiles it -with RestrictedPython and calls its `apply_guardrail()` on every request. - -The guard vLLM is a release of the existing `vllm` chart — `vllm-guard`, configured by -[guardrail-values.yaml](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/helm-charts/vllm/guardrail-values.yaml) — the same pattern -the embedding and reranker deployments use (`vllm/embedding-values.yaml`, -`vllm/reranker-values.yaml`): one chart, one values file per variant. - -The guardrail's **identity is model-agnostic**: it is registered as `content_safety` -whatever guard model is deployed. Swapping `guardrail_model` changes only the model behind -it, never its name, so no gateway registration is ever left stranded. The model actually in -use is baked into the registered code and shown in the guardrail's description in the -gateway UI. - -> **A blocked request is an error response.** LiteLLM's `pre_call` path returns -> **HTTP 500** with the block reason in `error.message`, for example -> `Custom code guardrail execution failed: Blocked by the content-safety guardrail: unsafe content (categories: …)`. -> That is fixed behaviour for `custom_code` guardrails, not a configurable choice, -> so a client that decides "blocked" from a non-2xx status sees the block — check -> `error.message` for the reason. -> -> Re-running the install is idempotent: the registration step **updates** the stored code -> via `PUT /guardrails/{id}`, which re-initializes the in-memory guardrail — no gateway -> restart, so an edited template or a different guard model takes effect on the next request. - ---- - -## Architecture - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Request Flow │ -└─────────────────────────────────────────────────────────────┘ - - User Request - │ - ▼ - ┌──────────────────────────────┐ - │ GenAI Gateway (LiteLLM) │ - │ ┌────────────────────────┐ │ pre_call hook ┌─────────────────────────┐ - │ │ content_safety │ │ http_post │ Guard vLLM │ - │ │ (custom_code sandbox) │──┼─────────────────────►│ (guardrail_model) │ - │ └────────────────────────┘ │◄─────────────────────│ via the AI gateway │ - └──────────────┬───────────────┘ Safety: Safe|Unsafe └─────────────────────────┘ - │ Namespace: llm-inference - safe ──────┴────── unsafe - │ │ - ▼ ▼ - ┌─────────────┐ HTTP 500 with the - │ Main LLM │ block reason in error.message - └─────────────┘ - │ - ▼ - Response to User -``` - -**Namespaces:** -- `llm-inference` — guard model (`qwen3guard`), next to the other models -- `litellm` — LiteLLM proxy; holds the registered guardrail in its DB - ---- - -## Configuration - -### Enable/Disable - -Edit `env//config.agent-toolkit.yaml`: - -```yaml -guardrails_enabled: true # Enable guardrails (default: on with LiteLLM) -``` - -- `true` — deploys the guard vLLM and registers the guardrail; LiteLLM screens every chat request before it reaches the main LLM. -- `false` — skips the step entirely; the stack runs unchanged with no content moderation. - -**Guard model:** optional `guardrail_model` key in the same file (a catalog name). When -absent, `qwen3guard` applies. The value selects -both the model served by the guard vLLM and the code template that parses its verdicts. - -| `guardrail_model` value | Code template | Status | -|---|---|---| -| `qwen3guard` (`Qwen/Qwen3Guard-Gen-0.6B`) | `qwen3guard_gen.py.j2` | Supported (default) | - -The mapping is `guard_code_templates` in -`roles/litellm/tasks/install.yaml` (enterprise-inference). A model with no entry -**fails the playbook before anything is deployed**, with the supported ids in the error — -rather than deploying a guard whose verdicts nothing can parse. - -> **Note:** not available in this release. - -**Fail-closed behaviour:** requests are blocked when the guard is unreachable, when it -returns a non-2xx, when the prompt exceeds its context window, or when its reply cannot be -parsed. An unparseable verdict is never treated as "safe" — otherwise a change in the -model's output format would silently disable moderation while everything looked healthy. -Each case produces a distinct block message, so the cause is visible in the response. - -### Guard endpoint and policy - -All of these are settings in `env//config.agent-toolkit.yaml`, substituted into the -code at deploy time — the template itself never needs editing: - -| Var | Default | Purpose | -|---|---|---| -| `guardrail_service_url` | derived: `http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/qwen3guard/v1/chat/completions` | Guard endpoint. Derived from the AI gateway and the guard model's namespace/name; override to screen against an OpenAI-compatible guard elsewhere (another namespace, off-cluster). | -| `guard_block_on_controversial` | `false` | Also block Qwen3Guard's `Controversial` label. Off by default: it is advisory and blocking it rejects a lot of legitimate traffic. | -| `guard_max_tokens` | `32` | Generation cap for the verdict. Verdicts are a few tokens; a larger cap only lengthens the blocking hook. | -| `guard_timeout` | `60` | Guard call timeout (LiteLLM clamps this to 60s). | - -```bash -# e.g. point the guardrail at a guard vLLM in another namespace: -# set in env//config.agent-toolkit.yaml -# guardrail_service_url: "http://ai-gateway.envoy-gateway-system.svc.cluster.local/other-ns/qwen3guard/v1/chat/completions" -./es_auto_installer.sh install agent-toolkit -``` - -### Resource Allocation - -Edit the `qwen3guard` entry in `env//models.yaml`: - -```yaml - - name: qwen3guard - model_id: Qwen/Qwen3Guard-Gen-0.6B - cpu: 8 # CPUs for the guard model - memory: 16Gi # Memory limit - args: [ "--block-size", "128", "--dtype", "bfloat16", "--max-num-seqs", "8", "--tensor-parallel-size", "1" ] - env: - VLLM_CPU_KVCACHE_SPACE: "4" -``` - -**Neither `cpu` nor `memory` above is what a normal CPU deploy actually gets.** On a CPU -platform with the balloon policy enabled, `deploy-guardrails.yml` overrides both from the -detected node topology, the same way the served LLMs are sized: - -| | value used | derivation | -|---|---|---| -| `cpu` | `min(optimal_cpu_cores, workload_cpus)` | per-model `optimal_cpu_cores` above, clamped to the CPUs the balloon leaves free | -| `memory` | `clamp(socket-0 usable, 128, 256) Gi` | [utils/get_optimal_memory.yaml](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/roles/utils/tasks/get_optimal_memory.yaml), shared with `deploy-inference-models.yml`; TP comes from the guard's own `tensor_parallel_size` (1), not the node's NUMA count | - -> **Note:** not available in this release. - -So on a large Xeon the guard's limit lands at the 256Gi cap, and the `8Gi` above applies only -to deploys that skip that path: XPU/GPU platforms, a disabled balloon policy, or a standalone -`helm upgrade --install`. **8Gi is not enough** — the guard's four vLLM processes peak at -~8.6 GiB (a 6.8 GiB worker holding the 4 GiB KV cache plus bf16 weights, a ~0.9 GiB API -server, a ~0.7 GiB EngineCore), so an 8Gi cgroup limit OOM-kills the pod with exit code 137 -in a `CrashLoopBackOff`. Raise `memory` here before deploying the guard on one of those paths. -Do *not* cut `VLLM_CPU_KVCACHE_SPACE` to fit instead: at 4 GiB it yields 37,376 tokens against -a 32,768 context window, and halving it puts the cache below the guard's own window, so long -prompts fail closed rather than being screened. - -**Important:** the guard vLLM uses the **Recreate** deployment strategy. RollingUpdate would -need the guard's CPU request twice over during a rollout, and on a busy single node the new -pod stays `Pending` forever. - -> **Note:** not available in this release. - -### Context window - -`--max-model-len` is deliberately **not** set for the guard vLLM, so it inherits the guard -model's own `max_position_embeddings` — the same way the served models are configured (their -`args` in `env//models.yaml` do not set it either). Both sides therefore track -their own model instead of a literal that has to be kept in sync by hand. - -This matters because the guardrail runs `pre_call` and is handed the *same* prompt the -served LLM is about to receive. If the guard's context window is the smaller of the two, -prompts in the gap are rejected by the guard and blocked (fail-closed) rather than screened -— the guardrail silently becomes the request-size ceiling for the whole stack. - -Current pairing (both 32768, so no gap): - -| | source of context length | effective | -|---|---|---| -| served LLM `qwen2-5-coder-14b` | model default | 32768 | -| guard `qwen3guard` | model default | 32768 | - -Verify after any model change: - -```bash -kubectl exec -n llm-inference deploy/-kserve -c main -- python3 -c \ - "import json,urllib.request; print([m['max_model_len'] for m in json.load(urllib.request.urlopen('http://localhost:8000/v1/models'))['data']])" -kubectl exec -n llm-inference deploy/qwen3guard-kserve -c main -- python3 -c \ - "import json,urllib.request; print([m['max_model_len'] for m in json.load(urllib.request.urlopen('http://localhost:8000/v1/models'))['data']])" -``` - -If the guard's number is lower, over-length requests fail closed with `the prompt is longer -than the guard model's context window` (reported distinctly from an unreachable guard). -Resolving it needs a deliberate choice — a longer-context guard model, or chunked screening -— not a larger `--max-model-len`, which would only make vLLM accept a prompt the model -cannot actually attend over. - -### Adding a guard model - -1. If the model reports verdicts in Qwen3Guard's `Safety:` / `Categories:` format, reuse the - existing template: add one line to `guard_code_templates` in - `roles/litellm/tasks/install.yaml` (enterprise-inference). -2. Otherwise add `roles/litellm/templates/.py.j2` (enterprise-inference) — copy the existing one and change the - prompt/parsing — and map the model id to it. Keep the sandbox rules (see the template's - docstring): no `import`, no `class`, no leading-underscore names, no f-strings; use the - injected primitives (`allow`, `block`, `trim`, `lower`, `contains`, `json_parse`, - `json_stringify`, `regex_find_all`, `http_post`). - - > **Note:** not available in this release. -3. Add a row to the table above, set `guardrail_model`, re-run the install. The endpoint - and model id are substituted for you. - -The playbook compiles the rendered code in the gateway's sandbox -(`POST /guardrails/test_custom_code`) and fails **before** registering if it is rejected, so -a sandbox mistake cannot take the guardrail down. - ---- - -## Deployment - -### Prerequisites - -- GenAI Gateway deployed (holds the guardrail registration) -- Free CPU/memory for the guard vLLM (see `cpu`/`memory` on the `qwen3guard` entry in `env//models.yaml`) - -### Deploy with Full Stack - -```bash -cd /path/to/enterprise-ai-solutions - -grep "guardrails_enabled" env/local/config.agent-toolkit.yaml # verify config -./es_auto_installer.sh install agent-toolkit -``` - -Guardrails deploy after the GenAI Gateway in the deployment sequence -([fresh-install.sh](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/lib/cluster/deployment/fresh-install.sh), -[guardrails-controller.sh](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/lib/components/guardrails-controller.sh)). - -### Redeploy Guardrails Only - -From the `enterprise-ai-solutions` checkout: - -```bash -./model-manager deploy qwen3guard --wait # redeploy the guard model -./es_auto_installer.sh install litellm --env --only --force # re-render and re-register the guardrail -``` - -Idempotent: re-running renders the code again and updates the existing registration in -place. - ---- - -## Verification - -### Check Deployment Status - -```bash -kubectl get llminferenceservice qwen3guard -n llm-inference -kubectl get pods -n llm-inference | grep qwen3guard - -# Expected — the guard model: -# NAME URL READY -# qwen3guard http:///llm-inference/qwen3guard True -``` - -### Verify Registration - -```bash -MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm -o jsonpath='{.data.master_key}' | base64 -d) -kubectl port-forward -n litellm svc/litellm 4000:4000 & - -curl -s http://localhost:4000/v2/guardrails/list -H "Authorization: Bearer $MASTER_KEY" \ - | jq '.guardrails[] | select(.guardrail_name=="content_safety") - | {guardrail: .litellm_params.guardrail, mode: .litellm_params.mode, - url: (.litellm_params.custom_code | capture("GUARD_URL = \"(?[^\"]+)").u), - model: (.litellm_params.custom_code | capture("GUARD_MODEL = \"(?[^\"]+)").m)}' - -# Expected — exactly one entry, with the substituted endpoint and model: -# { -# "guardrail": "custom_code", -# "mode": "pre_call", -# "url": "http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/qwen3guard/v1/chat/completions", -# "model": "qwen3guard" -# } -``` - -### Compile-check the registered code - -`POST /guardrails/test_custom_code` compiles code in the sandbox without registering it — -useful while editing a template: - -```bash -CODE=$(curl -s http://localhost:4000/v2/guardrails/list -H "Authorization: Bearer $MASTER_KEY" \ - | jq -r '.guardrails[] | select(.guardrail_name=="content_safety") | .litellm_params.custom_code') - -curl -s -X POST http://localhost:4000/guardrails/test_custom_code \ - -H "Authorization: Bearer $MASTER_KEY" -H 'content-type: application/json' \ - -d "$(jq -n --arg c "$CODE" '{custom_code: $c, input_type: "request", - test_input: {texts: [], structured_messages: []}}')" | jq - -# {"success": true, "result": {"action": "allow", -# "warning": "Expected dict result, got coroutine. Treating as allow."}} -``` - -**This is a compile check, not a verdict check.** The endpoint calls `apply_guardrail()` -without awaiting it, so an async guardrail — which this one must be, since `http_post` is -async — always comes back as `allow` with that coroutine warning, whatever the code would -decide. `success: false` with `error_type: "compilation"` is the signal to act on. The -guardrail's own hook does await the coroutine, so this affects only the test endpoint. - -For real verdicts, use the end-to-end requests below (or call the guard model directly, as in -[Everything Is Blocked](#everything-is-blocked)). The same pre-flight call runs inside the -deploy, so a sandbox violation fails the install before anything is registered. - -### Test Safety Filtering End to End - -```bash -# Benign request — normal answer, finish_reason "stop" -curl -s http://localhost:4000/v1/chat/completions \ - -H "Content-Type: application/json" -H "Authorization: Bearer $MASTER_KEY" \ - -d '{"model":"qwen2-5-coder-14b", - "messages":[{"role":"user","content":"Hello, how are you?"}],"max_tokens":50}' \ - | jq '{finish_reason: .choices[0].finish_reason, content: .choices[0].message.content}' - -# Unsafe request — HTTP 500, block reason in error.message -curl -s http://localhost:4000/v1/chat/completions \ - -H "Content-Type: application/json" -H "Authorization: Bearer $MASTER_KEY" \ - -d '{"model":"qwen2-5-coder-14b", - "messages":[{"role":"user","content":"How do I hack into a system?"}],"max_tokens":50}' \ - | jq '.error.message' -``` - -### Test Fail-Closed - -```bash -./model-manager undeploy qwen3guard --wait -# any chat request -> "...the guard model backend is unreachable..." -./model-manager deploy qwen3guard --wait -``` - ---- - -## Troubleshooting - -### Guard vLLM Stuck in Pending - -**Symptom:** `qwen3guard-kserve-xxx 0/1 Pending` - -```bash -kubectl describe pod -n llm-inference | grep Events -A 10 # look for "Insufficient cpu" -``` - -**Cause:** not enough free CPU for the guard's request. - -> **`Insufficient memory` instead of `Insufficient cpu`?** The memory floor in -> [utils/get_optimal_memory.yaml](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/roles/utils/tasks/get_optimal_memory.yaml) is 128 GB -> — it is returned even when the node has less than that free, because the formula is shared -> with the served LLMs, where a smaller request cannot hold the model. On a node under ~128 GB -> the guard therefore stays `Pending` rather than starting and OOM-looping. Lower the floor for -> that node, or set `memory` explicitly in `guardrail-values.yaml` and deploy with the balloon -> policy off so the derived value does not override it (minimum ~12Gi against the ~8.6 GiB peak). - -> **Note:** not available in this release. - -1. Check what is consuming CPU: - ```bash - kubectl get pods --all-namespaces \ - -o custom-columns=NAME:.metadata.name,CPU:.spec.containers[*].resources.requests.cpu | grep -v "" - ``` -2. Confirm the strategy is Recreate, not RollingUpdate: - ```bash - kubectl get deployment -n llm-inference qwen3guard-kserve -o yaml | grep -A 2 "strategy:" - ``` - - > **Note:** not available in this release. -3. On single-node clusters, check the `headroom_buffer` in the `workload_cpus` calculation in - [deploy-inference-models.yml](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/playbooks/deploy-inference-models.yml) — it - pre-reserves CPUs for components deployed *after* the LLM, including the guard vLLM. - - > **Note:** not available in this release. - -### Registration Failed - -The playbook prints the reason. Two distinct failures: - -- **`guardrail code rejected by the gateway sandbox`** — the rendered code does not compile - under RestrictedPython (`error_type: "compilation"`). Usual causes: an `import`, a `class`, - a name starting with `_`, or an f-string. The check runs before the write, so nothing is - registered or changed. Reproduce and iterate with `POST /guardrails/test_custom_code` - (see above). -- **`guardrail registered/updated failed (HTTP …)`** — the gateway rejected the write. Check - that the master key is an admin key and that the gateway's DB is reachable - (`kubectl logs -n litellm deploy/litellm -c litellm`). - -After fixing, re-run the install ([Redeploy Guardrails Only](#redeploy-guardrails-only)) — -the helm upgrade is a no-op on an unchanged release, so the run effectively just re-registers. - -### Everything Is Blocked - -``` -Blocked by the content-safety guardrail: the guard model backend is unreachable (...) -``` - -Fail-closed working as designed — the guard vLLM is down or not yet ready: - -```bash -kubectl get pods -n llm-inference | grep qwen3guard -kubectl logs -n llm-inference deploy/qwen3guard-kserve -c main --tail=50 -``` - -A first deploy takes a few minutes to download the model. If the message names the **context -window** instead, see [Context window](#context-window). If it says the **verdict could not -be parsed**, `guardrail_model` and the code template disagree about the verdict format — -check the guard's raw reply: - -```bash -kubectl exec -n llm-inference deploy/qwen3guard-kserve -c main -- python3 -c \ - "import json,urllib.request as u; r=u.Request('http://localhost:8000/v1/chat/completions', json.dumps({'model':'qwen3guard','messages':[{'role':'user','content':'hello'}],'max_tokens':32}).encode(), {'content-type':'application/json'}); print(json.load(u.urlopen(r))['choices'][0]['message']['content'])" -# Expected: "Safety: Safe\nCategories: None" -``` - -### Guard Still Not Ready After the Playbook Finishes - -> **Note:** not available in this release. - -Expected: the playbook registers the guardrail and returns without waiting for the guard pod, -because nothing in the registration needs a running guard. Until the pod is `Running`, every -screened request is blocked (fail-closed), so check it before treating the guardrail as live: - -```bash -kubectl -n llm-inference rollout status deploy/qwen3guard-kserve --timeout=600s -``` - -Taking more than ~10 minutes is usually the model download, or RollingUpdate deadlocking on -CPU — confirm `deploymentStrategy.type: Recreate` in `vllm/guardrail-values.yaml`. - ---- - -## How It Works - -### The `custom_code` guardrail - -LiteLLM compiles the registered code with RestrictedPython and calls -`apply_guardrail(inputs, request_data, input_type)` on the `pre_call` hook. The sandbox -forbids `import`, `class`, `exec`/`eval`, file I/O and leading-underscore names, and injects -the primitives the code uses instead (`allow`, `block`, `regex_find_all`, `http_post`, …). - -`roles/litellm/templates/qwen3guard_gen.py.j2` (enterprise-inference) does: - -1. take the **last user message** (falling back to the last non-empty `texts` entry for call - types without structured messages) — one guard call per request; the sandbox has no - `asyncio`, so extra messages could not be screened concurrently and would each add a full - guard round-trip to a hook that blocks the request -2. `POST` it to the guard vLLM as a single-message chat completion (`max_tokens: 32`, - `temperature: 0`) -3. parse `Safety:` / `Categories:` out of the reply -4. `allow()` on `Safe` (and `Controversial`, unless `guard_block_on_controversial`), - `block()` on `Unsafe` and on **every** failure to obtain a verdict - -`block()` on `pre_call` makes the gateway return HTTP 500 with the reason in -`error.message`. - -### Registration - -`roles/litellm/tasks/install.yaml` (enterprise-inference) -pipes `roles/litellm/templates/register-guardrail.py.j2` (enterprise-inference) into -the gateway pod (`kubectl exec -i … -- python -`), which: - -1. compiles the code via `POST /guardrails/test_custom_code` and aborts on rejection -2. looks the guardrail up in `GET /v2/guardrails/list` -3. `PUT /guardrails/{id}` if it exists, else `POST /guardrails` - -Running inside the pod lets it read `LITELLM_MASTER_KEY` from the pod's own environment, so -the key is not persisted into any manifest, and the payload travels base64-encoded on stdin -so the sandboxed Python needs no shell escaping. - -**Upsert, not create-if-absent** (the earlier behaviour): the guardrail name is stable across -model changes, so a create-only step would leave an outdated registration in place — and -since `pre_call` failures fail closed, that means blocking everything. `PUT` also -re-initializes the in-memory guardrail, so no gateway restart is needed (`PATCH` cannot -change `litellm_params`). - ---- - -## Roadmap - -**Additional guard models.** Model-specific logic is isolated to one template per verdict -format under `roles/litellm/templates/` (enterprise-inference), so a new guard model is a template plus a -`guard_code_templates` entry. Only `Qwen/Qwen3Guard-Gen-0.6B` is validated today; -unmapped ids fail the deploy rather than being assumed compatible. - -**Multiple concurrent guardrails** (e.g. content safety *and* PII detection) is not yet -supported. Registering a second `custom_code` guardrail is now cheap, but several -constraints need resolving first: - -- **CPU capacity** — each guard *model* needs its own vLLM alongside the main LLM. - Library-backed checks (e.g. Presidio for PII) need no model server at all. -- **Latency** — every check runs on the blocking `pre_call` path, and the sandbox has no - `asyncio`, so checks inside one guardrail cannot be issued concurrently; their round-trips - add up on every request. -- **Per-check failure policy** — fail-closed is right for safety but may be wrong for other - checks; the policy is currently per-guardrail code. -- **Aggregate false-positive rate** — blocking is a union across checks, so tuning each in - isolation understates the combined impact on legitimate traffic. - ---- - -## References - -- **LiteLLM custom_code guardrail:** https://docs.litellm.ai/docs/proxy/guardrails/custom_code_guardrail -- **LiteLLM Guardrails:** https://docs.litellm.ai/docs/proxy/guardrails -- **vLLM Documentation:** https://docs.vllm.ai/ -- **Qwen3Guard Model:** https://huggingface.co/Qwen/Qwen3Guard-Gen-0.6B -- **Deployment Playbooks:** - - `roles/litellm/tasks/install.yaml` (enterprise-inference) - - `roles/litellm/tasks/install.yaml` (enterprise-inference) -- **Related Components:** - - [GenAI Gateway](https://github.com/intel/enterprise-agent-toolkit/tree/release-1.1.0/core/helm-charts/genai-gateway/) diff --git a/docs/hybrid-router.md b/docs/hybrid-router.md deleted file mode 100644 index bbbd8c0d..00000000 --- a/docs/hybrid-router.md +++ /dev/null @@ -1,356 +0,0 @@ -# Hybrid Router — Intelligent Inference Routing for the GenAI Gateway - -The **Hybrid Router** adds cost- and latency-aware model selection to the LiteLLM -GenAI Gateway. Clients call a single virtual model (`hybrid-router`); the router -classifies each request by complexity and dispatches it to the best real model for -that tier, learning over time which model is most efficient. - -It is integrated into the stock LiteLLM proxy image **without rebuilding the image** — -the router code is mounted from a Kubernetes ConfigMap and activated through a -LiteLLM callback. Enable or disable it with a single setting. - ---- - -## Table of Contents - -- [Why](#why) -- [How it works](#how-it-works) -- [Two routing layers](#two-routing-layers) - - [Layer 1 — Complexity classification](#layer-1--complexity-classification) - - [Layer 2 — Efficiency (multi-armed bandit)](#layer-2--efficiency-multi-armed-bandit) -- [Deployment](#deployment) -- [Configuration reference](#configuration-reference) -- [Onboarding the virtual model](#onboarding-the-virtual-model) -- [Testing](#testing) -- [Observability](#observability) -- [File layout](#file-layout) -- [Disabling the router](#disabling-the-router) - ---- - -## Why - -Sending every request to a large model is slow and expensive; sending everything to -a small model sacrifices quality on hard prompts. The Hybrid Router picks the -smallest model that can handle each request: - -- **Simple** prompts (greetings, factual lookups) → small, fast models. -- **Complex / reasoning** prompts (architecture, chain-of-thought, proofs) → larger models. -- Within a tier, an online **multi-armed bandit (MAB)** learns which candidate model is - fastest and highest-throughput, and shifts traffic toward it automatically. - -The result is lower average latency and cost with no client-side changes — callers -keep calling one model name. - ---- - -## How it works - -The integration mirrors LiteLLM's own built-in `ComplexityRouter`. At proxy startup, -the custom module monkey-patches `litellm.router.Router` to recognise a new -`auto_router/hybrid_router` deployment prefix. A pre-routing hook then intercepts every -request to the virtual model *before* a deployment is chosen. - -``` -Request model="hybrid-router" - │ - ▼ -Router.async_pre_routing_hook (patched by custom_hybrid_router.py) - │ model in hybrid_routers? NO → normal LiteLLM routing (unaffected) - │ YES ↓ - │ 1. Extract user + system text from messages - │ 2. HybridRouter.classify() → SIMPLE / MEDIUM / COMPLEX / REASONING - │ 3. HybridRouter.pick_model() → best real model for that tier (MAB bandit) - │ 4. Return PreRoutingHookResponse(model=) - │ - ▼ -LiteLLM routes to the chosen real model as normal - │ - ▼ -async_log_success_event / async_log_failure_event - Compute latency + token throughput → reward → bandit.update() - (the bandit learns, per tier, which model is fastest over time) -``` - -Requests to any other model name (`llama-3-1-8b`, `qwen3-4b`, …) are **not touched** — -only traffic addressed to the virtual `hybrid-router` entry is intercepted. - ---- - -## Two routing layers - -### Layer 1 — Complexity classification - -A lightweight, rules-based classifier (no extra model call) scores each prompt across -several dimensions — estimated token count, code / reasoning / technical / simple -keyword hits, multi-step patterns (`first … then`, `step 2`, numbered lists), and -question density — then maps the weighted score to a tier. - -| Tier | Score range | Typical queries | -|------|-------------|-----------------| -| `SIMPLE` | `< 0.15` | Greetings, factual lookups, yes/no | -| `MEDIUM` | `0.15 – 0.35` | Explanations, summaries, basic coding | -| `COMPLEX` | `0.35 – 0.60` | Architecture, multi-step code, technical analysis | -| `REASONING` | `≥ 0.60` **or** 2+ reasoning markers | Chain-of-thought, deduction, proof | - -Tier boundaries, token thresholds, keyword lists, and dimension weights are all -overridable via `complexity_router_config` (see the reference below). - -### Layer 2 — Efficiency (multi-armed bandit) - -Each tier owns an independent bandit whose arms are that tier's candidate models. A -model may be fast for `SIMPLE` prompts but slow for `COMPLEX` ones (longer generation), -so per-tier bandits learn these behaviours separately. - -After each response the router computes a reward and updates the arm: - -``` -time_per_token = latency_seconds / max(completion_tokens, 1) -reward = target_tpt / (target_tpt + time_per_token) # in (0, 1] -``` - -Failures record a reward of `0`. When `quality_weight > 0`, the reward blends -efficiency with a quality score: -`reward = (1 - quality_weight) * efficiency + quality_weight * quality_score`. - -Three bandit algorithms ship (selectable via `bandit`): - -| Value | Algorithm | Behaviour | -|-------|-----------|-----------| -| `thompson` *(default)* | Beta-Bernoulli Thompson Sampling | Posterior sampling; strong exploration/exploitation balance | -| `ucb` | Upper Confidence Bound | Optimism under uncertainty; `delta` widens the exploration bound | -| `epsilon_greedy` | ε-greedy | Explores uniformly with probability `epsilon`, else greedy | - -> A tier with only one candidate model skips the bandit entirely and routes directly. - ---- - -## Deployment - -The router is part of the **`litellm`** role and is controlled by one value: - -```yaml -# env//config.agent-toolkit.yaml -# Mount the custom hybrid router into the LiteLLM container. -hybrid_router_enabled: true -``` - -When `hybrid_router_enabled: true`, the chart: - -1. Renders the router source into the `litellm-router-code` ConfigMap - (`templates/router-configmap.yaml`). -2. Volume-mounts each Python file into `/etc/litellm/` and `/etc/litellm/router_strategy/…` in the - LiteLLM container (`templates/deployment.yaml`). -3. Registers the callback so LiteLLM imports the module (and applies the monkey-patch) - at startup: - - ```yaml - litellm_settings: - callbacks: ["custom_hybrid_router.proxy_handler_instance"] - ``` - -No image rebuild is required. To change router *code*, edit the files under -`ext/enterprise.ai-inference/roles/litellm/files/router/` and re-run -`./es_auto_installer.sh install agent-toolkit -- -e litellm_reconcile=true`; to change router -*config*, edit the `hybrid_router_*` settings in `env//config.agent-toolkit.yaml` and -re-run the same command. - ---- - -## Configuration reference - -Routing configuration lives on the virtual model's `litellm_params.hybrid_router_config`. - -| Key | Default | Description | -|-----|---------|-------------| -| `bandit` | `thompson` | MAB algorithm: `ucb`, `epsilon_greedy`, `thompson` | -| `delta` | `0.1` | UCB exploration parameter — smaller = more exploration (must be in `(0, 1)`) | -| `epsilon` | `0.1` | ε-greedy exploration probability (must be in `[0, 1]`) | -| `target_tpt` | `1.0` | Target time-per-token; sets the reward curve's midpoint | -| `quality_weight` | `0.0` | Quality-vs-efficiency blend in `[0, 1]`; `0` = pure efficiency | -| `tier_candidates` | *(defaults to `hybrid_router_default_model` for every tier)* | Map of tier → list of real model names | -| `tier_priors` | *(none)* | Optional per-tier, per-arm Beta priors `(alpha, beta)` for Thompson Sampling | -| `complexity_router_config` | built-in defaults | Override tier boundaries, token thresholds, keyword lists, dimension weights | -| `hybrid_router_default_model` | — | Fallback model; **required** if `tier_candidates` is omitted | - -`complexity_router_config.tier_boundaries` accepts `simple_medium`, `medium_complex`, -and `complex_reasoning` (defaults `0.15`, `0.35`, `0.60`). - ---- - -## Onboarding the virtual model - -Add the real backend models to the gateway as usual, then add **one** virtual entry -whose `model` uses the `auto_router/hybrid_router` prefix. Example config: - -```yaml -model_list: - # --- real backends --- - - model_name: llama-3-1-8b - litellm_params: - model: openai/llama-3-1-8b - api_base: http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/llama-3-1-8b/v1 - api_key: unused - - model_name: qwen3-coder-30b - litellm_params: - model: openai/qwen3-coder-30b - api_base: http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference/qwen3-coder-30b/v1 - api_key: unused - - # --- virtual hybrid-router entry (what clients call) --- - - model_name: hybrid-router - litellm_params: - model: auto_router/hybrid_router - hybrid_router_default_model: llama-3-1-8b - hybrid_router_config: - bandit: thompson - target_tpt: 1.0 - quality_weight: 0.0 - tier_candidates: - SIMPLE: [llama-3-1-8b, qwen3-coder-30b] - MEDIUM: [llama-3-1-8b, qwen3-coder-30b] - COMPLEX: [qwen3-coder-30b] - REASONING: [qwen3-coder-30b] - complexity_router_config: - tier_boundaries: - simple_medium: 0.15 - medium_complex: 0.35 - complex_reasoning: 0.60 -``` - -The `auto_router/hybrid_router` model is never dispatched directly — the pre-routing -hook rewrites the target before LiteLLM selects a deployment. - -### Onboarding at runtime via the `/model/new` API - -If the gateway is already running (and `store_model_in_db` is enabled), you can add the -virtual entry live — no config edit or restart — by POSTing to `/model/new` with the -master key. First retrieve the key the same way as the other guides: - -```bash -# Retrieve the LiteLLM master key from its Secret -export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm -o jsonpath='{.data.master_key}' | base64 -d) - -# Admin API: https://litellm., or a port-forward as here -kubectl port-forward -n litellm svc/litellm 4000:4000 & -curl -s --location 'http://localhost:4000/model/new' \ - --header "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - --header 'Content-Type: application/json' \ - --data '{ - "model_name": "hybrid_router2", - "litellm_params": { - "model": "auto_router/hybrid_router", - "hybrid_router_default_model": "qwen2-5-coder-14b", - "hybrid_router_config": { - "bandit": "thompson", - "delta": 0.1, - "epsilon": 0.1, - "target_tpt": 1.0, - "quality_weight": 0.0, - "tier_candidates": { - "SIMPLE": [ - "llama-3-1-8b", - "qwen2-5-coder-14b" - ], - "MEDIUM": [ - "llama-3-1-8b", - "qwen2-5-coder-14b" - ], - "COMPLEX": [ - "qwen3-coder-30b" - ], - "REASONING": [ - "qwen3-coder-30b" - ] - }, - "complexity_router_config": { - "tier_boundaries": { - "simple_medium": 0.15, - "medium_complex": 0.35, - "complex_reasoning": 0.60 - }, - "token_thresholds": { - "simple": 15, - "complex": 400 - } - } - } - }, - "model_info": {} -}' -``` - -The `model_name` is what clients call (here `hybrid_router2`), and every model listed -in `tier_candidates` / `hybrid_router_default_model` must already be onboarded on the -gateway. The `LITELLM_MASTER_KEY` is stored in the `litellm-master-key` Secret in the -`litellm` namespace. - ---- - -## Testing - -Send any request to `model="hybrid-router"`: - -```bash -curl -k https://litellm./v1/chat/completions \ - -H "Authorization: Bearer $LITELLM_MASTER_KEY" \ - -H "Content-Type: application/json" \ - -d '{"model": "hybrid-router", "messages": [{"role": "user", "content": "What is 2+2?"}]}' -``` - -The router classifies the prompt and transparently forwards it. Requests addressed to -`llama-3-1-8b`, `qwen3-coder-30b`, or any other model name are unaffected. - ---- - -## Observability - -The proxy logs one line at startup and one per routed request: - -``` -[HybridRouterProxy] litellm.router.Router patched for auto_router/hybrid_router -[HybridRouterProxy] Initialised model_name=hybrid-router bandit=thompson default=llama-3-1-8b tiers=['SIMPLE', 'MEDIUM', 'COMPLEX', 'REASONING'] -[HybridRouterProxy] model=hybrid-router call_id=... tier=SIMPLE -> llama-3-1-8b -``` - -Inspect them with: - -```bash -kubectl logs -n litellm deploy/litellm -c litellm -f -``` - -Per-tier bandit state (arm counts, running means, and — for Thompson — the Beta -`alpha`/`beta` posteriors) is exposed programmatically via -`HybridRouterProxy.router_state()`. Latency and token metrics also flow to Langfuse / -Prometheus through the standard gateway telemetry pipeline. - ---- - -## File layout - -``` -core/helm-charts/genai-gateway/ -├── values.yaml ← customRouter.enabled + callbacks -├── templates/ -│ ├── router-configmap.yaml ← renders router code into a ConfigMap -│ └── deployment.yaml ← volume-mounts the code into /app/ -└── router/ - ├── custom_hybrid_router.py ← callback + Router monkey-patch (entry point) - └── router_strategy/ - ├── complexity_router/ ← (tier config; sourced from LiteLLM) - ├── efficiency_router/ - │ ├── bandit.py ← UCB / EpsilonGreedy / ThompsonSampling - │ └── efficiency_router.py ← standalone efficiency router + reward fns - └── hybrid_router/ - └── hybrid_router.py ← two-layer router (classify → pick) -``` - ---- - -## Disabling the router - -Set `hybrid_router_enabled: false` in `env//config.agent-toolkit.yaml` and re-run -`./es_auto_installer.sh install agent-toolkit -- -e litellm_reconcile=true`. The ConfigMap and -volume mounts are removed and the callback is dropped, so the gateway behaves as a stock -LiteLLM proxy. Remove the virtual `hybrid-router` model entry as well so clients no -longer reference it. diff --git a/docs/intel-arc-xpu-deployment.md b/docs/intel-arc-xpu-deployment.md deleted file mode 100644 index 2b0638fb..00000000 --- a/docs/intel-arc-xpu-deployment.md +++ /dev/null @@ -1,195 +0,0 @@ -# Intel® Arc™ (XPU) GPU Deployment Guide - -> **Note:** not available with the unified installer in this release. - - - - -## Overview - -This guide describes how to deploy the Intel® Agent Toolkit on nodes -with Intel® discrete GPUs (Arc Battlemage B-series cards such as B60/B70) using the vLLM XPU backend. This is a third compute platform alongside the -existing CPU (Xeon) and GPU (NVIDIA) paths, selected via `compute_platform=xpu`. - -## Supported Models - -Selectable from the interactive menu (`31`–`36`) or by setting `models=` directly in -`core/inventory/agentic-config.cfg`. `Tensor Parallel` indicates how many GPUs a single -model replica is sharded across. - -| Menu # | Model ID | `models=` value | Tensor Parallel | -|--------|----------|------------------|:---:| -| 31 | Qwen/Qwen3-Coder-30B-A3B-Instruct | `xpu-qwen3-coder-30b` | 4 | -| 32 | Qwen/Qwen2.5-Coder-14B-Instruct | `xpu-qwen2-5-coder-14b` | 2 | -| 33 | meta-llama/Llama-3.1-8B-Instruct | `xpu-llama-8b` | 1 | -| 34 | Qwen/Qwen3-Coder-Next | `xpu-qwen3-coder-next` | 4 | -| 35 | google/gemma-4-31B-it *(default)* | `xpu-gemma4-31b` | 4 | -| 36 | Qwen/Qwen3.6-27B | `xpu-qwen36-27b` | 4 | - -These map 1:1 to the `modelConfigs` entries in -[`core/helm-charts/vllm/xpu-values.yaml`](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/helm-charts/vllm/xpu-values.yaml), which -holds the per-model vLLM flags, tool-call parser, and tensor-parallel size. Update that file -if you need to change memory utilization, context length, or add a new model. - -> **Note:** `compute_platform=g` is a separate path for NVIDIA GPU deployments -> (e.g. `gpu-nvidia-b300-llama-70b`) and is unrelated to the Intel XPU backend described here. - -## Prerequisites - -Complete the general [prerequisites](./prerequisites.md) first, then the following -XPU-specific items on **every worker node that has an Intel discrete GPU**: - -### 1. Hardware - -- Intel® Arc™ / Flex / Max discrete GPU (this guide has been exercised on Battlemage B-series - cards). -- Confirm the render node is visible on the host: - ```bash - ls /dev/dri/ - # Expect renderD1xx entries, e.g. renderD128 - ``` - -### 2. GPU driver and Level Zero runtime - -Install the Intel GPU driver/compute runtime for your kernel (Xe or i915) so that -`libze_intel_gpu.so.1` and `libze_loader.so.1` exist under -`/usr/lib/x86_64-linux-gnu/`. The vLLM XPU container image does **not** ship these — the -Helm chart mounts them from the host via `hostPath` volumes (see -`extraVolumes`/`extraVolumeMounts` in `xpu-values.yaml`), so they must already be present -on the node before you deploy. - -### 3. Intel GPU Plugin for Kubernetes (automated) - -When `compute_platform=xpu`, `fresh-install.sh` automatically runs -`run_deploy_intel_gpu_plugin_playbook` (from `core/lib/components/intel-gpu-plugin.sh`) -right after the cluster configuration playbook and before any model is deployed. It -applies the "base" overlay manifest from -[intel/intel-device-plugins-for-kubernetes](https://github.com/intel/intel-device-plugins-for-kubernetes) -— no NFD or node labeling required — and waits for the resulting DaemonSet to roll out: - -``` -core/playbooks/deploy-intel-gpu-plugin.yml -``` - -The branch/tag it deploys from defaults to `main` and is controlled by -`intel_gpu_plugin_ref` in `core/inventory/metadata/agentic-metadata.cfg`; pin it to a -specific release tag there for reproducible deployments. - -After the run, confirm the resource is advertised on your node: - -```bash -kubectl describe node | grep -A2 'Allocatable:' | grep gpu.intel.com -``` - -You should see `gpu.intel.com/xe` (newer Xe kernel driver, e.g. Ubuntu 24.04+/25.10 on -Arc B-series) or `gpu.intel.com/i915` (legacy i915 driver) listed with a count. If it's -missing, re-run manually to see the failure: - -```bash -ansible-playbook -i "${INVENTORY_PATH}" --become --become-user=root \ - playbooks/deploy-intel-gpu-plugin.yml --extra-vars "intel_gpu_plugin_ref=main" \ - --vault-password-file "$vault_pass_file" -``` - -### 4. Driver resource name override (`xe` vs `i915`) - -`xpu-values.yaml` defaults to `xpuDeviceResource: "gpu.intel.com/xe"`. If your node plugin -exposes `gpu.intel.com/i915` instead, change it before deploying: - -```yaml -# core/helm-charts/vllm/xpu-values.yaml -#xpuDeviceResource: "gpu.intel.com/i915" -xpuDeviceResource: "gpu.intel.com/xe" -``` - -### 5. Supplemental group IDs - -`podSecurityContext.supplementalGroups: [990, 44]` in `xpu-values.yaml` grants the -non-root vLLM container access to `/dev/dri`. These GIDs are host-specific — verify and -adjust them if pods fail with a GPU permission error: - -```bash -getent group render video # e.g. render:x:990 video:x:44 -stat -c '%g %G' /dev/dri/renderD128 -``` - -## Configuration (`agentic-config.cfg`) - -Set `compute_platform=xpu` (or the short form `x`) and pick a model, either by number or -by name, in `core/inventory/agentic-config.cfg`: - -```ini -cluster_url=api.example.com -cert_file=~/certs/cert.pem -key_file=~/certs/key.pem -hugging_face_token= -compute_platform=xpu -models=xpu-gemma4-31b # or a menu number, e.g. models=35 -deploy_kubernetes_fresh=on -deploy_ingress_controller=on -deploy_genai_gateway=on -deploy_observability=off -deploy_llm_models=on -deploy_agenticai_plugin=off -deploy_redis=off -deploy_pgvector=off -deploy_kuberay=off -deploy_agent_sandbox=off -deploy_ceph=off -rack_scale_mode=off -deploy_guardrails=off -deploy_vllm_sr=off -``` - -If `models=` is left blank and you run the toolkit interactively, `model-selection.sh` -will print the "Available Models for XPU Deployment" menu (31–36) and prompt for a choice. - -## Deploying - -```bash -# Fresh cluster + XPU model deployment -./es_auto_installer.sh install agent-toolkit - -# Add or remove models on an already-deployed cluster -./model-manager deploy # or: ./model-manager undeploy -``` - -Internally, `install-model.sh` detects `compute_platform=xpu`, sets `xpu_playbook=true`, -and passes `xpu_values_file=/vllm/xpu-values.yaml` to the -`playbooks/deploy-inference-models.yml` Ansible run, which then executes -`helm upgrade --install vllm--xpu ... --values ` for the tasks -tagged `install-xpu-`. - - -## Verifying the Deployment - -```bash -# Confirm the release is up -helm list -A | grep xpu - -# Watch pod status -kubectl get pods -l app.kubernetes.io/name=vllm | grep xpu - -# Test inference through the GenAI Gateway (adjust model name/path per the table above) -curl -k https://${BASE_URL}/v1/completions \ - -X POST \ - -d '{"model": "google/gemma-4-31B-it", "prompt": "What is Deep Learning?", "max_tokens": 50, "temperature": 0}' \ - -H 'Content-Type: application/json' \ - -H "Authorization: Bearer $TOKEN" -``` - -## Troubleshooting - -| Symptom | Likely Cause | Fix | -|---|---|---| -| Pod stuck `Pending`, event shows `Insufficient gpu.intel.com/xe` | Intel GPU Plugin not installed, or wrong `xpuDeviceResource` | Install the plugin (see Prerequisites §3) and confirm the resource name matches your driver (§4) | -| `libze_loader.so.1: cannot open shared object file` | Host is missing the Level Zero runtime | Install Intel GPU compute runtime on the node so the libs exist under `/usr/lib/x86_64-linux-gnu/` | -| `CreateContainerConfigError` / permission denied on `/dev/dri` | `supplementalGroups` GIDs don't match the host's `render`/`video` groups | Re-check with `getent group render video` and update `xpu-values.yaml` | -| Config validation fails with `Invalid value for compute_platform` | Older/uninstalled fix — ensure `read-config-file.sh` accepts `xpu`/`x` | Confirm you're on a build where `compute_platform=xpu` is accepted (see `core/lib/system/precheck/read-config-file.sh`) | -| Model deploys but never appears behind the GenAI Gateway | `xpu_playbook`/`xpu_values_file` not passed to Ansible | Confirm `install-model.sh`'s `ansible-playbook --extra-vars` includes `xpu_playbook=true xpu_values_file=...` | - -## References - -- [Intel GPU Plugin for Kubernetes](https://github.com/intel/intel-device-plugins-for-kubernetes) -- [vLLM XPU Backend Documentation](https://docs.vllm.ai/en/latest/getting_started/xpu-installation.html) -- [Intel discrete GPU driver installation guides](https://dgpu-docs.intel.com/driver/client/overview.html) diff --git a/docs/kuberay.md b/docs/kuberay.md deleted file mode 100644 index c39e5fa1..00000000 --- a/docs/kuberay.md +++ /dev/null @@ -1,277 +0,0 @@ -# KubeRay — Distributed Computing for Agentic Workloads - -**KubeRay** brings [Ray](https://www.ray.io/) — the Python-native distributed computing framework — into the Intel® Agent Toolkit as a first-class component. It enables agent workloads to fan out tasks across multiple CPU cores in parallel, run stateful actors, and use Ray's built-in autoscaler to match resource consumption to demand. - -The implementation deploys two components into the cluster: - -1. **KubeRay Operator** — a Kubernetes controller that manages `RayCluster` custom resources. -2. **RayCluster** — a head pod (scheduler/coordinator) and one or more worker pods (task executors) managed by the operator. - ---- - -## Architecture - -``` - ┌─────────────────────────────────────┐ - │ ray-system namespace │ - │ │ - Agent / client │ kuberay-operator │ - ─────────────► │ watches RayCluster CR │ - ray://... │ │ │ - │ ▼ │ - │ ray-cluster-head-svc (:10001) │ - │ │ │ - │ │ schedules tasks │ - │ ▼ │ - │ ray-cluster-worker-pod-0 │ - │ ray-cluster-worker-pod-1 ... │ - └─────────────────────────────────────┘ - - Ray Dashboard : http://ray-cluster-head-svc.ray-system.svc.cluster.local:8265 - Ray Client API : ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001 -``` - -**Key design points:** - -- The head pod runs with `num-cpus=0` so no user tasks are scheduled on it — all workloads run on workers. -- The Ray autoscaler reads `minReplicas` / `maxReplicas` from the cluster spec and adds or removes worker pods automatically based on pending task load. -- Worker count and resource limits are controlled entirely via **`env//config.agent-toolkit.yaml`**. The operator version is pinned in `env//config.agent-toolkit.yaml`. - ---- - -## Deployed Components - -| Component | Kind | Namespace | -|---|---|---| -| `kuberay-operator` | Deployment | `ray-system` | -| RayCluster CRD | ClusterScoped | — | -| `ray-cluster` | RayCluster CR | `ray-system` | -| `ray-cluster-head-svc` | Service (ClusterIP) | `ray-system` | -| Ray head pod | Pod | `ray-system` | -| Ray worker pods | Pods (autoscaled) | `ray-system` | - ---- - -## Configuration - -KubeRay uses **two separate groups of settings** to keep concerns clearly separated: - -| File | What to set | -|---|---| -| `env//config.agent-toolkit.yaml` | `kuberay_enabled: true` / `kuberay_enabled: false` — the deployment toggle | -| `env//config.agent-toolkit.yaml` | All tuning: namespace, Ray image, worker replicas, CPU/memory limits | - -### Enable deployment — `config.agent-toolkit.yaml` - -```yaml -kuberay_enabled: true -``` - -Set to `false` to skip KubeRay during the next run. If the `ray-system` namespace -already exists from a previous run, deployment is automatically skipped (resume mode). - -> **Note:** resume mode is not available in this release. - -### Tune the cluster — `config.agent-toolkit.yaml` - -```yaml -# Kubernetes namespace for all Ray resources -kuberay_namespace: "ray-system" - -kuberay_release_name: "ray-cluster" - -# Ray image — must match the ray[default] version used by connecting clients -kuberay_ray_image: "rayproject/ray:2.40.0-py312" - -kuberay_head_cpu_request: "500m" -kuberay_head_cpu_limit: "2" -kuberay_head_memory_request: "2Gi" -kuberay_head_memory_limit: "4Gi" - -kuberay_worker_replicas: 2 # initial worker count -kuberay_worker_min_replicas: 1 # autoscaler floor -kuberay_worker_max_replicas: 4 # autoscaler ceiling -kuberay_worker_cpu_request: "500m" -kuberay_worker_cpu_limit: "2" -kuberay_worker_memory_request: "2Gi" -kuberay_worker_memory_limit: "4Gi" -``` - -This file is created automatically with safe defaults on the first run of -`./es_auto_installer.sh init agent-toolkit`. Edit it before re-running to apply custom values. - -#### Worker resource sizing guide - -| Profile | `kuberay_worker_cpu_request` | `kuberay_worker_cpu_limit` | `kuberay_worker_memory_request` | `kuberay_worker_memory_limit` | -|---|---|---|---|---| -| Light (dev / single node) | `500m` | `2` | `1Gi` | `2Gi` | -| Medium *(default)* | `500m` | `2` | `2Gi` | `4Gi` | -| Heavy (multi-node / batch) | `2` | `8` | `8Gi` | `16Gi` | - -### Operator version pin — `config.agent-toolkit.yaml` - -```yaml -kuberay_operator_version: "1.3.0" -``` - -Update this value to upgrade the KubeRay operator. The Ray image in -`config.agent-toolkit.yaml` should be updated to match the corresponding Ray version. - ---- - -## Deployment - -```bash -# 1. Set the toggle in env//config.agent-toolkit.yaml -# kuberay_enabled: true - -# 2. (Optional) edit env//config.agent-toolkit.yaml to tune resources - -# 3. Run the deploy script -./es_auto_installer.sh install agent-toolkit -``` - -The deploy script runs 4 steps for KubeRay: - -| Step | Action | -|---|---| -| 1 | Create the `ray-system` namespace (idempotent) | -| 2 | Add the KubeRay Helm repo and install the operator | -| 3 | Deploy the RayCluster CR via the bundled `core/helm-charts/kuberay` chart | -| 4 | Poll until the head pod is Running and Ready | - ---- - -## Verify the Deployment - -```bash -# All pods should be Running -kubectl get pods -n ray-system - -# Expected output: -# NAME READY STATUS RESTARTS -# kuberay-operator-xxx 1/1 Running 0 -# ray-cluster-head-xxx 1/1 Running 0 -# ray-cluster-worker-small-xxx 1/1 Running 0 -# ray-cluster-worker-small-xxx 1/1 Running 0 - -# Check the RayCluster CR status -kubectl get raycluster -n ray-system - -# View the Ray Dashboard: https://ray./ (basic auth user ray, password below) -kubectl get secret ray-dashboard-auth -n ray-system -o jsonpath='{.data.password}' | base64 -d - -# Or port-forward from your local machine -kubectl port-forward svc/ray-cluster-head-svc 8265:8265 -n ray-system -# Then open: http://localhost:8265 -``` - ---- - -## In-Cluster Access Points - -| Endpoint | Address | -|---|---| -| **Ray Client API** | `ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001` | -| **Ray Dashboard** | `http://ray-cluster-head-svc.ray-system.svc.cluster.local:8265` | -| **GCS (internal)** | `ray-cluster-head-svc.ray-system.svc.cluster.local:6379` | - -These addresses are valid from any pod running in the cluster whose namespace is labelled -`istio.io/dataplane-mode=ambient`. From outside the cluster, open the Dashboard at -`https://ray./` (user `ray`, password in Secret `ray-dashboard-auth`), or use -`kubectl port-forward` to reach the Dashboard or Client API. - ---- - -## Connecting a Python Client - -Install Ray on the client side with the same version as the cluster image: - -```bash -pip install "ray[default]==2.40.0" -``` - -Connect from within the cluster (e.g. from the Coding Agent pod): - -```python -import ray - -ray.init("ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001") - -@ray.remote -def hello(): - return "Hello from Ray worker!" - -result = ray.get(hello.remote()) -print(result) # Hello from Ray worker! -``` - -Connect from outside the cluster via port-forward: - -```bash -kubectl port-forward svc/ray-cluster-head-svc 10001:10001 -n ray-system & -``` - -```python -import ray -ray.init("ray://localhost:10001") -``` - ---- - -## Scaling Workers - -### Manual scale - -```bash -# Scale to 5 workers immediately -kubectl scale raycluster ray-cluster -n ray-system --replicas=5 -``` - -### Via config (persistent) - -Edit `env//config.agent-toolkit.yaml`: - -```yaml -kuberay_worker_replicas: 5 -kuberay_worker_max_replicas: 8 -``` - -Then re-run: - -```bash -./es_auto_installer.sh install agent-toolkit -``` - ---- - -## Upgrading Ray - -1. Choose a target version from the [Ray Docker Hub tags](https://hub.docker.com/r/rayproject/ray/tags). -2. Update `config.agent-toolkit.yaml`: - ```yaml - kuberay_ray_image: "rayproject/ray:2.41.0-py312" - ``` -3. Update the operator version (`kuberay_operator_version`) in `config.agent-toolkit.yaml` if required. -4. Re-run `./es_auto_installer.sh install agent-toolkit` — the script upgrades the Helm releases in place. -5. Update `pip install "ray[default]==2.41.0"` in any client code. - -> **Note:** The Ray client version must match the cluster image version exactly. -> Mismatches cause connection errors. - ---- - -## Removing KubeRay - -```bash -# Uninstall the RayCluster -helm uninstall ray-cluster -n ray-system - -# Uninstall the operator -helm uninstall kuberay-operator -n ray-system - -# Delete the namespace (removes all remaining resources) -kubectl delete namespace ray-system -``` - -Set `kuberay_enabled: false` in `config.agent-toolkit.yaml` so subsequent deploy runs skip it. diff --git a/docs/multi-node-deployment.md b/docs/multi-node-deployment.md deleted file mode 100644 index 9e6095e4..00000000 --- a/docs/multi-node-deployment.md +++ /dev/null @@ -1,516 +0,0 @@ -# Multi-Node Deployment Guide - -> **100G Arista fabric deployment?** If your rack has a 100G Clos fabric, Intel® E810-C NICs, and NVMe storage nodes, use the **[Rack-Scale Deployment Guide](rack-scale-deployment.md)** instead — it covers BGP, dual-homed nodes, and Ceph-on-fabric with a single `rack-profile.yaml` config. -> -> **Note:** not available in this release. - -This guide describes how to deploy the Intel® Agent Toolkit across multiple nodes — a control-plane node running all stack services plus one or more worker nodes that host additional LLM inference workloads. - -The Kubernetes layer is provisioned by **Kubespray**, which natively supports multi-node clusters. Everything above Kubernetes (LiteLLM, Langfuse, Redis, Prometheus/Grafana) runs on the cluster and is automatically distributed by Kubernetes scheduling. - - -## Table of Contents - -- [Step 1 — Configure `hosts.yaml`](#step-1--configure-hostsyaml) -- [Step 2 — Configure the environment files](#step-2--configure-the-environment-files) -- [Step 3 — Deploy](#step-3--deploy) -- [Step 4 — Verify](#step-4--verify) -- [Step 5 — Semantic Router (Intelligent Query Routing)](#step-5--semantic-router-intelligent-query-routing) -- [Step 6 — Redis (Shared Memory Backend)](#step-6--redis-shared-memory-backend) -- [Step 7 — PostgreSQL + pgvector (Vector Store)](#step-7--postgresql--pgvector-vector-store--long-term-memory) -- [Step 8 — Agent Sandbox (Sandboxed Code Execution)](#step-8--agent-sandbox-sandboxed-code-execution) -- [Adding a Worker Node to a Running Cluster](#adding-a-worker-node-to-a-running-cluster) -- [Supported Deployment Topologies](#supported-deployment-topologies) -- [Notes](#notes) -- [Troubleshooting](#troubleshooting) - ---- - -## Step 1 — Configure `hosts.yaml` - -The default `env//inventory/hosts.yaml`, created by `./es_auto_installer.sh init agent-toolkit`, is a single-node config pointing to `localhost`. For multi-node, edit it to list every node under the correct Kubespray groups. - -### Single Master + Multiple Workers (recommended for most deployments) - -```yaml -all: - hosts: - master1: - ansible_host: 10.0.0.1 # control-plane private IP - ansible_user: ubuntu - ansible_ssh_private_key_file: /home/ubuntu/.ssh/id_rsa - ansible_connection: ssh - ansible_become: true - worker1: - ansible_host: 10.0.0.2 # worker node 1 private IP - ansible_user: ubuntu - ansible_ssh_private_key_file: /home/ubuntu/.ssh/id_rsa - ansible_connection: ssh - ansible_become: true - worker2: - ansible_host: 10.0.0.3 # worker node 2 private IP - ansible_user: ubuntu - ansible_ssh_private_key_file: /home/ubuntu/.ssh/id_rsa - ansible_connection: ssh - ansible_become: true - children: - kube_control_plane: - hosts: - master1: - kube_node: - hosts: - master1: - worker1: - worker2: - etcd: - hosts: - master1: - k8s_cluster: - children: - kube_control_plane: - kube_node: - calico_rr: - hosts: {} -``` - - -> **Note:** The node running `./es_auto_installer.sh install agent-toolkit` must be able to reach all other nodes via SSH using the key specified in `ansible_ssh_private_key_file`. For the node you run it on, either set `ansible_connection: local` in place of the SSH settings, or make sure that node can SSH to itself with the same key. Keep `ansible_connection: ssh` on every other node: the installer's playbook runs locally, and steps it runs for a node without that line (Kata, CPU pinning) would run on the installer machine instead. - ---- - -## Step 2 — Configure the environment files - -Open `env//global_config.yaml` and `env//config.agent-toolkit.yaml` and fill in your values: - -```yaml -# ---- env//global_config.yaml ---- - -# Required on multi-node: shared storage that every node can mount. nfs provisions an NFS server on the -# first control-plane node at /data/nfs (ceph and netapp-trident also work); local-path is single-node only -storage_backend: nfs - -# Your cluster FQDN — this becomes the base URL for all services -base_domain_name: "example.com" - -# TLS certificate — provide a full-chain cert + private key -# For a custom domain: supply your CA-signed or self-signed cert/key files -gateway_tls_mode: "custom" # selfsigned (default) | custom -gateway_tls_cert_file: "/path/to/your/fullchain.pem" -gateway_tls_key_file: "/path/to/your/private.key" - -# Enable/disable stack components -observability_enabled: true - -# Proxy settings (optional, depending on network) -http_proxy: "" -https_proxy: "" -no_proxy: "" - -# ---- env//config.agent-toolkit.yaml ---- - -# Model(s) to deploy — select the model(s) from the model list (ex: qwen2-5-coder-14b), separated by commas -llm_services_autodeploy_models: ["qwen2-5-coder-14b"] - -# API access: LiteLLM virtual keys (set by init agent-toolkit); "jwt" for Keycloak JWT -auth_type: "litellm_vkey" - -# Enable/disable stack components -# deploy_agenticai_plugin (Flowise agentic AI plugin): not available in this release -redis_stack_enabled: true # standalone Redis Stack in its own namespace -pgvector_enabled: true # optional: PostgreSQL 16 + pgvector — shared vector store and long-term memory backend -kuberay_enabled: false # optional: KubeRay operator — enables Ray distributed computing inside the cluster -agent_sandbox_enabled: true # optional: Agent Sandbox controller — isolated pod environments for safe code execution -openshell_enabled: false # optional: NVIDIA OpenShell policy-enforced sandboxes (requires agent_sandbox_enabled: true) -``` - -HuggingFace token (required to pull gated models): run `export HF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxx` before `./es_auto_installer.sh install agent-toolkit`. - ->*Note:* For proxy settings, see [running-behind-proxy.md](./running-behind-proxy.md). - -### Choose your model - -Set `llm_services_autodeploy_models` in `config.agent-toolkit.yaml` to one value from the table below: - -**CPU models** - -| # | Value to set in `llm_services_autodeploy_models` | Model | -|---|---|---| -| `21` | `qwen3-coder-30b` | Qwen/Qwen3-Coder-30B-A3B-Instruct | -| `22` | `qwen2-5-coder-14b` | Qwen/Qwen2.5-Coder-14B-Instruct *(default — used by the Coding Agent)* | -| `23` | `bge-base-en` | BAAI/bge-base-en-v1.5 *(text embedding)* | -| `24` | `bge-reranker` | BAAI/bge-reranker-base *(reranking)* | -| `25` | `qwen3-30b-a3b` | Qwen/Qwen3-30B-A3B-Instruct-2507 | -| `26` | `gemma-4-26b` | google/gemma-4-26B-A4B-it | -| `27` | `llama-3-1-8b` | meta-llama/Llama-3.1-8B-Instruct | -| `28` | `llama-3-1-8b-specdec` | meta-llama/Llama-3.1-8B-Instruct *(with speculative decoding)* | -| `29` | `qwen3-coder-30b-specdec` | Qwen/Qwen3-Coder-30B-A3B-Instruct *(with speculative decoding)* | -| `30` | `qwen3-6-35b-a3b` | Qwen/Qwen3.6-35B-A3B | - -> **Memory:** a node needs the `memory:` requests of its models (in `env//models.yaml`) plus about 17 GiB for the rest of the stack, and 16 GiB more for Qwen3Guard while the content-safety guardrail is on. The default install requests about 131 GiB (`qwen2-5-coder-14b` 96 GiB, Qwen3Guard 16 GiB, router 2 GiB, the rest 17 GiB); each model runs on one node, so one node must have room for it. On 128 GB nodes choose a 64 GiB model (`qwen2-5-coder-7b`, `llama-3-1-8b`). `qwen3-coder-30b` requests 160 GiB. - -> **Note:** `meta-llama/Llama-3.1-8B-Instruct` does not support parallel tool calling. Only sequential tool calls are supported with this model. - -> **Note:** For how per-model CPU/memory sizing and vLLM flags are configured under the -> hood, or to add a new model, see [Xeon (CPU) vLLM Model Configuration](xeon-model-configuration.md). - -**Speculative Decoding:** - -Models that support speculative decoding are available with a `-specdec` suffix (e.g. `qwen3-coder-30b-specdec`, `qwen2-5-coder-14b-specdec`, `llama-3-1-8b-specdec`). This technique uses a smaller draft model to generate candidate tokens quickly, which are then verified by the larger target model in parallel — reducing time-to-first-token and overall generation latency while preserving output quality. - -These models are registered in LiteLLM with a `-specdec` suffix to distinguish them from their non-speculative counterparts (e.g. `qwen3-coder-30b-specdec`). The draft model is automatically configured during deployment. - -To deploy a speculative decoding variant, set the `-specdec` model in `config.agent-toolkit.yaml`: - -```yaml -llm_services_autodeploy_models: ["qwen3-coder-30b-specdec"] -``` - -Multiple models can be deployed together using a comma-separated list: `llm_services_autodeploy_models: ["qwen3-coder-30b", "bge-base-en"]` - ---- - -## Step 3 — Deploy - -Run the deployment script from the control-plane node: - -```bash -./es_auto_installer.sh init agent-toolkit -./es_auto_installer.sh install agent-toolkit -``` - -Kubespray will use `env//inventory/hosts.yaml` to provision Kubernetes across all listed nodes (~20–30 min). The remaining stack components are then deployed on top. - ---- - -## Step 4 — Verify - -After deployment, confirm all nodes joined the cluster and all pods are healthy: - -```bash -# The installer writes the cluster's kubeconfig into the env -export KUBECONFIG=$(pwd)/env//kubeconfig.yaml - -# All nodes should show Ready -kubectl get nodes -o wide - -# All pods should be Running -# (the vLLM pod may take an additional 10-15 min to pull the model weights) -kubectl get pods -A - -# Retrieve the LiteLLM master key -export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm -o jsonpath='{.data.master_key}' | base64 -d) - -# (Optional) If behind a corporate proxy, update no_proxy to prevent the request from being intercepted by the proxy (replace with your base_domain_name) -export no_proxy="${no_proxy},litellm.,langfuse." - -# Gateway IP: map litellm. (and the other service names) to it in /etc/hosts -kubectl get svc -n envoy-gateway-system -l gateway.envoyproxy.io/owning-gateway-name=eg-gateway \ - -o jsonpath='{.items[0].status.loadBalancer.ingress[0].ip}' - -# List registered models to confirm the model name (replace with your base_domain_name) -curl -k https://litellm./v1/models \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" - -# Test chat completions (replace with your base_domain_name, then use the model name returned by /v1/models above) -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - -d '{"model": "qwen2-5-coder-14b", - "messages": [{"role":"user","content":"Write a Python hello world"}], - "max_tokens": 100}' -``` - -> The `LITELLM_MASTER_KEY` is stored in the `litellm-master-key` Secret in the `litellm` namespace. - ---- - -## Step 5 — Semantic Router (Intelligent Query Routing) - -Semantic routing automatically directs queries to the most appropriate model based on content analysis using embeddings. This allows you to route simple queries to faster/cheaper CPU models while directing complex tasks to more powerful GPU models or larger CPU models. - -**Why Use Semantic Routing?** - -- **Cost optimization:** Route simple queries to efficient models, complex ones to powerful models -- **Latency reduction:** Fast models handle straightforward requests quickly -- **Intelligent dispatch:** Coding tasks → coding-specialized models, reasoning → larger models -- **Transparent routing:** Applications use a single model name (e.g., `hybrid-router`), routing happens server-side - -> **📚 For more information:** See the official [LiteLLM Auto Routing documentation](https://docs.litellm.ai/docs/proxy/auto_routing#litellm-proxy-server) - -### Prerequisites - -- Step 4 complete and base stack verified -- At least one model deployed (you'll add a second model for routing) - -### 1. Deploy a Second Model and an Embedding Model - -The hybrid router spreads requests over the deployed chat models, so deploy a second one. **BAAI/bge-base-en-v1.5** (`bge-base-en`) is added as well, as the embedding model for your agents. - -A second larger model i.e. **Qwen/Qwen3-Coder-30B-A3B-Instruct** with better capabilities will also be deployed alongside your existing one. - -**Update `env//config.agent-toolkit.yaml` to include the embedding model and second model:** - -```yaml -llm_services_autodeploy_models: ["qwen2-5-coder-14b", "bge-base-en", "qwen3-coder-30b"] -``` - -**Deploy the model:** - -*Important:* With the NRI balloon policy, the default model (`cpu: auto`) takes the free physical cores of one NUMA node. When no NUMA node has enough free cores left, a further deploy stops with `NRI pre-flight failed: not enough physical cores`. To make room, set an explicit `cpu:` for each model in `env//models.yaml` (see [xeon-model-configuration.md](xeon-model-configuration.md)), then re-run the install: - -```bash -./es_auto_installer.sh install agent-toolkit -``` - -Restart the GenAI Gateway's Deployment: -```bash -kubectl rollout restart deployment litellm -n litellm -``` - -Follow the steps to [re-verify the base stack](#step-4--verify) to ensure models can be accessed. - -### 2. Access the LiteLLM UI - -Open `https://litellm./ui` in your browser (the gateway IP must be in `/etc/hosts` for that name, as in the quick-start). Without the hosts entry, port-forward the LiteLLM Service and open `http://localhost:4000/ui`: - -``` -kubectl port-forward -n litellm svc/litellm 4000:4000 -``` - -Login credentials: -- Username: default which is `admin` -- Password: the value of `LITELLM_MASTER_KEY` - -### 3. Configure Semantic Router via UI - -**Step 3a — Verify the Embedding Model:** - -1. Navigate to: **Models+Endpoints** → **All Models** tab -2. Look for `bge-base-en` in the models list - -**Step 3b — The hybrid router:** - -This release creates the `hybrid-router` model at install (`hybrid_router_enabled: true`, the default), so there is no UI step. It sorts each request by complexity and sends it to one of the deployed chat models. Models deployed after the install join it when you re-run `./es_auto_installer.sh install agent-toolkit`. Tiers and model lists: [hybrid-router.md](hybrid-router.md). - -### 4. Verify Semantic Routing - -```bash -export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm -o jsonpath='{.data.master_key}' | base64 -d) - -# Simple query — should route to the smaller/faster model -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - -d '{"model": "hybrid-router", "messages": [{"role":"user","content":"What is a Python list?"}], "max_tokens": 100}' - -# Complex query — should route to the more powerful model -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - -d '{"model": "hybrid-router", "messages": [{"role":"user","content":"How to code a program in Python that implements a distributed task queue with Redis backend"}], "max_tokens": 200}' -``` - -Check routing decisions in Langfuse at `https://langfuse.`. - -Login credentials: the Langfuse login and password are generated into the `langfuse-secrets` Secret in the `langfuse` namespace (keys `admin_email` / `admin_password`). - -Go inside the `inference` project. Under **Tracing**, select the most recent `litellm_request`, scroll down to **Metadata** → **attributes**. Look at the `llm.model_name` field to confirm routing decisions. - ---- - -## Step 6 — Redis (Shared Memory Backend) - -Redis is the **common memory backend** for all agentic workloads in this stack — deploy it before any use-case agent (MCP agents, etc.). - -The `charts/redis-stack` chart deploys **Redis Stack** (includes RediSearch) into its own `redis` namespace as a single persistent instance shared across all agents. - -**Automated deployment (recommended):** - -By default, Redis should already be deployed. You can check by running `kubectl get pods -n redis`. If not, follow the instructions below to deploy it. - -Set `redis_stack_enabled: true` in `env//config.agent-toolkit.yaml`: -```yaml -redis_stack_enabled: true -``` - -Then re-run `es_auto_installer.sh`: -```bash -./es_auto_installer.sh install agent-toolkit -``` - -**Verify it is running:** - -```bash -kubectl get pods -n redis -# NAME READY STATUS RESTARTS AGE -# redis-stack-server-0 1/1 Running 0 60s - -kubectl exec -n redis redis-stack-server-0 -- sh -c \ - 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning ping' -# PONG -``` - -**Redis URL (in-cluster) — use this in all agents:** - -```bash -kubectl get secret redis-stack-server-credentials -n redis \ - -o jsonpath='{.data.REDIS_URL}' | base64 -d -# redis://default:@redis-stack-server.redis.svc.cluster.local:6379 -``` - -### Redis security notes - -Redis holds agent session state and is a code-execution surface (Lua, plus JavaScript via RedisGears), so it must never be reachable unauthenticated. - -- **Authentication is mandatory** — the chart fails to render without a password. -- **The Service is `ClusterIP`.** Do not switch it to `NodePort` or `LoadBalancer`. On a multi-node cluster a NodePort binds the 30000-32767 range on *every* node IP, so anything that can route to any node reaches Redis. This matters most when nodes have public addresses or sit in a permissive cloud security group. -- **Firewall the NodePort range.** In addition to the inter-node ports listed above, restrict `30000-32767` to trusted sources at the host firewall or cloud security-group level. Do not expose it to the internet. -- **Mesh-only access.** Redis runs in the ambient mesh: namespaces in the mesh reach it, plaintext clients from outside are refused. - ---- - -## Step 7 — PostgreSQL + pgvector (Vector Store & Long-Term Memory) - -PostgreSQL 16 with the **pgvector** extension gives every agentic workload a persistent, queryable vector store for long-term memory, RAG pipelines, semantic search, and structured state storage. - -**When to enable:** -- Your agent needs long-term memory that survives pod/session restarts -- You are building RAG pipelines that store and retrieve embeddings -- Use cases require structured relational + vector data in the same store - -By default, `pgvector` should already be deployed. You can check by running `kubectl get pods -n pgvector`. If not, follow the instructions below to deploy it. - -Enable it in `env//config.agent-toolkit.yaml`: -```yaml -pgvector_enabled: true -``` - -Then re-run the deploy script: -```bash -./es_auto_installer.sh install agent-toolkit -``` - -**What gets deployed:** - -| Resource | Detail | -|---|---| -| Namespace | `pgvector` | -| Image | `pgvector/pgvector:pg16` (PostgreSQL 16 + pgvector extension) | -| Service | `pgvector.pgvector.svc.cluster.local:5432` | -| Database | `agentdb` | -| User | `agentuser` | -| Credentials secret | `pgvector-credentials` in the `pgvector` namespace | - -**Verify it is running:** - -```bash -kubectl get pods -n pgvector -# NAME READY STATUS RESTARTS AGE -# pgvector-0 1/1 Running 0 60s - -kubectl exec -n pgvector pgvector-0 -- \ - psql -U agentuser -d agentdb \ - -c "SELECT extname, extversion FROM pg_extension WHERE extname='vector';" -# extname | extversion -# --------+----------- -# vector | 0.8.0 -``` - -**Retrieve the connection string from the cluster secret:** - -```bash -kubectl get secret pgvector-credentials -n pgvector \ - -o jsonpath='{.data.DATABASE_URL}' | base64 -d -# postgresql://agentuser:@pgvector.pgvector.svc.cluster.local:5432/agentdb -``` - -**In-cluster connection string (for use in agent workloads):** - -``` -postgresql://agentuser:@pgvector.pgvector.svc.cluster.local:5432/agentdb -``` - ---- - -## Step 8 — Agent Sandbox (Sandboxed Code Execution) - -Agent Sandbox provides **isolated, ephemeral Kubernetes pods** for safe code execution. Every sandbox is a fully self-contained pod — the agent can run arbitrary code, install packages, and write files without touching the host or other workloads. - -By default, Agent Sandbox should already be deployed. You can check by running `kubectl get pods -n agent-sandbox-system`. If not, follow the instructions below to deploy it. - -Enable it in `env//config.agent-toolkit.yaml`: -```yaml -agent_sandbox_enabled: true -``` - -Then re-run the deploy script: -```bash -./es_auto_installer.sh install agent-toolkit -``` - -**What gets deployed** (all in the `agent-sandbox-system` namespace): - -| Component | Description | -|---|---| -| `agent-sandbox-controller` | Kubernetes operator that manages Sandbox pod lifecycle | -| CRDs | `sandboxes`, `sandboxtemplates`, `sandboxclaims`, `sandboxwarmpools` | -| `sandbox-router` | HTTP proxy that routes SDK requests to sandbox pods | -| `python-sandbox-template` | Default SandboxTemplate using a locally-built Python runtime | - -**Verify:** - -```bash -kubectl get pods -n agent-sandbox-system -# NAME READY STATUS RESTARTS -# agent-sandbox-controller-xxx 1/1 Running 0 -# sandbox-router-xxx 1/1 Running 0 - -kubectl get sandboxtemplate -n agent-sandbox-system -# NAME AGE -# python-sandbox-template 1m -``` - -> **In-cluster router URL** (used by the in-cluster agent): -> `http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080` - -For the full guide — adding custom templates, WarmPools, and SDK usage — see **[agent-sandbox.md](agent-sandbox.md)**. - ---- - -## Adding a Worker Node to a Running Cluster - -To expand a running cluster with an additional worker node: - -> **Note:** not available in this release. The installer provisions Kubernetes only while `env//kubeconfig.yaml` does not exist, so list every node in `env//inventory/hosts.yaml` before the first `./es_auto_installer.sh install agent-toolkit`. - ---- - -## Supported Deployment Topologies - -| Topology | Use case | -|---|---| -| Single node (default) | Development, testing, single-server deployments | -| 1 control-plane + N workers | Production — scale inference horizontally | -| 3 control-planes + N workers | HA production — no single point of failure on the control plane | - ---- - -## Notes - -- The platform gateway is the `eg-gateway` LoadBalancer Service in `envoy-gateway-system`; MetalLB assigns its address. Point DNS for `*.` at that address. -- **Redis** runs as a single `StatefulSet` in the `redis` namespace. It is shared across all agent namespaces but is not clustered by default. For high-availability Redis, configure Redis Cluster or Redis Sentinel via the `charts/redis-stack` chart values. -- **Model weights** are downloaded once into the `model-store` PVC in `llm-inference` and reused by later deploys. -- Ensure all required ports are open between nodes (Kubernetes API: 6443, etcd: 2379–2380, Calico: 179, kubelet: 10250). - ---- - -## Troubleshooting - -| Symptom | Resolution | -|---|---| -| Node shows `NotReady` | Check kubelet: `systemctl status kubelet` on the affected node | -| SSH connection refused during Kubespray | Verify `ansible_host` IPs and `ansible_ssh_private_key_file` paths in `hosts.yaml` | -| Pods stuck in `Pending` | Check node resources: `kubectl describe node ` | -| Model pod not scheduled on worker | Confirm the worker has sufficient CPU/RAM and no taints blocking scheduling: `kubectl describe node ` | - -For further help, open an issue in the repository. \ No newline at end of file diff --git a/docs/openshell.md b/docs/openshell.md deleted file mode 100644 index 9ab5c161..00000000 --- a/docs/openshell.md +++ /dev/null @@ -1,643 +0,0 @@ -# NVIDIA OpenShell (Policy-Enforced Sandboxes) - -[NVIDIA OpenShell](https://github.com/NVIDIA/OpenShell) adds a policy layer on top of -[Agent Sandbox](agent-sandbox.md). Its gateway creates sandboxes as `agents.x-k8s.io` -Sandbox CRs, and a supervisor inside every sandbox enforces: - -- **Egress default-deny** with per-host / per-binary allow rules and L7 (HTTP method/path) policy -- **Filesystem restrictions** (Landlock, best effort: applied where the node kernel supports it) and seccomp -- **Credential isolation** — the sandbox only sees a placeholder; the supervisor injects the - real credential into requests toward the allowed endpoint - -The toolkit registers the **GenAI Gateway** (LiteLLM) as an OpenShell provider, so agents in -OpenShell sandboxes call models through LiteLLM with a dedicated, budgeted virtual key that -never enters the sandbox. - -OpenShell is **optional** and **off by default** (`openshell_enabled: false`). - ---- - -## Supported Configuration - -| Component | Version | -|---|---| -| OpenShell Helm chart / images | `0.1.6` (`oci://ghcr.io/nvidia/openshell/helm-chart`) | -| OpenShell CLI (used by the deployment) | `v0.1.6` GitHub release | -| Agent Sandbox | `v1.0.10` (`agent_sandbox_enabled: true`) | -| GenAI Gateway | LiteLLM as deployed by `auth_type: "litellm_vkey"` (optional; provider is skipped if absent) | -| User authentication | Single-admin mode (ClusterIP gateway, access gated by Kubernetes RBAC) | -| CNI | Must enforce `NetworkPolicy` (e.g. Calico) | - -### Upgrading from OpenShell 0.0.x - -OpenShell 0.1.0 introduced breaking changes. Before running the toolkit deployment against an -existing 0.0.x installation, follow the upstream [0.1.0 upgrade guide](https://docs.nvidia.com/openshell/v0.1.6/upgrade/0-1-0). -Back up the gateway database and credential-encryption material, coordinate the gateway, -drivers, supervisors, CLI and SDK versions, remove and recreate existing sandboxes, and preserve -or re-import provider profiles and credentials. Do not treat a version-pin change alone as a -complete migration. - ---- - -## Architecture - -Two different components are called "gateway" in this document: - -- **OpenShell gateway** — the OpenShell control plane. It creates and deletes sandboxes and - stores policies and provider credentials. It does not proxy LLM traffic. -- **GenAI Gateway (LiteLLM)** — the toolkit's existing model proxy (`auth_type: "litellm_vkey"`). - OpenShell does not deploy its own; sandboxes reach models only through this one. - -An **agent** is any program you run inside a sandbox (a custom Python agent, a coding -assistant, a framework app). OpenShell does not ship an agent. The **supervisor** is the -OpenShell process that runs in the same pod as the agent and enforces its policy. - -Deployment installs the platform once; each agent run then gets its own sandbox, created on -demand with `openshell sandbox create` (or the gateway API) and removed with `sandbox delete`. - -``` -Admin / CI / orchestrator - │ openshell CLI or API over kubectl port-forward (mTLS client cert) - ▼ -OpenShell gateway (StatefulSet openshell-0, openshell-system) - │ 1. creates Sandbox CR ▲ 3. supervisor fetches policy and - ▼ │ provider credentials (mTLS) -Agent Sandbox controller ── 2. creates pod ──┐ -(agent_sandbox_enabled) ▼ -┌─ sandbox pod default-- (openshell-sandboxes) ─────────┐ -│ agent process (your code) ──► OpenShell supervisor │ -│ egress / L7 policy, Landlock│ -│ placeholder → real key │ -└──────────────────────────────────────┬──────────────────────┘ - │ 4. allowed traffic only - ┌────────────────────────────┴──────────────────┐ - ▼ ▼ -GenAI Gateway (LiteLLM, :4000) hosts allowed by the sandbox - virtual key → model backends policy (via the corporate proxy) -``` - ---- - -## How OpenShell Connects to the Toolkit - -### Reused toolkit components - -| Toolkit component | Used by OpenShell for | Changed | -|---|---|---| -| Kubernetes cluster | Runs the gateway and sandbox pods | No | -| Agent Sandbox controller `v1.0.10` (`agent_sandbox_enabled`) | Turns OpenShell `Sandbox` CRs into pods | No | -| GenAI Gateway / LiteLLM (`auth_type: "litellm_vkey"`) | The only path from a sandbox to models | One additional virtual key | -| Model backends behind LiteLLM | Reached through LiteLLM only | No | -| Deployment framework (`config.agent-toolkit.yaml`, `es_auto_installer.sh`, Ansible) | Installs and re-runs OpenShell like other components | New `openshell_enabled` switch | -| Proxy settings (`https_proxy`, `no_proxy`) | Sandbox egress is chained through the corporate proxy | No | -| CNI (e.g. Calico) | Enforces the sandbox NetworkPolicy | No | - -Not used by OpenShell: the Agent Sandbox router, `SandboxTemplate`, `WarmPool` and the -`k8s-agent-sandbox` SDK. OpenShell creates `Sandbox` CRs directly, so both ways of running -sandboxes coexist on the same controller. For the Fluent Bit limitation in legacy 0.0.116 -deployments, see [Legacy 0.0.116 Limitations](#legacy-0-0-116-limitations). - -### Added by OpenShell - -| Component | Kind | Role | -|---|---|---| -| OpenShell gateway | StatefulSet + Service `openshell:8080` (mTLS) | Sandbox lifecycle API, policy and credential store | -| Supervisor | Process in every sandbox pod | Egress and L7 enforcement, Landlock, seccomp, credential injection | -| `openshell` CLI | Binary on the admin host | Administration; used by the playbook to register the provider | -| Provider `genai-gateway` (profile `eat-genai-gateway`) | Gateway record | LiteLLM host and port, bearer credential, allowed binaries | -| NetworkPolicy `eat-openshell-sandbox-pods` | Added by the toolkit | Pod-level network limits under the supervisor | - -### Interfaces - -| # | From | To | Interface | Configured by | -|---|---|---|---|---| -| 1 | Admin / CI | OpenShell gateway | gRPC over mTLS through `kubectl port-forward` (secret `openshell-client-tls`) | Chart; see [Verification](#verification) | -| 2 | OpenShell gateway | Kubernetes API | Creates `agents.x-k8s.io/v1beta1` `Sandbox` CRs in `openshell-sandboxes` | Chart RBAC | -| 3 | Agent Sandbox controller | Kubernetes API | Reconciles the CR into a pod | Toolkit, unchanged | -| 4 | Supervisor | OpenShell gateway | gRPC over mTLS: policy, credentials, events | Playbook copies the client TLS secret into the sandbox namespace | -| 5 | Agent | Supervisor | All pod egress passes through the supervisor | OpenShell | -| 6 | Supervisor | LiteLLM `:4000` | OpenAI-compatible HTTP; `Authorization: Bearer ` rewritten to the virtual key | Provider profile; `providers_v2_enabled=true` (playbook) | -| 7 | Playbook | LiteLLM admin API | `kubectl exec` into the LiteLLM pod, `POST /key/generate` with the in-pod master key → Secret `openshell-genai-key` → provider credential | Playbook | -| 8 | LiteLLM | Model backends | Unchanged; the key's allowed models and budget apply | Toolkit, unchanged | -| 9 | Supervisor | External hosts | Only hosts in the sandbox policy, through the corporate proxy | `--policy` per sandbox; proxy from `global_config.yaml` | - -### Where credentials live - -| Credential | Location | Visible inside a sandbox | -|---|---|---| -| LiteLLM master key | LiteLLM pod only | No | -| Virtual key `openshell-sandboxes` | Secret `openshell-genai-key` and the OpenShell gateway | No — only a placeholder | -| Client certificate (`openshell-client-tls`) | `openshell-system` and `openshell-sandboxes` | Mounted for the supervisor; grants gateway admin, so restrict `pods/exec` | - ---- - -## Deployed Components - -| Component | Kind | Namespace | Notes | -|---|---|---|---| -| `openshell` | StatefulSet + Service (ClusterIP :8080, mTLS) | `openshell-system` | Upstream Helm chart with `charts/openshell/values.yaml` | -| `openshell-client-tls` | Secret | `openshell-system`, `openshell-sandboxes` | Client mTLS bundle; copied into the sandbox namespace (supervisors mount it) | -| `openshell-genai-key` | Secret | `openshell-system` | LiteLLM virtual key minted inside the LiteLLM pod (master key never leaves it) | -| `eat-genai-gateway` | Provider profile | gateway | LiteLLM endpoint, bearer credential, allowed binaries | -| `genai-gateway` | Provider | gateway | Attach to sandboxes with `--provider genai-gateway` | -| `eat-openshell-sandbox-pods` | NetworkPolicy | `openshell-sandboxes` | Pod-level egress/ingress limits for sandbox pods (see below) | - ---- - -## Configuration - -### Enable in `env//config.agent-toolkit.yaml` - -```yaml -agent_sandbox_enabled: true -openshell_enabled: true -``` - -`openshell_enabled: true` requires `agent_sandbox_enabled: true` in the same run, or Agent Sandbox -CRDs already present on the cluster; otherwise the deployment exits before installing -anything. On re-runs, resume mode skips OpenShell only if the `openshell_release_name` release -in `openshell_namespace` (as set in `config.agent-toolkit.yaml`) is `deployed` and the last run -completed with the current version pins and settings (see [Deployment](#deployment)). - -> **Note:** resume mode is not available in this release. - -### Version pins in `env//config.agent-toolkit.yaml` - -```yaml -openshell_chart_version: "0.1.6" -openshell_image_tag: "0.1.6" -openshell_release_tag: "v0.1.6" -``` - -### Settings in `env//config.agent-toolkit.yaml` - -| Variable | Default | Purpose | -|---|---|---| -| `openshell_release_name` | `openshell` | Helm release and gateway Service name | -| `openshell_namespace` | `openshell-system` | Gateway namespace (holds provider credentials) | -| `openshell_sandbox_namespace` | `openshell-sandboxes` | Sandbox pods | -| `openshell_allow_unauthenticated_clusterip_only` | `false` | Must be set to `true` to accept single-admin mode (see [Authentication](#authentication)) | -| `openshell_oidc_issuer` / `openshell_oidc_audience` | `""` / `openshell-cli` | OIDC user authentication (alternative to single-admin mode) | -| `openshell_genai_provider_enabled` | `true` | Register the GenAI Gateway provider | -| `openshell_genai_key_alias` | `openshell-sandboxes` | LiteLLM virtual key alias (spend tracking) | -| `openshell_genai_key_models` | `[]` | Models the key may use (empty = all) | -| `openshell_genai_key_max_budget` | `50` | LiteLLM budget for the key | -| `openshell_cli_dir` | `""` | Where the playbook keeps the CLI; empty = `~/.cache/eat/openshell-cli-` (mode `0700`) | -| `openshell_workspace_storage_class` | `""` | StorageClass for sandbox workspace volumes; empty = `local-path` when the cluster has it, else the default class. Multi-node NFS clusters get a non-default `local-path` class for this: seeding a workspace on NFS takes about 16 minutes | -| `openshell_sandbox_network_policy` | `true` | Apply `eat-openshell-sandbox-pods` | -| `openshell_upstream_proxy_cidrs` | RFC 1918 ranges | Where the corporate proxy may live (proxy port only) | -| `openshell_sandbox_egress_cidrs` | `[]` | Extra private CIDRs that sandbox policies may target | -| `openshell_sandbox_dns_cidrs` | `[]` | Extra resolvers reachable on port `53`; empty = auto-detect NodeLocal DNSCache | - -> **Note:** `openshell_allow_unauthenticated_clusterip_only` is not available in this release. - -The corporate proxy (`https_proxy` / `no_proxy` from `global_config.yaml`) is passed to the -gateway, which chains sandbox egress through it. - -### Authentication - -OpenShell on Kubernetes authenticates users with OIDC only; mTLS covers transport and -supervisors. Choose one mode: - -- **Single-admin (supported)**: leave `openshell_oidc_issuer` empty (the default). - The gateway stays `ClusterIP`; only users who can `kubectl port-forward` in - `openshell-system` and read `openshell-client-tls` can reach it. -- **OIDC**: set `openshell_oidc_issuer` (for example a Keycloak realm URL, served over HTTPS). - Not yet validated with the toolkit. - ---- - -## Deployment - -```bash -# env//config.agent-toolkit.yaml -agent_sandbox_enabled: true -openshell_enabled: true -openshell_oidc_issuer: "" # empty = single-admin via kubectl port-forward - -./es_auto_installer.sh install agent-toolkit -``` - -The `openshell` role runs 4 task groups: - -| Task Group | Action | -|---|---| -| 1 | Prerequisites — cluster connectivity, explicit auth mode, Agent Sandbox `v1beta1` API served | -| 2 | Namespaces, Helm install, client TLS copy into the sandbox namespace, sandbox NetworkPolicy, gateway rollout | -| 3 | GenAI Gateway provider — mint virtual key, register profile and provider via a temporary port-forward (CLI credentials removed afterwards) | -| 4 | Summary | - -Re-running is safe: the virtual key is minted once, the provider profile is updated in place -(running sandboxes pick up changes), and an existing provider is kept. - -The last task stores a fingerprint of the version pins, `inference_openshell.yml`, -`charts/openshell/` and the playbook in ConfigMap `openshell-deploy-state`. On the -next `./es_auto_installer.sh install agent-toolkit`, resume mode skips OpenShell only while that fingerprint -matches. To apply a changed pin, setting or provider profile, edit the file and re-run -`./es_auto_installer.sh install agent-toolkit` with `openshell_enabled: true`; a failed or interrupted run is retried -the same way. - -> **Note:** the `openshell-deploy-state` fingerprint is not available in this release. - ---- - -## Verification - -```bash -kubectl get pods -n openshell-system -# NAME READY STATUS RESTARTS -# openshell-0 1/1 Running 0 - -kubectl get secret openshell-genai-key -n openshell-system -kubectl get networkpolicy -n openshell-sandboxes -``` - -### Connect the CLI (admin, control plane) - -Install the CLI from the [v0.1.6 release](https://github.com/NVIDIA/OpenShell/releases/tag/v0.1.6), then: - -```bash -kubectl port-forward -n openshell-system svc/openshell 8080:8080 & -export NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost - -MTLS=${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/eat/mtls -mkdir -p "$MTLS" && chmod 700 "$MTLS" -for k in ca.crt tls.crt tls.key; do - kubectl get secret openshell-client-tls -n openshell-system \ - -o jsonpath="{.data.${k//./\\.}}" | base64 -d > "$MTLS/$k" -done -chmod 600 "$MTLS"/* - -openshell gateway add https://127.0.0.1:8080 --local --name eat -openshell provider list -# NAME TYPE CREDENTIAL_KEYS CONFIG_KEYS -# genai-gateway eat-genai-gateway 1 0 -``` - -> The client certificate grants full control of the gateway. Keep it on the control plane. - -### Run a sandbox that calls the GenAI Gateway - -```bash -openshell sandbox create --name demo --provider genai-gateway --detach \ - --env OPENAI_BASE_URL=http://litellm.litellm.svc.cluster.local:4000/v1 - -openshell sandbox exec -n demo --no-tty -- sh -c 'echo $OPENAI_API_KEY' -# openshell:resolve:env:..._OPENAI_API_KEY <- placeholder, not the key - -openshell sandbox exec -n demo --no-tty -- sh -c \ - 'curl -s $OPENAI_BASE_URL/models -H "Authorization: Bearer $OPENAI_API_KEY"' -# {"data":[{"id":"", ...}]} <- key injected by the supervisor - -openshell sandbox exec -n demo --no-tty -- \ - curl -s -m 10 -o /dev/null -w '%{http_code}\n' https://example.com -# 000 <- denied: not allowed by any policy - -openshell logs demo --source sandbox | grep DENIED -openshell sandbox delete demo -``` - -Without `--from`, sandboxes use the OpenShell community base image. Pass -`--from ` for your own agent image, and `--policy ` to allow additional -endpoints (see the [OpenShell policy reference](https://github.com/NVIDIA/OpenShell/blob/v0.1.6/docs/reference/policy-schema.mdx)). - ---- - -## Run OpenCode (coding agent) in a sandbox - -[OpenCode](https://opencode.ai) is preinstalled in the community sandbox image. It runs entirely -inside the sandbox and reaches the model only through the `genai-gateway` provider — so the -LiteLLM key never enters the sandbox, and every other outbound connection stays denied. This -reuses the same sandbox setup as above; you only add a small OpenCode config, then start its TUI. - -Pick a `MODEL` your GenAI Gateway serves that supports tool calling (from the `/models` list above). - -### 1. Create the sandbox and add a minimal OpenCode config - -```bash -MODEL= # a tool-calling model your GenAI Gateway serves - -# Deny-all network policy: the sandbox's ONLY egress is the genai-gateway provider endpoint. -# Without it, the community image's default policy lets python/pip reach PyPI. Filesystem and -# landlock are applied at startup, so this MUST be passed to `sandbox create` (it cannot be -# changed later with `policy set`). -cat > /tmp/opencode-policy.yaml <<'YAML' -version: 1 -filesystem_policy: - include_workdir: true - read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log] - read_write: [/sandbox, /tmp, /dev/null] -landlock: - compatibility: best_effort -network_policies: {} -YAML - -openshell sandbox create --name opencode --provider genai-gateway --policy /tmp/opencode-policy.yaml --detach \ - --env OPENAI_BASE_URL=http://litellm.litellm.svc.cluster.local:4000/v1 - -# OpenCode talks to the GenAI Gateway using the sandbox's injected env (placeholder key). -openshell sandbox exec -n opencode --no-tty -- sh -c 'mkdir -p ~/.config/opencode && cat > ~/.config/opencode/opencode.json' < In the community image, `opencode` is a Node launcher that starts the bundled executable -> `/usr/lib/node_modules/opencode-ai/bin/.opencode`, which makes the model calls. That path is -> allowlisted in the `genai-gateway` provider profile -> (`charts/openshell/genai-gateway-provider.yaml` in Intel® Agent Toolkit, `ext/enterprise.agent-toolkit/` in the -> enterprise-ai-solutions checkout). If a -> model call returns `binary ... not allowed in policy '_provider_genai_gateway'`, add OpenCode's -> resolved binary path there and re-run the deployment (or `openshell provider profile update`). - ---- - -## End-to-End Example: Restricted Agent - -**Scenario:** an LLM agent that runs arbitrary shell commands chosen by the model. It may read -from the GitHub API and call models through the GenAI Gateway, and nothing else: it cannot -write to GitHub, cannot send data to other hosts, and never sees the LiteLLM key. - -The example uses the default community image and a standard-library-only Python agent, so no -image build is needed. Run it on the control plane after -[connecting the CLI](#connect-the-cli-admin-control-plane). - -### 1. Write the sandbox policy - -`github-readonly.yaml` allows `curl` to reach `api.github.com` with read-only methods. The -GenAI Gateway endpoint is added by the `genai-gateway` provider, so it is not listed here. - -```yaml -version: 1 -filesystem_policy: - include_workdir: true - read_only: [/bin, /usr, /lib, /proc, /dev/urandom, /etc, /var/log] - read_write: [/tmp, /dev/null] -landlock: - compatibility: best_effort -network_policies: - github_api: - name: github-api-readonly - endpoints: - - host: api.github.com - port: 443 - protocol: rest - enforcement: enforce - access: read-only - binaries: - - path: /usr/bin/curl -``` - -### 2. Write the agent - -`agent.py` gives the model one tool, `run_shell`, and loops until the model answers without -a tool call: - -```python -"""Minimal tool-calling agent: the LLM gets one tool that runs shell commands in the sandbox.""" -import json, os, re, subprocess, sys, urllib.request - -MODEL = os.environ["MODEL"] # a model id from GET /v1/models -# Tool output goes into the next LLM request; redact credential placeholders before sending it. -PLACEHOLDER = re.compile(r"openshell:resolve:env:[A-Za-z0-9_]+") -TOOLS = [{"type": "function", "function": { - "name": "run_shell", "description": "Run a bash command and return its output.", - "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]}}}] - - -def chat(messages): - req = urllib.request.Request( - os.environ["OPENAI_BASE_URL"] + "/chat/completions", - json.dumps({"model": MODEL, "messages": messages, "tools": TOOLS}).encode(), - {"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"], "Content-Type": "application/json"}) - return json.load(urllib.request.urlopen(req, timeout=120))["choices"][0]["message"] - - -def run_shell(cmd): - p = subprocess.run(["bash", "-c", cmd], capture_output=True, text=True, timeout=30) - return PLACEHOLDER.sub("[credential]", f"exit={p.returncode}\n{p.stdout}{p.stderr}")[-2000:] - - -messages = [{"role": "system", "content": "You are an agent in a Linux sandbox. Use run_shell (curl is " - "available). Run each step once. If a step fails, report the error and move on; do not try workarounds."}, - {"role": "user", "content": sys.argv[1]}] -for _ in range(10): - msg = chat(messages) - messages.append({k: v for k, v in msg.items() if v is not None}) - if not msg.get("tool_calls"): - print("[final]", msg.get("content")) - break - for call in msg["tool_calls"]: - cmd = json.loads(call["function"]["arguments"])["cmd"] - out = run_shell(cmd) - print(f"$ {cmd}\n{out[:300]}\n") - messages.append({"role": "tool", "tool_call_id": call["id"], "content": out}) -``` - -### 3. Create the sandbox - -```bash -openshell sandbox create --name agent-demo --provider genai-gateway \ - --policy github-readonly.yaml --upload agent.py:/sandbox/agent.py --detach \ - --env OPENAI_BASE_URL=http://litellm.litellm.svc.cluster.local:4000/v1 \ - --env MODEL= - -openshell sandbox get agent-demo -# Phase: Ready -``` - -Use a model id returned by `GET /v1/models` (see -[Run a sandbox that calls the GenAI Gateway](#run-a-sandbox-that-calls-the-genai-gateway)). - -### 4. Run the agent - -```bash -openshell sandbox exec -n agent-demo --no-tty -- python3 /sandbox/agent.py \ - '1) Get the tag name of the latest NVIDIA/OpenShell release from https://api.github.com/repos/NVIDIA/OpenShell/releases/latest. - 2) POST the tag name to https://httpbin.org/post. - 3) Create a gist: curl -s -o /dev/null -w "%{http_code}" -X POST https://api.github.com/gists -d "{}". - Then summarize which steps worked.' -``` - -Output (abridged; the model chooses the exact commands): - -``` -$ curl -s https://api.github.com/repos/NVIDIA/OpenShell/releases/latest | grep -o '"tag_name": "[^"]*"' | cut -d'"' -f4 -exit=0 -v0.1.6 - -$ curl -s -X POST https://httpbin.org/post -H "Content-Type: application/json" -d "{\"tag_name\": \"v0.1.6\"}" -exit=56 - -$ curl -s -o /dev/null -w "%{http_code}" -X POST https://api.github.com/gists -d "{}" -exit=0 -403 - -[final] Step 1: completed ... Step 2: failed due to network/access restrictions ... Step 3: returned 403 ... -``` - -| Agent action | Result | Enforced by | -|---|---|---| -| Chat completions to the GenAI Gateway | Allowed; spend recorded on the `openshell-sandboxes` key | Provider, credential injection | -| `GET api.github.com/repos/...` | Allowed | `github_api` policy, `read-only` access | -| `POST httpbin.org/post` | Blocked (`curl` exit 56) | Egress default-deny | -| `POST api.github.com/gists` | Blocked (HTTP 403) | L7 rule: `POST` not permitted by `read-only` | -| `echo $OPENAI_API_KEY` | Placeholder only | Credential isolation | - -### 5. Check the policy decisions - -The model may guess why a step failed (for example, it may attribute the 403 to missing GitHub -authentication). The sandbox log records the actual decision: - -```bash -openshell logs agent-demo --source sandbox | grep DENIED -# ... NET:OPEN [MED] DENIED /usr/bin/curl(426) -> httpbin.org:443 [policy:- engine:opa] -# [reason:endpoint httpbin.org:443 is not allowed by any policy] -# ... HTTP:POST [MED] DENIED POST http://api.github.com:443/gists [policy:github_api engine:l7] -# [reason:L7_REQUEST deny POST api.github.com:443/gists reason=POST /gists not permitted by policy] -``` - -### 6. Clean up - -```bash -openshell sandbox delete agent-demo -``` - ---- - -## Sandbox NetworkPolicy - -The toolkit applies `eat-openshell-sandbox-pods` as defense in depth under the OpenShell -egress policy. It selects only sandbox pods without `openshell.ai/boundary-role`, so the -split supervisor/workload pods used by newer charts retain the chart's stricter policies: - -- **Ingress**: only from `openshell-system` -- **Egress**: kube-dns, port `53` on the NodeLocal DNSCache address (auto-detected from the - `nodelocaldns` DaemonSet, or `openshell_sandbox_dns_cidrs`), `openshell-system`, the GenAI - Gateway on port `4000`, the proxy port on `openshell_upstream_proxy_cidrs`, - `openshell_sandbox_egress_cidrs`, and public addresses (all private and link-local ranges - excluded) - ---- - -## Legacy 0.0.116 Limitations - -These notes apply to deployments still running OpenShell 0.0.116; the toolkit defaults to 0.1.6. - -- **Credential placeholder in a request body fails the request.** If an agent copies the - placeholder into a request body (for example by pasting `env` output into its LLM context), - the supervisor rejects the request with `credential_injection_failed`. Redact - `openshell:resolve:env:*` from tool output before sending it to the model. -- **Sandbox pod logs show warnings only.** Policy decisions are written to a file inside the - pod; read them with `openshell logs `. Fluent Bit does not collect them. -- **`kubectl exec` into a sandbox pod bypasses the sandbox policy.** Restrict `pods/exec` in - `openshell-sandboxes` with Kubernetes RBAC. -- **One release name per cluster.** The chart creates a cluster-scoped ClusterRole named after - the release (`openshell-node-reader` for release `openshell`). A second install with the same - release name in another namespace fails with a Helm ownership error; set - `openshell_release_name` to a different value. -- **NetworkPolicy enforcement depends on the CNI.** Some CNIs (for example kindnet) do not block - traffic from a pod to its own node, such as the API server on a single-node cluster. - ---- - -## Removal - -The toolkit has no per-component uninstall. To remove OpenShell from a running cluster, set -`openshell_enabled: false` in `config.agent-toolkit.yaml` (so a later run does not reinstall it), then run -these steps on the control plane. They use the default names; if you changed them in -`config.agent-toolkit.yaml`, use yours. - -```bash -# 1. Delete the sandboxes (with the CLI connected, see Verification) -openshell sandbox list -openshell sandbox delete - -# 2. Uninstall the gateway, then delete both namespaces. helm uninstall keeps the gateway -# database PVC and the credential-encryption key Secret; deleting the namespaces removes -# them, together with the Secrets and the NetworkPolicy the playbook created. -helm uninstall openshell -n openshell-system --wait -kubectl delete namespace openshell-sandboxes openshell-system - -# 3. Revoke the LiteLLM virtual key (runs in the LiteLLM pod, which holds the master key) -kubectl exec -n litellm deploy/litellm -c litellm -- python -c ' -import os, urllib.request -req = urllib.request.Request("http://127.0.0.1:4000/key/delete", - b"{\"key_aliases\": [\"openshell-sandboxes\"]}", - {"Authorization": "Bearer " + os.environ["PROXY_MASTER_KEY"], "Content-Type": "application/json"}) -print(urllib.request.urlopen(req).read().decode())' - -# 4. Admin host: `gateway remove` keeps the client certificate files, so delete them too, -# and the CLI the playbook downloaded -openshell gateway remove eat -rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/eat" ~/.cache/eat/openshell-cli-v0.1.6 -``` - ---- - -## Troubleshooting - -```bash -kubectl get pods -n openshell-system -kubectl logs -n openshell-system statefulset/openshell -kubectl get sandbox,pods -n openshell-sandboxes -openshell logs --source sandbox -``` - -| Symptom | Cause / Fix | -|---|---| -| `openshell \| Check Agent Sandbox API is served (agent_sandbox)` fails | Enable Agent Sandbox in the same run | -| `OpenShell on Kubernetes authenticates users via OIDC only` | Choose an auth mode in `config.agent-toolkit.yaml` | -| LLM call returns `policy_denied` | The calling binary is not in the provider profile `binaries` list (`charts/openshell/genai-gateway-provider.yaml` in Intel® Agent Toolkit); edit it and re-run `./es_auto_installer.sh install agent-toolkit` with `openshell_enabled: true` | -| `transport error` / `Connection reset by peer`, or `--upload` fails with `ssh tar extract exited with status 255` | `kubectl port-forward` dropped a stream; retry the command (re-run `openshell sandbox upload ` for a failed upload), and restart the port-forward if it exited | -| CLI hangs | Make sure `NO_PROXY` includes `127.0.0.1`, so the CLI does not send gateway traffic through a proxy | -| Sandbox fails with `Policy fetch failed ... failed to connect to OpenShell server` | Sandbox DNS is blocked. Check `kubectl get netpol eat-openshell-sandbox-pods -n openshell-sandboxes -o yaml` lists the resolver from the pod's `/etc/resolv.conf` (NodeLocal DNSCache `169.254.25.10` on kubespray); if the cluster uses another DNS cache, set `openshell_sandbox_dns_cidrs` and re-run the deployment | - ---- - -## Configuration Files - -- **Role**: `roles/openshell/tasks/install.yaml` -- **Variables**: `roles/openshell/defaults/main.yaml` (override them in `env//config.agent-toolkit.yaml`) -- **Helm overlay**: `charts/openshell/values.yaml` -- **Provider profile**: `charts/openshell/genai-gateway-provider.yaml` - ---- - -## References - -- [NVIDIA/OpenShell](https://github.com/NVIDIA/OpenShell) -- [OpenShell v0.1.6 release](https://github.com/NVIDIA/OpenShell/releases/tag/v0.1.6) -- [Agent Sandbox in this toolkit](agent-sandbox.md) diff --git a/docs/overview/meet.md b/docs/overview/meet.md new file mode 100644 index 00000000..889edab5 --- /dev/null +++ b/docs/overview/meet.md @@ -0,0 +1,112 @@ +# Meet the Agent Toolkit + +[← Docs index](../README.md) + +Intel® Agent Toolkit is a layer for running production AI agents on Intel® Platforms. It provides the services a model endpoint does not: session and long-term memory, an Agent Sandbox, tool integration, and tracing. + +You choose the models to serve on Intel® Platforms. [Toolkit Manager](https://github.com/intel/toolkit-manager) installs the cluster (for example Kubernetes), the model gateway, and this toolkit in one run. Agents built with LangGraph, CrewAI, Microsoft Agent Framework, OpenClaw, or any other agentic framework connect through standard interfaces: an OpenAI-compatible endpoint for model calls, Redis and PostgreSQL/pgvector for memory and state, and the Agent Sandbox. Existing agent code needs no rewrite: change the base URL and the credentials. + +

+ Intel® Agent Toolkit. Your agent (LangGraph, CrewAI, OpenClaw, Microsoft Agent Framework) calls an API gateway (LiteLLM, auth, rate limits). The stack provides memory (Redis, PostgreSQL, pgvector), inference and routing (vLLM, SGLang, cloud LLMs), an agent sandbox for code execution, and observability (Langfuse, Prometheus, Grafana). Deployment scales from one node to a rack with Ansible, Helm, and autoscaling, on a cluster (for example Kubernetes) or Docker Compose, using Intel® Xeon® processors for orchestration and execution, with GPUs and cloud LLMs for inference. +

+ +## What is an agent in this stack? + +An **agent** is an application that calls a language model and then acts on the result: it may query a database, execute generated code, or invoke an external API, then return that result to the model and continue. + +In practice that loop looks like this: + +1. The application sends a prompt to a language model through the gateway. +2. The model returns text, a tool call, or generated code. +3. The application (or the agent runtime) executes that action: a database query, a sandbox run, or an external API. +4. The result is sent back to the model, and the loop continues until the task is done. + +Orchestration frameworks such as LangGraph, CrewAI, Microsoft Agent Framework, and OpenClaw implement steps 1, 2, and 4. This toolkit runs the production services that loop calls: model serving through the gateway, memory, the Agent Sandbox, and tools, and it keeps state between steps. + +## Which repository to start from + +Install from [Toolkit Manager](https://github.com/intel/toolkit-manager), not from this repository. `./toolkit_manager.sh` lives there: `init agent-toolkit` clones this repo under `ext/` and writes live config under `env/local/`. Edit those files; do not treat the YAML in this GitHub repo as the running config. + +Toolkit Manager can also install [Intel® Inference Toolkit](https://github.com/intel/inference-toolkit) (`init inference`) and [Intel® Chatbot Toolkit](https://github.com/intel/chatbot-toolkit) (`init erag`). + +For the first run, use [Prerequisites](../getting-started/prerequisites.md) and the [single-node quickstart](../getting-started/quickstart.md). For more than one host, use [multi-node deployment](../deployment/multi-node.md). + +## What install brings up + +A default install brings these parts up in order. Each part is configurable: you can bring your own cluster, pick the gateway and models, and switch individual toolkit components on or off. See [Configuration](../configuration/configuration.md). + +| Part | What it deploys | How you confirm it | +|---|---|---| +| **Platform** | Cluster (for example Kubernetes), storage, service mesh, identity, Prometheus / Grafana | `kubectl get nodes` shows Ready | +| **Intel® Inference Toolkit** | Model serving (vLLM or another engine), LiteLLM or the AI gateway, Langfuse | `https://litellm./v1/chat/completions` returns a completion | +| **Intel® Agent Toolkit** (this repository) | Redis, PostgreSQL with pgvector, Agent Sandbox, OpenShell, and KubeRay | Agents can store state and run actions off the host | + +`./toolkit_manager.sh init agent-toolkit` followed by `install agent-toolkit` installs all three. The toolkit needs a cluster and model serving, so a successful install includes both a model API and the agent backends. + +## Architecture deep dive + +The numbered overview above is the product picture. The diagram below is the request path once the stack is running: the application calls the OpenAI-compatible gateway; behind it are model serving, memory, the sandbox, tools, and observability on the cluster (for example Kubernetes). + +

+ Intel® Agent Toolkit architecture: agent frameworks call a gateway with guardrails and observability; memory (Redis, PostgreSQL), sandbox and Ray, inference routing to SLMs and LLMs; deploy on Kubernetes or Docker Compose on Intel® Xeon® and accelerators. +

+ +## Toolkit components + +The install and configuration guides use these names. Each component ships with a default implementation that you can run immediately; a component can be replaced later without rebuilding the rest of the stack. + +| Component | Default | Role | +|---|---|---| +| **LiteLLM** | On (`auth_type: litellm_vkey`) | HTTPS gateway: one URL, virtual keys per app, OpenAI-compatible `/v1/chat/completions` | +| **Redis Stack** | On | Short-term memory: session state, caches, and RediSearch | +| **PostgreSQL + pgvector** | On | Long-term memory: embeddings, RAG, and data that persists across pod restarts | +| **Agent Sandbox** | On | Isolated pods for agent actions, off the host | +| **OpenShell** | Off | Policy layer on the Agent Sandbox. Set `openshell_enabled: true` at install | +| **KubeRay** | Off | Distributes Python tasks across worker pods. Set `kuberay_enabled: true` | +| **Keycloak realm** | On | Creates an `agent-toolkit` realm on the platform Keycloak (does not deploy Keycloak). Not required for the default LiteLLM path. Set `keycloak_agent_config_enabled: false` to skip it | +| **Langfuse** | On with LiteLLM | Trace UI for each LLM call: prompt, tokens, latency, and the model that served the request | + +For Keycloak JWT on the AI gateway (`auth_type: jwt`), see [Configuration](../configuration/configuration.md). + +## Deployment commands + +After [Prerequisites](../getting-started/prerequisites.md): + +```bash +./toolkit_manager.sh configure +./toolkit_manager.sh init agent-toolkit +# edit env/local/*.yaml: see Configuration +./toolkit_manager.sh install agent-toolkit +``` + +`init` copies this repository's defaults into `env/local/`. Edit that copy; do not treat the files in git as live configuration. Run `install` again to resume a failed install or to apply YAML changes: the toolkit roles (Redis, pgvector, sandbox, KubeRay, OpenShell) upgrade on every run. + +## Request flow + +1. The application calls `https://litellm./v1/chat/completions` with a LiteLLM **virtual key** (create one after install; the master key is only for smoke tests and key admin). See [Build your first agent](../getting-started/first-agent.md). +2. LiteLLM authenticates the key. When guardrails are enabled, a safety model screens the prompt before the main model sees it. +3. The request is sent to the named model, or to a router that selects a model. See [Routing](../configuration/routing.md). +4. vLLM running on Intel® Platforms generates the completion. +5. If the agent then needs memory or code execution, it calls Redis, pgvector, or the sandbox **inside the cluster**. Those services are not exposed on the public gateway URL. + +In-cluster URLs are listed in the [Backend connection reference](../reference/backend-connections.md). + +## What this toolkit is not + +This toolkit is not LangGraph, CrewAI, or LangChain. Those frameworks run on top of the toolkit and use its gateway, memory stores and sandbox through standard clients. + +It is not a hosted model API. Models run on your hosts, on Intel® Platforms. A GPU is not required. You can still register a GPU or cloud endpoint (OpenAI, Anthropic, Gemini) on the same gateway later. + +## Next steps + +If this is the first time you are installing the stack, work through the pages in this order: + +1. **[Prerequisites](../getting-started/prerequisites.md)**: hardware, SSH, DNS, and the TLS certificate. +2. **[Quickstart](../getting-started/quickstart.md)**: install on one host and send a chat request. +3. **[Configuration](../configuration/configuration.md)**: the YAML files under `env/local/` when you need to change the default layout. + +The [glossary](../reference/glossary.md) defines the terms these pages use. The [FAQ](../faq-and-troubleshooting/frequently-asked-questions.md) answers the questions people ask after a first read. For more than one host, go to [multi-node deployment](../deployment/multi-node.md). After a chat completion succeeds, copy in-cluster URLs from the [backend connection reference](../reference/backend-connections.md), or tune [guardrails](../configuration/guardrails.md) and [routing](../configuration/routing.md). + +--- + +*Intel, the Intel logo and Xeon are trademarks of Intel Corporation or its subsidiaries.* diff --git a/docs/pictures/intel-agent-toolkit-architecture.png b/docs/pictures/intel-agent-toolkit-architecture.png deleted file mode 100644 index 075d9adf..00000000 Binary files a/docs/pictures/intel-agent-toolkit-architecture.png and /dev/null differ diff --git a/docs/prerequisites.md b/docs/prerequisites.md deleted file mode 100644 index 4c99edb1..00000000 --- a/docs/prerequisites.md +++ /dev/null @@ -1,140 +0,0 @@ -# Prerequisites — Intel® Agent Toolkit - -## Hardware - -| Resource | Minimum | Recommended | -|---|---|---| -| CPU | 48 cores | 96+ cores | -| RAM | 32 GB | 64 GB | -| Disk | 150 GB | 200 GB | -| OS | Ubuntu 22.04 / 24.04 | Ubuntu 22.04 LTS | -| Architecture | x86_64 | x86_64 | - -> **Note:** For tp1, tp2 system should have minimum 128Gi and for tp>=4 minimum 256Gi memory available for the model's pod. - -## Access - -- A [Hugging Face](https://huggingface.co) account with an API token that has **read** access to gated models. -- `sudo` privileges on the deployment node. -- Internet access from the node to pull Helm charts and container images. - -## Node Kernel Settings - -`fs.inotify.max_user_instances` is a per-UID limit shared by every container -running as that UID. The kernel default of 128 is exhausted on nodes running -many pods, after which file watchers fail with `too many open files` (e.g. the -vLLM-SR router loses config hot-reload). Raise it on every node: - -```bash -sudo tee /etc/sysctl.d/90-inotify.conf > /dev/null <<'EOF' -fs.inotify.max_user_instances = 8192 -fs.inotify.max_user_watches = 1048576 -EOF -sudo sysctl --system -``` - -## SSH Key Setup - -Log in as a non-root user with `sudo` privileges. Using `root` or a password-based account may cause unexpected behavior during deployment. - -1. **Generate an SSH key pair** (or use an existing one): - - ```bash - ssh-keygen -t rsa -b 4096 - ``` - - Leave the password blank when prompted. - -2. **Copy the public key** (`id_rsa.pub`) to every control plane and workload node that will be part of the cluster. - -3. **Add the public key** to `~/.ssh/authorized_keys` on each node: - - ```bash - echo "" >> ~/.ssh/authorized_keys - ``` - -4. **Verify SSH access** from the Ansible control machine to each node: - - ```bash - chmod 600 - ssh -i @ - ``` - - If a bastion host is used, ensure the Ansible control machine can reach the cluster nodes through it. - -5. **Configure the Ansible inventory** (`env//inventory/hosts.yaml`) with your node IPs and SSH user. Example templates are provided for both deployment topologies: - - | Topology | Example inventory | - |---|---| - | Single node (all-in-one) | [examples/single-node/hosts.yaml](examples/single-node/hosts.yaml) | - | Multi-node (3 control-plane + N workers) | [examples/multi-node/hosts.yaml](examples/multi-node/hosts.yaml) | - - Copy the appropriate template to `env//inventory/hosts.yaml` and replace `ansible_user`, `ansible_host`, and `ansible_ssh_private_key_file` with your actual values. - -## DNS and SSL/TLS Setup - -### Production Environment - -- Use a registered domain name with DNS records pointing to your server or load balancer. -- Obtain an SSL/TLS certificate from a trusted Certificate Authority (CA) and install it on your system. -- The certificate must cover the base domain **and all use-case subdomains**. For a `base_domain_name` of `api.example.com` the following FQDNs need to be covered: - - | FQDN | Purpose | - |---|---| - | `litellm.api.example.com` | GenAI Gateway (LiteLLM) | - | `langfuse.api.example.com` | Langfuse trace UI | - | `coding-agent-api.example.com` | Coding Agent UI. **Note:** not available in this release. | - | `vllm-sr.api.example.com` | vLLM Semantic Router dashboard | - - - Request a **multi-SAN** or **wildcard** (`*.api.example.com`) certificate from your CA that includes all of the above. -- Set up automatic renewal or calendar reminders before certificates expire. -- Ensure required firewall ports (e.g., port 80 for HTTP validation) are open during certificate issuance. - -### Development Environment - -For local testing, `litellm.api.example.com` can be mapped to the gateway IP. - -1. **Add entries to `/etc/hosts`** for every subdomain the stack uses: - - ```bash - # Get the private IP of the machine - hostname -I - - # Add all stack subdomains to /etc/hosts (replace with the gateway IP) - # Replace api.example.com with your actual base_domain_name - sudo bash -c 'cat >> /etc/hosts < litellm.api.example.com - langfuse.api.example.com - 127.0.0.1 coding-agent-api.example.com - vllm-sr.api.example.com - EOF' - ``` - - The subdomains follow this pattern for a `base_domain_name` of `api.example.com`: - - | Host entry | Service | - |---|---| - | `litellm.api.example.com` | GenAI Gateway (LiteLLM) | - | `langfuse.api.example.com` | Langfuse trace UI | - | `coding-agent-api.example.com` | Coding Agent UI. **Note:** not available in this release. | - | `vllm-sr.api.example.com` | vLLM Semantic Router dashboard | - - -2. **Generate a self-signed SSL certificate** covering all subdomains: - - ```bash - # Replace api.example.com with your actual base_domain_name - DOMAIN="api.example.com" - - mkdir -p ~/certs && cd ~/certs && \ - openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes \ - -subj "/CN=${DOMAIN}" \ - -addext "subjectAltName = DNS:${DOMAIN}, DNS:litellm.${DOMAIN}, DNS:langfuse.${DOMAIN}, DNS:coding-agent-${DOMAIN}, DNS:vllm-sr.${DOMAIN}" - ``` - - > **Note:** The `-addext` option requires OpenSSL ≥ 1.1.1. If you add more use cases later, regenerate the cert with the additional `DNS:` entries. - - Files generated: - - `cert.pem` — the self-signed certificate (contains SANs for all subdomains) - - `key.pem` — the private key diff --git a/docs/rack-scale-deployment.md b/docs/rack-scale-deployment.md deleted file mode 100644 index 5305d4bd..00000000 --- a/docs/rack-scale-deployment.md +++ /dev/null @@ -1,799 +0,0 @@ -# Rack-Scale Deployment — AI Fabric Mode - -> **Note:** not available with the unified installer in this release. - -This guide covers deploying the Intel® Agent Toolkit on a -high-performance rack with a **high-speed Ethernet AI fabric** (100G, 200G, 400G, or 800G), -Intel® E810-C or compatible NICs, and NVMe Ceph storage — using the `rack_scale_mode` deployment path. - -> **Speed-agnostic design:** The deployment stack (Kubespray, Calico BGP, Rook/Ceph, and the -> rack-profile parser) does not depend on link speed. Migrating from 100G to 400G or 800G -> requires only updating NIC names and fabric IPs in `rack-profile.yaml` and adjusting the -> `mtu` field to match your switch configuration. No code changes are needed. -> -> **Validated on:** Intel® Lab201 — Arista Clos fabric, Intel® E810-C NICs, 100G uplinks. - -In rack-scale mode, a single declarative file (`rack-profile.yaml`) describes -your entire hardware topology. The parser generates all derived Kubernetes and -Ceph config from it automatically. You do not hand-edit `hosts.yaml` or -`ceph-storage.yml`. - ---- - -## Table of Contents - -- [When to Use This Guide](#when-to-use-this-guide) -- [Architecture Overview](#architecture-overview) -- [Hardware Reference — Intel Lab201](#hardware-reference--intel-lab201) -- [How It Works](#how-it-works) -- [Fabric Topologies — Clos and Star](#fabric-topologies--clos-and-star) -- [Step 1 — Prerequisites](#step-1--prerequisites) -- [Step 2 — Edit rack-profile.yaml](#step-2--edit-rack-profileyaml) -- [Step 3 — Run the Parser](#step-3--run-the-parser) -- [Step 4 — Configure agentic-config.cfg](#step-4--configure-agentic-configcfg) -- [Step 5 — Deploy](#step-5--deploy) -- [Step 6 — Verify Fabric Networking](#step-6--verify-fabric-networking) -- [Step 7 — Verify Ceph on Fabric](#step-7--verify-ceph-on-fabric) -- [rack-profile.yaml Reference](#rack-profileyaml-reference) -- [Network Design Decisions](#network-design-decisions) -- [Validated Performance](#validated-performance) -- [Troubleshooting](#troubleshooting) - ---- - -## When to Use This Guide - -Use this guide when your rack has: - -- A **high-speed Ethernet AI fabric** (100G, 200G, 400G, or 800G) — either a switched - Clos fabric with BGP routing, or a **switchless star** where nodes are cabled - directly to one another (see [Fabric Topologies](#fabric-topologies--clos-and-star)) -- Intel® **E810-C** or compatible high-speed NICs in compute/storage nodes -- **Dual-homed nodes** — a high-speed fabric NIC for data plane + a 1G/10G management NIC -- **NVMe storage nodes** for Ceph OSD placement -- Multiple node families (e.g. Intel® GNR-AP compute + minfra control plane + mstore storage) - -For standard single-NIC multi-node deployments, see [multi-node-deployment.md](multi-node-deployment.md). - ---- - -## Architecture Overview - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ Management Network │ -│ 172.18.x.x (1G/10G) │ -│ master1/2/3 ceph1/2/3 gnr01–gnr06 │ -│ 172.18.168.x 172.18.168.x 172.18.148/158.x │ -└────────────┬───────────────┬────────────────────┬───────────────┘ - │ SSH / Ansible │ │ - │ │ │ -┌────────────▼───────────────▼────────────────────▼───────────────┐ -│ High-Speed AI Fabric (Arista Clos or equivalent) │ -│ Leaf-C (10.202.0.0/16) Leaf-D (10.201.0.0/16) │ -│ │ -│ ceph1: 10.201.2.1 gnr01: 10.201.148.1 + 10.202.148.1 │ -│ ceph2: 10.201.2.2 gnr02: 10.201.148.5 + 10.202.148.5 │ -│ ceph3: 10.201.2.3 gnr0N: ... │ -│ │ -│ Pod-to-pod traffic: native BGP, zero encapsulation, MTU 9000 │ -│ Ceph OSD traffic: 10.201.2.x ↔ 10.201.148.x (same fabric) │ -└─────────────────────────────────────────────────────────────────┘ -``` - -**Key design points:** - -- **Control plane on management** (`control_plane_on_fabric: false`) — kube-apiserver and etcd bind to `172.18.x.x`. Safe for sites where master nodes have only 1G management NICs. -- **Workers and storage on fabric** — kubelet `ip`/`access_ip` = fabric IP. All pod and Ceph traffic uses the high-speed fabric NIC. -- **Calico native BGP** — no IPIP or VXLAN overlay. Pods route directly via leaf switches at wire speed. -- **Ceph OSD bind address** = fabric IP. OSD-to-OSD replication and client traffic both flow over the fabric NIC. - ---- - -## Hardware Reference — Intel Lab201 - -| Node | Hostname | Role | Mgmt IP | Fabric IP(s) | NIC | -|---|---|---|---|---|---| -| master1–3 | minfra01–03 | control-plane, etcd | 172.18.168.1–5 | 10.201.1.1–3 | ens786f0np0 | -| ceph1–3 | mstore01–03 | storage (Ceph OSD) | 172.18.168.7–11 | 10.201.2.1–3 | ens786f0np0 | -| gnr01–03 | m6972m01–03 | compute (GNR-AP) | 172.18.148.1–9 | 10.201.148.x + 10.202.148.x | ens6f0 + ens28f0 | -| gnr04–06 | m6980m05–07 | compute (GNR-AP) | 172.18.158.17–30 | 10.201.158.x + 10.202.158.x | ens6f0 + ens28f0 | - -> GNR-AP compute nodes are **dual-homed** across both Arista leaf switches — -> `ens6f0` (Leaf-D, `10.201.x.x`) is the primary Kubernetes `access_ip`; -> `ens28f0` (Leaf-C, `10.202.x.x`) is reserved for RDMA/Multus secondary networks (Phase 3). - ---- - -## How It Works - -``` -rack-profile.yaml (you edit this — one file per site) - │ - ▼ -rack-profile-parser.sh (generates all derived config) - │ - ├──▶ core/inventory/hosts.yaml (Kubespray inventory) - ├──▶ core/inventory/metadata/k8s-net-fabric.yml (Calico BGP vars) - ├──▶ core/inventory/netplan/.yaml (fabric IPs + routes) - ├──▶ core/inventory/metadata/bgp-peers/*.yaml (per-node BGPPeer CRDs) - └──▶ core/inventory/metadata/vars/ceph-storage.yml (Ceph OSD vars) - │ - ▼ - ./es_auto_installer.sh install agent-toolkit - │ - ├──▶ deploy-netplan.yml → applies fabric IPs to the NICs - ├──▶ deploy-ecmp-sysctl.yml → star hub forwarding (star only) - ├──▶ verify-fabric.yml → fabric reachability precheck - ├──▶ Kubespray → Kubernetes cluster (BGP, MTU 9000, dual-homed) - ├──▶ Calico → Native BGP peering, no encapsulation - ├──▶ deploy-ecmp-sysctl.yml → ECMP hashing (post-Calico, BGP sites) - ├──▶ Rook/Ceph → OSDs on fabric IPs, NVMe raw devices - └──▶ AI Stack → LiteLLM, Langfuse, Redis, pgvector, Sandbox -``` - -The parser is the only place topology is interpreted. Everything downstream — -netplan, Ansible groups, sysctl targets — is derived from the profile, so the -deployment scripts contain no site-specific assumptions. - ---- - -## Fabric Topologies — Clos and Star - -`network.topology` selects how the parser wires the fabric. It defaults to `clos`, -so existing profiles that omit the key are unaffected. - -### `topology: clos` (default) - -Leaf/spine. Every fabric NIC declares the `leaf:` it is cabled to, and each leaf -declares its `peer_ip` (the switch SVI) and `fabric_subnet`. Nodes share a flat -subnet per leaf — `network.fabric_prefix` (default `16`) is the on-link prefix. - -The parser generates, per NIC: -- the address at `fabric_prefix` -- a gateway of the leaf's `peer_ip` -- static routes to every *other* leaf's `fabric_subnet` via that gateway - -With `calico_mode: bgp`, each secondary NIC also gets a `BGPPeer` CRD using -`sourceAddress`, so bird dials that leaf from the correct local IP. - -Leaves whose `peer_ip` is still `TBD` are skipped — no gateway, no routes, no peer. - -### `topology: star` (switchless) - -No switches. Each spoke is cabled directly to one hub node, and every cable is -its own point-to-point subnet — declare `prefix: 30` on each NIC and `peer:` the -inventory name of the node at the far end. Exactly one node sets -`fabric_router: true`. - -The parser: -- derives the **fabric supernet** — the smallest network containing every - `fabric_ip` in the profile -- gives each spoke a static route to that supernet via the hub IP that shares the - spoke's own /30 (the next-hop is on-link, so no ARP-for-a-stranger problem) -- gives the hub only its connected legs — no routes, since every /30 is local -- puts the hub in the `fabric_routers` inventory group, which - `deploy-ecmp-sysctl.yml` uses to set `net.ipv4.ip_forward=1` - -``` - master1 ──── 10.201.1.1/30 ──┐ - │ 10.201.1.2/30 - master2 ──── 10.201.1.5/30 ──┼── hpe690 (fabric_router: true) - │ 10.201.1.6/30 - master3 ──── 10.201.1.9/30 ──┘ 10.201.1.10/30 - - spoke route: 10.201.1.0/28 via - hub: forwards between legs (ip_forward=1) -``` - -> **Do not put a star fabric on one flat subnet.** Every node would believe its -> peers are on-link and ARP for them; the hub does not answer for addresses it -> does not own, so nothing resolves and etcd never forms a quorum. The /30-per-cable -> model is what makes the hub a router instead of a bystander. - -`calico_mode: vxlan` is the right choice for star — there are no switches to peer -with, so there is no BGP next-hop to program. - -### ECMP is derived, not labelled - -`deploy-ecmp-sysctl.yml` no longer targets a hardware label. The parser computes -the `ecmp_nodes` group: any node with **two or more fabric NICs whose leaf has a -real `peer_ip`**, when `calico_mode: bgp`. Those nodes get -`fib_multipath_hash_policy=1` and loose reverse-path filtering. - -Star nodes are excluded by construction — a star has no equal-cost paths to hash -across, only point-to-point legs. - -Both `ecmp_nodes` and `fabric_routers` are omitted from the inventory when no node -qualifies, so the playbook is a no-op on a single-homed Clos site. - ---- - -## Step 1 — Prerequisites - -Same as the standard deployment, plus: - -- All nodes reachable from the bastion (master1) via SSH on the **management network** (`172.18.x.x`) -- Fabric NICs physically cabled and **up**. Their IPs do not need to be set by hand — - the parser generates a netplan file per node from `rack-profile.yaml` and - `deploy-netplan.yml` applies it. The generated file is named `99-fabric.yaml` so it - outranks `50-cloud-init.yaml`. -- Interface names recorded accurately per node — they vary across node families. - Confirm with `ip -br link` on each node; do not assume they match. -- Clos only: leaf switches already configured with BGP and SVI gateway IPs -- NVMe devices on storage nodes wiped and unpartitioned (e.g. `nvme1n1`, `nvme2n1`, `nvme3n1` — **never `nvme0n1`** which is the OS disk) - -See [prerequisites.md](prerequisites.md) for SSH key and TLS setup. - ---- - -## Step 2 — Edit rack-profile.yaml - -`core/inventory/rack-profile.yaml` is the **single source of truth** for your rack hardware. Edit it to match your site. Do not edit `hosts.yaml` or `ceph-storage.yml` directly — they are generated. - -### Site metadata - -```yaml -site: - name: lab201 - location: "Your site name" - description: "Brief description" -``` - -### Network fabric - -```yaml -network: - calico_mode: bgp # 'bgp' for switched fabric | 'vxlan' for dev/switchless - topology: clos # 'clos' (default) | 'star' — see Fabric Topologies - pod_cidr: 10.244.0.0/16 # must not overlap fabric or mgmt subnets - service_cidr: 10.96.0.0/12 - mtu: 9000 # set to match your switch configuration - - fabric_prefix: 16 # default on-link prefix; override per NIC with `prefix:` - netplan_renderer: networkd # or NetworkManager — must match the host's renderer - - # false = masters/etcd stay on management network (recommended for most sites) - # true = masters also have fabric NICs and bind to fabric IPs - control_plane_on_fabric: false - - leafs: - - name: leaf1 - model: "Arista DCS-7170-64C" - asn: 65005 - peer_ip: 10.202.0.1 # Arista SVI gateway IP for this leaf's subnet - fabric_subnet: 10.202.0.0/16 - - name: leaf2 - model: "Arista DCS-7170-64C" - asn: 65004 - peer_ip: 10.201.0.1 - fabric_subnet: 10.201.0.0/16 - - bgp: - cluster_asn: 65100 # AS number assigned to all cluster nodes -``` - -For `topology: star`, delete the `leafs:` block entirely and see -[Star topology](#star-topology-example) below. - -### SSH access - -Defaults applied to every non-bastion node. Both are overridable per node. - -```yaml -access: - ansible_user: ubuntu - ansible_ssh_private_key_file: ~/.ssh/id_ed25519 -``` - -### Racks and nodes - -Each node entry maps its management IP, fabric NICs, and roles: - -```yaml -racks: - rack-infra: - nodes: - master1: - hostname: minfra01 - mgmt_ip: 172.18.168.1 - local: true # marks the Ansible bastion node - roles: [kube_control_plane, etcd] - fabric_nics: - - nic: ens786f0np0 - fabric_ip: 10.201.1.1 - leaf: leaf2 - - ceph1: - hostname: mstore01 - mgmt_ip: 172.18.168.7 - roles: [kube_node, storage] # 'storage' role → Ceph OSD node - fabric_nics: - - nic: ens786f0np0 - fabric_ip: 10.201.2.1 - leaf: leaf2 - - rack-compute: - nodes: - gnr01: - hostname: m6972m01 - mgmt_ip: 172.18.148.1 - roles: [kube_node, gnr_ap] - fabric_nics: - - nic: ens6f0 # primary — used as access_ip - fabric_ip: 10.201.148.1 - leaf: leaf2 - - nic: ens28f0 # secondary — dual-homed, so joins ecmp_nodes - fabric_ip: 10.202.148.1 - leaf: leaf1 -``` - -**Role reference:** - -| Role | Effect | -|---|---| -| `kube_control_plane` | Added to `kube_control_plane` Kubespray group | -| `etcd` | Added to `etcd` group | -| `kube_node` | Added to `kube_node` (worker) group | -| `storage` | Added to `ceph_storage_nodes`; Ceph OSD devices assigned | -| `gnr_ap` | Added to `gnr_ap` group; NRI CPU policy applied | - -Roles outside this table produce a warning and no inventory group — the parser -lists what it recognises so a typo does not silently drop a node from a group. - -A node may combine roles. `[kube_control_plane, etcd, storage]` colocates the -control plane with Ceph OSDs; the Rook chart already carries the tolerations for -the control-plane taint (operator, mon/mgr placement, provisioner, plugin, and -discover). Adding `kube_node` to a master also schedules general workloads there -— a valid choice on a small cluster, but the control-plane taint no longer -protects it. - -#### Star topology example - -Set `topology: star`, drop `leafs:` and every `leaf:` key, then declare each cable -as its own /30 with `peer:` naming the far end. Exactly one node sets -`fabric_router: true`. - -```yaml -network: - calico_mode: vxlan - topology: star - control_plane_on_fabric: true - -racks: - rack-infra: - nodes: - master1: - hostname: gigabyte01 - mgmt_ip: 172.26.38.228 - local: true - roles: [kube_control_plane, etcd, storage] - fabric_nics: - - nic: enp167s0np0 - fabric_ip: 10.201.1.1 - prefix: 30 - peer: worker1 - - rack-compute: - nodes: - worker1: # the hub — one NIC per spoke - hostname: hpe690 - mgmt_ip: 172.26.38.103 - roles: [kube_node] - fabric_router: true - fabric_nics: - - nic: enp151s0np0 - fabric_ip: 10.201.1.2 - prefix: 30 - peer: master1 -``` - -The parser rejects a star profile that has no `fabric_router`, has more than one, -or whose `peer:` names a node that is not defined. It also warns if a spoke's /30 -contains no hub IP — that combination cannot produce a working route and almost -always means the addresses or the cabling map are wrong. - -### Storage - -```yaml -storage: - ceph_fabric_nic: ens786f0np0 # NIC used for Ceph public + cluster network - ceph_public_network: 10.201.0.0/16 - ceph_cluster_network: 10.201.0.0/16 - - nodes: - - name: ceph1 - devices: [nvme1n1, nvme2n1, nvme3n1] # raw NVMe devices for OSD — NOT nvme0n1 - - name: ceph2 - devices: [nvme1n1, nvme2n1, nvme3n1] - - name: ceph3 - devices: [nvme1n1, nvme2n1, nvme3n1] -``` - -> **Important:** `nvme0n1` is the OS disk on all storage nodes — never list it. -> Ceph will wipe any device listed here. Verify with `lsblk` on each storage node before proceeding. - ---- - -## Step 3 — Run the Parser - -```bash -cd /home/ubuntu/rack-scale/applications.ai.enterprise.agentic-ai-stack-rack-scale - -# Dry-run first — shows what would be generated without writing files -./core/lib/rack-profile-parser.sh --dry-run - -# Generate all derived files -./core/lib/rack-profile-parser.sh -``` - -**What gets generated:** - -``` -core/inventory/hosts.yaml - └─ All nodes with correct ip/access_ip (fabric IPs for workers/storage, - mgmt IPs for control-plane when control_plane_on_fabric=false) - └─ Ceph OSD nodes include their devices: list - -core/inventory/metadata/k8s-net-fabric.yml - └─ calico_mode, pod_cidr, service_cidr, mtu, BGP peer list - -core/inventory/metadata/vars/ceph-storage.yml - └─ ceph_fabric_nic, ceph_public/cluster_network, ceph_storage_nodes list -``` - -**Verify the output:** - -```bash -# Workers should have fabric IPs as ip/access_ip -grep -A3 "gnr01:" core/inventory/hosts.yaml -# ip: 10.201.148.1 -# access_ip: 10.201.148.1 - -# Control plane should have mgmt IPs (when control_plane_on_fabric=false) -grep -A3 "master1:" core/inventory/hosts.yaml -# ip: 172.18.168.1 -# access_ip: 172.18.168.1 - -# Ceph nodes should have fabric IPs and devices listed -grep -A6 "ceph1:" core/inventory/hosts.yaml -# ip: 10.201.2.1 -# access_ip: 10.201.2.1 -# devices: ['nvme1n1', 'nvme2n1', 'nvme3n1'] -``` - ---- - -## Step 4 — Configure agentic-config.cfg - -Open `core/inventory/agentic-config.cfg` and set: - -```ini -cluster_url=your-cluster-fqdn.example.com -cert_file=~/certs/cert.pem -key_file=~/certs/key.pem -hugging_face_token=hf_xxxxxxxxxxxxxxxxxxxx - -# Model — MoE models recommended for CPU inference (lower latency than dense) -models=cpu-qwen3-30b-a3b - -# Core deployment flags -deploy_kubernetes_fresh=on -deploy_ingress_controller=on -deploy_genai_gateway=on -deploy_observability=on -deploy_llm_models=on -deploy_agenticai_plugin=on -deploy_redis=on -deploy_pgvector=on -deploy_agent_sandbox=on - -# Ceph distributed storage — requires storage-role nodes in rack-profile.yaml -deploy_ceph=on - -# Enables rack-scale mode — activates fabric-aware Kubespray config, -# Calico BGP, and Ceph-on-fabric deployment paths -rack_scale_mode=on -``` - -> **`rack_scale_mode=on`** is the key flag. It activates: -> - Kubespray reading `k8s-net-fabric.yml` for BGP and MTU config -> - Calico deploying in native BGP mode (no IPIP/VXLAN) -> - Ceph reading `ceph-storage.yml` to bind OSDs to fabric IPs -> - Node labeling for `ei-inference-eligible` and `ei-infra-eligible` - -### Model selection for CPU inference - -| Model value | Parameters | Active params | Recommended for | -|---|---|---|---| -| `cpu-llama-8b` | 8B dense | 8B | Fastest, lowest latency | -| `cpu-llama-8b-specdec` | 8B + speculative | 8B | Faster with speculative decoding | -| `cpu-qwen3-30b-a3b` | 30B MoE | ~3B | **Best CPU trade-off** — large model quality, low cost | -| `cpu-qwen3-6-35b-a3b` | 35B MoE | ~3B | Newest Qwen MoE — same active cost, more capacity | -| `cpu-gemma4-26b-a4b` | 26B MoE | ~4B | Google Gemma4 alternative | -| `cpu-qwen2-5-coder-14b` | 14B dense | 14B | Coding-specialized, higher latency | -| `cpu-qwen3-coder-30b` | 30B dense | 30B | Highest quality, slowest | - -MoE (Mixture of Experts) models activate only a fraction of parameters per token, giving near-large-model quality at small-model inference cost. **`cpu-qwen3-30b-a3b` is the recommended default for CPU deployments.** - ---- - -## Step 5 — Deploy - -```bash -./es_auto_installer.sh init agent-toolkit -./es_auto_installer.sh install agent-toolkit -``` - -Expected phases: -1. **Kubespray** (~20–35 min) — provisions Kubernetes across all nodes, configures Calico BGP, sets MTU 9000 -2. **Ingress + Gateway** (~5 min) — NGINX ingress, LiteLLM -3. **Observability** (~5 min) — Prometheus, Grafana, Langfuse -4. **Ceph** (~10 min) — Rook operator, CephCluster, StorageClass -5. **LLM models** (~5–15 min depending on model weight download) -6. **Redis, pgvector, Agent Sandbox** (~5 min) - -Total: approximately 50–70 minutes for a fresh 12-node cluster. - ---- - -## Step 6 — Verify Fabric Networking - -After deployment, confirm pod traffic is running over the fabric: - -```bash -# All nodes Ready, workers on fabric IPs, masters on mgmt IPs -kubectl get nodes -o wide - -# BGP sessions — all cluster nodes should show Established -# SSH to a worker node and run: -ssh ubuntu@ "sudo birdc show protocols | grep -E 'Mesh|Established'" -# Expected: Mesh_10_201_x_x BGP ... Established - -# Pod-to-pod route uses fabric NIC (not mgmt NIC) -ssh ubuntu@ "ip route show 10.244.0.0/16" -# 10.244.x.x via 10.201.x.x dev ens6f0 ← fabric NIC ✅ - -# Cross-leaf pod latency -kubectl run ping-test --image=busybox --rm -it --restart=Never -- \ - ping -c4 -# Expected: < 1ms RTT -``` - -**Validated performance (Intel Lab201, Arista Clos, 100G E810-C NICs):** - -``` -iperf3 4-stream cross-leaf (gnr01 → gnr04): - [SUM] 0.00-10.00 sec 96.7 GBytes 83.1 Gbits/sec ✅ -``` - -> On 200G/400G/800G links, expected throughput scales proportionally — -> no configuration changes required beyond `mtu` and NIC interface names in `rack-profile.yaml`. - ---- - -## Step 7 — Verify Ceph on Fabric - -Confirm Ceph OSD traffic uses fabric IPs: - -```bash -# All OSDs up and on fabric IPs -kubectl -n rook-ceph exec deploy/rook-ceph-tools -- ceph osd find 0 -# "addr": "10.201.2.x:6800" ← fabric IP ✅ -# "host": "ceph1" - -kubectl -n rook-ceph exec deploy/rook-ceph-tools -- ceph status -# osd: 3 osds: 3 up, 3 in -# HEALTH_OK - -# Run a quick block storage write test -kubectl apply -f - <<'EOF' -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: ceph-verify-pvc -spec: - accessModes: [ReadWriteOnce] - storageClassName: ceph-block - resources: - requests: - storage: 10Gi ---- -apiVersion: v1 -kind: Pod -metadata: - name: ceph-verify -spec: - restartPolicy: Never - containers: - - name: fio - image: ljishen/fio - command: - - fio - - --name=seqwrite - - --filename=/data/testfile - - --rw=write - - --bs=1M - - --size=4G - - --numjobs=4 - - --iodepth=32 - - --ioengine=libaio - - --direct=1 - - --group_reporting - volumeMounts: - - name: data - mountPath: /data - volumes: - - name: data - persistentVolumeClaim: - claimName: ceph-verify-pvc -EOF - -kubectl wait pod/ceph-verify --for=condition=Ready=False --timeout=300s -kubectl logs ceph-verify | grep "WRITE:" -# WRITE: bw=XXXX MiB/s ← should be >500 MiB/s on NVMe fabric - -kubectl delete pod ceph-verify && kubectl delete pvc ceph-verify-pvc -``` - -**Validated performance (Intel Lab201, 3×NVMe nodes, 100G fabric, concurrent workloads):** - -| Test | Result | -|---|---| -| Sequential write (isolated) | **1.42 GB/s** | -| Random 4K read IOPS (concurrent) | **29,000 IOPS** | -| Random 4K write IOPS (concurrent) | **12,500 IOPS** | -| Fabric NIC utilization under load | ~18–20 Gbps (validated on 100G; NVMe is the bottleneck, not the fabric) | - ---- - -## rack-profile.yaml Reference - -### `network` fields - -| Field | Type | Description | -|---|---|---| -| `calico_mode` | `bgp` \| `vxlan` | CNI mode. `bgp` = native L3 via the switches, `vxlan` = overlay for dev/switchless | -| `topology` | `clos` \| `star` | Fabric wiring model. Default `clos`. See [Fabric Topologies](#fabric-topologies--clos-and-star) | -| `pod_cidr` | CIDR | Pod network. Must not overlap `10.201.x.x` fabric or `172.18.x.x` mgmt | -| `service_cidr` | CIDR | Kubernetes service network | -| `mtu` | int | Fabric MTU. Set to match switch config (9000 for jumbo frames) | -| `fabric_prefix` | int | Default on-link prefix for fabric NICs. Default `16`. Override per NIC with `prefix:` | -| `netplan_renderer` | `networkd` \| `NetworkManager` | Renderer written into the generated netplan. Default `networkd`. Must match the host | -| `control_plane_on_fabric` | bool | `false` = masters bind to mgmt IP (etcd/apiserver on management). `true` = masters also use fabric IPs | -| `leafs[].peer_ip` | IP | Switch SVI gateway IP — Calico BGP peer target. `TBD` skips gateway, routes, and peering | -| `leafs[].fabric_subnet` | CIDR | That leaf's subnet — used to generate cross-leaf routes | -| `leafs[].asn` | int | Leaf switch BGP ASN | -| `bgp.cluster_asn` | int | BGP AS number for all cluster nodes | - -### `access` fields - -| Field | Type | Description | -|---|---|---| -| `ansible_user` | string | SSH user for non-bastion nodes. Default `ubuntu`. Override per node | -| `ansible_ssh_private_key_file` | path | SSH key for non-bastion nodes. Default `~/.ssh/id_ed25519`. Override per node | - -### `node` fields - -| Field | Type | Description | -|---|---|---| -| `hostname` | string | Actual system hostname | -| `mgmt_ip` | IP | Management network IP (used for SSH/Ansible). Must be unique | -| `local` | bool | Mark the Ansible bastion node (`ansible_connection: local`) | -| `roles` | list | Kubespray groups this node joins. See role table above | -| `fabric_router` | bool | **Star only.** Marks the hub. Exactly one node must set it | -| `ceph_fabric_nic` | string | Overrides `storage.ceph_fabric_nic` for this node | -| `ansible_user` | string | Overrides `access.ansible_user` for this node | -| `ansible_ssh_private_key_file` | path | Overrides `access.ansible_ssh_private_key_file` for this node | -| `fabric_nics[].nic` | string | Kernel interface name (e.g. `ens6f0`) | -| `fabric_nics[].fabric_ip` | IP | IP to configure on this NIC. Must be unique | -| `fabric_nics[].prefix` | int | Overrides `network.fabric_prefix` for this NIC (e.g. `30` for a star cable) | -| `fabric_nics[].leaf` | string | **Clos only.** Leaf name from `network.leafs` this NIC connects to | -| `fabric_nics[].peer` | string | **Star only.** Inventory name of the node at the other end of the cable | - -The first entry in `fabric_nics` is the primary — it becomes `ip`/`access_ip`. -A node with no `fabric_nics` falls back to `mgmt_ip`. - -### `storage` fields - -| Field | Type | Description | -|---|---|---| -| `ceph_fabric_nic` | string | Site-wide NIC name carrying Ceph traffic. Its presence enables Rook's `provider: host`; the name itself is not passed to Rook but is validated against each storage node's real NICs. Override per node with `ceph_fabric_nic` | -| `ceph_public_network` | CIDR | Client-to-OSD network. Applied via Rook `network.addressRanges.public` | -| `ceph_cluster_network` | CIDR | OSD-to-OSD replication network. Applied via Rook `network.addressRanges.cluster` | -| `nodes[].name` | string | Node name (must match a node key in `racks`) | -| `nodes[].devices` | list | Raw block device names for OSD. **Never include the OS disk.** | - -### Derived inventory groups - -The parser computes these from the profile — they are never declared directly. - -| Group | Membership | -|---|---| -| `ecmp_nodes` | `calico_mode: bgp` nodes with ≥2 fabric NICs on leaves that have a real `peer_ip`. Gets ECMP flow hashing + loose RPF | -| `fabric_routers` | The `fabric_router: true` node in a star. Gets `ip_forward=1` | -| `cp_mgmt_nodes` | Control-plane nodes on the management network, when they share one NIC name | -| `cp_mgmt__nodes` | One group per distinct mgmt NIC name, when control-plane nodes differ | - -A group with no members is omitted from `hosts.yaml`, which is what makes the -sysctl playbook a safe no-op on a plain single-homed Clos site. - -### Validation - -The parser exits non-zero without writing any files when it finds: an unknown -`topology`; a duplicate `mgmt_ip` or `fabric_ip`; a star with zero or multiple -`fabric_router` nodes; or a `peer:` that names an undefined node. It warns (and -continues) on an unrecognised role, a `storage` node whose `fabric_nics` contain no -NIC matching its effective `ceph_fabric_nic`, `fabric_router` set outside a star, -and a star spoke that shares no subnet with any hub NIC. - -Run `./core/lib/rack-profile-parser.sh --dry-run` to see every generated file -without touching the filesystem. - ---- - -## Network Design Decisions - -### Why native BGP instead of VXLAN? - -VXLAN adds ~50 bytes of encapsulation overhead per packet and requires the host -kernel to encap/decap every packet. On a high-speed AI fabric with jumbo frames, this -wastes bandwidth and CPU cycles — and the penalty grows with link speed. - -With native BGP (`calico_mode: bgp`), Calico programs per-pod host routes via -bird and the Arista leaf switches forward pod traffic at L3 wire speed. No -encapsulation, no kernel overhead — packets go fabric NIC → Arista → fabric NIC. - -### Why control_plane_on_fabric=false? - -kube-apiserver and etcd are sensitive to network partitions. At most customer -sites, master nodes have only 1G management NICs. Binding etcd to a fabric IP -that could be unreachable during NIC or switch maintenance risks split-brain. -The management network is the safe choice for control-plane communication. - -Workers use fabric IPs as `access_ip` — kubelet and pod traffic go over 100G — -but kube-apiserver is still reachable on `172.18.x.x` from all nodes. - -### Why Ceph public and cluster networks on the same fabric subnet? - -For simplicity on a two-leaf Clos: all nodes can reach `10.201.0.0/16` via the -fabric. A separate cluster network is only needed if you want to isolate -OSD-to-OSD replication from client traffic. With high-speed fabric available, sharing the -subnet is not a bottleneck — the NVMe drives saturate before the network does. - ---- - -## Validated Performance - -All results measured on Intel Lab201 — Arista Clos fabric, Intel® E810-C NICs at **100G**, -3× control-plane, 3× NVMe storage, 6× GNR-AP compute nodes. - -The stack is speed-agnostic. Results on 200G/400G/800G fabrics will scale with link speed -— NVMe drive throughput and Ceph OSD count are the expected bottleneck, not the network. - -| Metric | Result | -|---|---| -| BGP sessions established | 11/11 ✅ | -| Cross-leaf iperf3 (4 streams, 100G links) | **83.1 Gbits/sec** | -| Cross-leaf pod RTT | **0.7ms** | -| Encapsulation overhead | **None** (native BGP — applies at any link speed) | -| Ceph sequential write (isolated, fio 4-job) | **1.42 GB/s** | -| Ceph random 4K read IOPS (concurrent burn) | **29,000** | -| Ceph random 4K write IOPS (concurrent burn) | **12,500** | -| Ceph fabric NIC utilization under burn | ~18–20 Gbps (NVMe-limited, not fabric-limited) | -| Cluster stability under burn | ✅ No errors, all OSDs up | - ---- - -## Troubleshooting - -| Symptom | Check | -|---|---| -| Workers show mgmt IP as `INTERNAL-IP` instead of fabric IP | Parser generated incorrect `ip`/`access_ip`. Re-run `rack-profile-parser.sh` and verify `control_plane_on_fabric` setting | -| BGP sessions not `Established` | Verify Arista SVI IPs match `leafs[].peer_ip` in `rack-profile.yaml`. Check `sudo birdc show protocols` on a worker node | -| Ceph OSDs bound to mgmt IP instead of fabric IP | `ceph_fabric_nic` in `rack-profile.yaml` does not match actual NIC name on storage nodes. Verify with `ip link show` on a storage node | -| Ceph `HEALTH_WARN: too many PGs per OSD` | Benign with small OSD count. Fix: `kubectl -n rook-ceph exec deploy/rook-ceph-tools -- ceph config set global mon_max_pg_per_osd 300` | -| Pod-to-pod traffic going over mgmt NIC | Calico IP autodetection picked wrong interface. Check `calico_ip_auto_method` in `k8s-net-fabric.yml` — should be set to match the fabric NIC | -| NVMe device not used by Ceph | Device may have existing partitions. Wipe with `wipefs -a /dev/nvmeXn1` on the storage node, then re-run Ceph deployment | -| `rack-profile-parser.sh` reports missing node | Node name in `storage.nodes` does not match a node key in `racks`. Names must match exactly | -| `verify-fabric.yml` says a master's fabric IP is unreachable, but cabling is fine | On a **star**, spoke-to-spoke traffic transits the hub, so check the hub (`fabric_routers`) first: `sudo iptables -S FORWARD`. A bare `-P FORWARD DROP` with no `star fabric transit` ACCEPT rules blackholes spoke-to-spoke traffic while hub-to-spoke pings still succeed — so the fabric looks healthy. Both `reset.yml` and Kubespray's reset role flush the filter table, so this is the normal state after a reset. Fix: `ansible-playbook -i core/inventory/hosts.yaml core/playbooks/deploy-ecmp-sysctl.yml` | diff --git a/docs/reference/agent-sandbox.md b/docs/reference/agent-sandbox.md new file mode 100644 index 00000000..96911802 --- /dev/null +++ b/docs/reference/agent-sandbox.md @@ -0,0 +1,459 @@ +# Agent sandbox + +[← Docs index](../README.md) + +Agent-generated code must not run on the host or inside the model-serving pod. **Agent sandbox** runs it in a short-lived Kubernetes pod with its own filesystem, process tree, and network. The agent calls a router service, and the router creates the pod. Use this page to configure the sandbox, check it, add runtimes, and call it from the Python SDK. The implementation is [kubernetes-sigs/agent-sandbox](https://github.com/kubernetes-sigs/agent-sandbox). + +The sandbox is installed with `install agent-toolkit` and is on by default. For the in-cluster URL only, see the [backend connection reference](backend-connections.md#agent-sandbox). + +## How it works + +``` +Agent (e.g. Coding Agent) + │ HTTP (in-cluster DNS) + ▼ +sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080 + │ creates a SandboxClaim through the Kubernetes API + ▼ +agent-sandbox-controller + │ starts a pod from the SandboxTemplate + ▼ +sandbox-claim- (NetworkPolicy: ingress only from app=sandbox-router, same namespace) + │ + ▼ +python-runtime-sandbox: uvicorn on :8888 + POST /execute {"command": "..."} → {stdout, stderr, exit_code} +``` + +- Every component runs in the **`agent-sandbox-system`** namespace. The controller generates a NetworkPolicy that admits traffic only from `app=sandbox-router` pods in the same namespace, so templates and sandboxes must live there too. +- The router is a Go reverse proxy (`sandbox-router-go`). This install turns on `--authz-mode=tokenreview`, so each request to the router must carry a Kubernetes service-account Bearer token. There is no static `ROUTER_AUTH_TOKEN` secret. See [Router token](#router-token). +- Sandbox create and delete go through the Kubernetes API (CRDs). The router only forwards traffic to a running sandbox pod. +- Sandbox pods get an egress NetworkPolicy (`eat-sandbox-pool-egress`): they may reach the public internet, but **not** RFC1918 or link-local ranges. Code inside a sandbox cannot call in-cluster Redis, pgvector, or LiteLLM by ClusterIP. Reach those services from the agent pod, not from sandbox code. +- A default install also creates a warm pool of **5** idle Python sandbox pods (`agent_sandbox_python_warm_pool_size`). That uses CPU and memory before the first tool call. Set the size to `0` to skip pre-warming. +- All images come from published registries. No local build is required. + +| Component | Kind | Namespace | Image or detail | +|---|---|---|---| +| `agent-sandbox-controller` | Deployment | `agent-sandbox-system` | `registry.k8s.io/agent-sandbox/agent-sandbox-controller:v1.0.10` | +| CRDs | Cluster-scoped | | `sandboxes`, `sandboxtemplates`, `sandboxclaims`, `sandboxwarmpools` (v1beta1) | +| `sandbox-router` | Deployment | `agent-sandbox-system` | `registry.k8s.io/agent-sandbox/sandbox-router-go:v1.0.10` (TokenReview auth) | +| `sandbox-router-svc` | Service | `agent-sandbox-system` | ClusterIP :8080 | +| `python-sandbox-template` | SandboxTemplate | `agent-sandbox-system` | `registry.k8s.io/agent-sandbox/python-runtime-sandbox:v1.0.10` | +| `python-pool` | SandboxWarmPool | `agent-sandbox-system` | 5 pre-warmed pods from `python-sandbox-template` | + +## 1. Configure + +After `./toolkit_manager.sh init agent-toolkit`, set these in `env/local/config.agent-toolkit.yaml`. The defaults need no change. + +| Field | Default | What it means | +|---|---|---| +| `agent_sandbox_enabled` | `true` | Set `false` to skip the sandbox. | +| `agent_sandbox_namespace` | `agent-sandbox-system` | Namespace for every sandbox component. | +| `agent_sandbox_version` | `v1.0.10` | Upstream release. Selects the manifests fetched from GitHub and the runtime image tag. | +| `agent_sandbox_router_image` | `registry.k8s.io/agent-sandbox/sandbox-router-go:` | Router image. Override to mirror it for air-gapped clusters. | +| `agent_sandbox_python_runtime_image` | `registry.k8s.io/agent-sandbox/python-runtime-sandbox:` | Image for the default template. Override to mirror it. | +| `agent_sandbox_python_warm_pool_name` | `python-pool` | Name of the default warm pool. | +| `agent_sandbox_python_warm_pool_size` | `5` | Pre-warmed pods kept ready for the first call. Uses node CPU and memory on install. `0` creates no warm pool. | + +Cluster-wide settings that also apply (`base_domain_name`, `gateway_tls_mode`) are in `env/local/global_config.yaml`. API sign-in is `auth_type` in `config.agent-toolkit.yaml`. See [Configuration](../configuration/configuration.md). + + + +## Router token + +Every data-plane call through the router (command execution after `create_sandbox`) needs a Kubernetes service-account Bearer token. `/healthz` does not. Mint a short-lived token from a service account that can talk to the API (the default SA in the sandbox namespace is enough for a lab): + +```bash +export ROUTER_TOKEN=$(kubectl create token default -n agent-sandbox-system --duration=1h) +``` + +Pass it on every SDK client that talks to the router with `extra_headers` (Direct mode). Tunnel mode in SDK 1.0.10 has no `extra_headers` field, so from a workstation use a port-forward plus Direct mode: + +```bash +kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 +``` + +```python +from k8s_agent_sandbox import SandboxClient +from k8s_agent_sandbox.models import SandboxDirectConnectionConfig + +client = SandboxClient( + connection_config=SandboxDirectConnectionConfig( + api_url="http://localhost:8080", + extra_headers={"Authorization": f"Bearer {ROUTER_TOKEN}"}, + ) +) +``` + +In an agent pod, use the same `extra_headers` with `api_url="http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080"`, and prefer the pod's projected service-account token (`/var/run/secrets/kubernetes.io/serviceaccount/token`) instead of `kubectl create token`. + +## 2. Install + +```bash +./toolkit_manager.sh configure # one-time +./toolkit_manager.sh init agent-toolkit # writes env/local/ +./toolkit_manager.sh install agent-toolkit # installs the sandbox with the layer +``` + +The installer: + +1. Creates the namespace and applies the upstream `sandbox-with-extensions` manifest (CRDs and controller). +2. Waits for the controller, then applies the published `sandbox-router` manifests and pins the router image. It also sets TokenReview auth (`--authz-mode=tokenreview`). +3. Applies `python-sandbox-template` and creates the `python-pool` warm pool. + +Re-run `install` to resume a failed run or to re-apply the same manifests. The playbook does not skip the sandbox when the controller already exists. + +> The default `--env` is `local`; pass a different `--env ` to target +> another environment. `teardown` and `validate ` verbs are also +> available. + +## 3. Verify + +```bash +kubectl get pods -n agent-sandbox-system # all Running +kubectl get deployment -n agent-sandbox-system agent-sandbox-controller sandbox-router + +kubectl get crd sandboxes.agents.x-k8s.io -o jsonpath='{.spec.versions[*].name}' +# Expected: v1alpha1 v1beta1 + +kubectl get sandboxtemplate -n agent-sandbox-system # python-sandbox-template +kubectl get sandboxwarmpool -n agent-sandbox-system python-pool # 5 ready + +kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 & +curl -s http://localhost:8080/healthz +# {"status":"ok"} +``` + +## 4. Run code from the SDK + +Install the SDK version that matches the deployment. This release pins agent-sandbox **v1.0.10**, so use the matching SDK: + +```bash +pip install k8s-agent-sandbox==1.0.10 +``` + +SDK documentation: [agentic-sandbox-client](https://github.com/kubernetes-sigs/agent-sandbox/tree/v1.0.10/clients/python/agentic-sandbox-client). Mint a [Router token](#router-token) first; every example below needs it on `extra_headers`. + +| Where the client runs | Connection | +|---|---| +| Agent pod in the cluster | Direct mode to `sandbox-router-svc…:8080` plus a Bearer token | +| Workstation | `kubectl port-forward` to the router Service, then Direct mode to `http://localhost:8080` plus a Bearer token | + +**In the cluster (agent pods):** + +With Istio on, run the agent in a namespace labelled `istio.io/dataplane-mode=ambient`: the router is in the mesh with strict mTLS and refuses plain-text callers. + +```python +from pathlib import Path +from k8s_agent_sandbox import SandboxClient +from k8s_agent_sandbox.models import SandboxDirectConnectionConfig + +token = Path("/var/run/secrets/kubernetes.io/serviceaccount/token").read_text().strip() + +client = SandboxClient( + connection_config=SandboxDirectConnectionConfig( + api_url="http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080", + extra_headers={"Authorization": f"Bearer {token}"}, + ) +) + +sandbox = client.create_sandbox( + template="python-sandbox-template", + namespace="agent-sandbox-system", +) +try: + result = sandbox.commands.run("python3 -c \"print('Hello from in-cluster sandbox!')\"") + print(result.stdout) +finally: + sandbox.terminate() +``` + +**From a workstation.** Keep a port-forward running, mint `ROUTER_TOKEN` as in [Router token](#router-token), then: + +```python +import os +from k8s_agent_sandbox import SandboxClient +from k8s_agent_sandbox.models import SandboxDirectConnectionConfig + +client = SandboxClient( + connection_config=SandboxDirectConnectionConfig( + api_url="http://localhost:8080", + extra_headers={"Authorization": f"Bearer {os.environ['ROUTER_TOKEN']}"}, + ) +) + +sandbox = client.create_sandbox( + template="python-sandbox-template", + namespace="agent-sandbox-system", +) +try: + result = sandbox.commands.run("python3 --version") + print(result.stdout) +finally: + sandbox.terminate() +``` + +**Session sandbox (state across calls).** To keep installed packages and files between tool calls, create the sandbox once and reuse it (same `client` with the token): + +```python +_sandbox = None + +def get_sandbox(): + global _sandbox + if _sandbox is None or not _sandbox.is_active: + _sandbox = client.create_sandbox( + template="python-sandbox-template", + namespace="agent-sandbox-system", + ) + return _sandbox + +get_sandbox().commands.run("pip install pandas") +result = get_sandbox().commands.run("python3 -c 'import pandas; print(pandas.__version__)'") +print(result.stdout) + +get_sandbox().terminate() +_sandbox = None +``` + +## 5. Add a runtime template + +Add one `SandboxTemplate` per runtime (Node.js, R, Java, and so on). + +1. Build and push an image that serves the same API as `python-runtime-sandbox` on port 8888: `POST /execute` with `{"command": ""}`, returning `{"stdout": "...", "stderr": "...", "exit_code": 0}`. + + ```bash + docker build -t your-registry.io/my-node-sandbox:v1.0 ./path/to/dockerfile-dir + docker push your-registry.io/my-node-sandbox:v1.0 + ``` + + For local development without a registry, load the image instead: `kind load docker-image ` (Kind) or `minikube image load ` (Minikube). + +2. Create the template in `agent-sandbox-system`, the namespace where sandboxes are created. This is the default template with a different name and image: + + ```yaml + apiVersion: extensions.agents.x-k8s.io/v1beta1 + kind: SandboxTemplate + metadata: + name: node-sandbox-template + namespace: agent-sandbox-system + spec: + service: true # headless Service per pod: required for SDK DNS mode + podTemplate: + spec: + containers: + - name: runtime + image: your-registry.io/my-node-sandbox:v1.0 + imagePullPolicy: IfNotPresent # or Always for frequent updates + ports: + - name: api + containerPort: 8888 + protocol: TCP + resources: + requests: { cpu: "250m", memory: "256Mi" } + limits: { cpu: "1000m", memory: "1Gi" } + securityContext: + allowPrivilegeEscalation: false + runAsNonRoot: true + runAsUser: 1000 + capabilities: + drop: [ALL] + ``` + +3. Apply it and use it: + + ```bash + kubectl apply -f node-sandbox-template.yaml + kubectl get sandboxtemplate -n agent-sandbox-system + ``` + + ```python + sandbox = client.create_sandbox(template="node-sandbox-template", namespace="agent-sandbox-system") + ``` + +## 6. Add a warm pool + +A warm pool keeps idle sandbox pods ready, so `create_sandbox` returns without waiting for scheduling or an image pull. The controller hands out a warm pod and refills the pool in the background. The installer creates `python-pool`; to size it, use `agent_sandbox_python_warm_pool_size` before install. For another template, apply a pool in the same namespace as the template: + +```yaml +apiVersion: extensions.agents.x-k8s.io/v1beta1 +kind: SandboxWarmPool +metadata: + name: node-pool + namespace: agent-sandbox-system + labels: + app: node-pool +spec: + replicas: 3 # pre-warmed pods to keep + sandboxTemplateRef: + name: node-sandbox-template # must exist in the same namespace +``` + +```bash +kubectl apply -f warmpool.yaml +kubectl get sandboxwarmpool -n agent-sandbox-system +``` + +## Kata Containers + +A default sandbox pod uses the `runc` runtime. It is isolated by namespaces and cgroups and shares the host kernel with every other workload on the node. [Kata Containers](https://github.com/kata-containers/kata-containers) boots each pod in its own virtual machine and guest kernel. + +| RuntimeClass | Hypervisor | Notes | +|---|---|---| +| `kata-fc` | [Firecracker](https://github.com/kata-containers/kata-containers/tree/main/docs/design/arch-images#firecracker) | Small device model, about 125 ms boot. Needs the containerd devmapper snapshotter | +| `kata-qemu` | QEMU | Broader devices (VFIO and device passthrough). Heavier boot. Uses the default snapshotter | + +The template follows the upstream [Firecracker sandbox example](https://agent-sandbox.sigs.k8s.io/docs/use-cases/examples/firecracker-sandbox/) and keeps the published `python-runtime-sandbox` image, so the `k8s-agent-sandbox` SDK is unchanged. The Kata template differs by `runtimeClassName`. + +### Enable Kata + +```yaml +# env/local/config.agent-toolkit.yaml +agent_sandbox_enabled: true + +# env/local/global_config.yaml +kata_containers_enabled: true +kata_runtime: "kata-fc" # kata-fc | kata-qemu | both +kata_version: "3.32.0" # kata-deploy Helm chart version +``` + +Kata is an add-on. The `SandboxTemplate` it publishes needs the agent-sandbox CRDs. With `kata_containers_enabled: true` and `agent_sandbox_enabled: false`, the runtime classes are still installed and no Kata template or pool is created. + +### Node prerequisites + +| Requirement | Needed by | What the playbook does | +|---|---|---| +| `/dev/kvm` (Intel VT-x on bare metal, or nested virtualization on a VM) | both runtimes | `stat`. If the device is missing, the playbook loads `kvm` and `kvm_intel` when the CPU has the `vmx` flag, then checks again. If `vmx` is absent, it warns and skips the host | +| containerd devmapper snapshotter in `ok` state | `kata-fc` only | Provisioned by the playbook. It creates a loopback thin pool at `/var/lib/containerd/devmapper` (`containerd-devmapper.service`, so it survives reboot), registers the snapshotter in `/etc/containerd/config.toml`, and restarts containerd on each KVM-capable node | + +Firecracker cannot use overlayfs for the container rootfs. It needs devmapper. Kubespray rewrites `/etc/containerd/config.toml` on a fresh install, and the Kata step runs after that, so it writes the snapshotter again on every deploy. The thin pool defaults to a 100 GB sparse file. To use a real block device, pre-create a `containerd-thinpool` device and the playbook reuses it. + +| Situation | Result | +|---|---| +| No node exposes `/dev/kvm` | Stops. Enable VT-x, or set `kata_containers_enabled: false` | +| `kata_runtime` is `kata-fc` or `both`, and devmapper is not `ok` on any node | Stops. Fix the thin pool, or set `kata_runtime: kata-qemu` | +| Firecracker is on and devmapper is not `ok` on some nodes | Those nodes are not labelled. A label from an earlier run is removed. The run names them | +| `agent_sandbox_enabled: false` | Runtime classes are installed. No Kata template or pool | +| `kata_runtime` is not one of the three values | Stops and lists the valid values | + +### What gets installed + +| Resource | Kind | Namespace | +|---|---|---| +| `containerd-thinpool` and `containerd-devmapper.service` | devmapper thin pool (`kata-fc` only, per KVM node) | host | +| `kata-deploy` | DaemonSet (upstream Helm chart) | `kube-system` | +| `kata-fc` / `kata-qemu` | RuntimeClass | cluster | +| `ei-kata-eligible=true` | Node label, on nodes that passed the preflight | — | +| `kata-sandbox-template` | SandboxTemplate | `agent-sandbox-system` | +| `kata-pool` (size 1) | SandboxWarmPool | `agent-sandbox-system` | + +The chart is `oci://ghcr.io/kata-containers/kata-deploy-charts/kata-deploy`. `kata-deploy` installs the Kata binaries, guest kernel, and rootfs on each node and restarts containerd there. The rollout wait is 15 minutes. + +The warm pool is created without a readiness gate, so a virtualization problem on one node does not hang the stack install. Check it with the commands below. + +### Verify Kata + +```bash +kubectl get ds -n kube-system kata-deploy +kubectl get runtimeclass # kata-fc and/or kata-qemu +kubectl get nodes -l ei-kata-eligible=true +kubectl get sandboxtemplate,sandboxwarmpool -n agent-sandbox-system + +kubectl get pod -n agent-sandbox-system -l sandbox=kata \ + -o jsonpath='{.items[0].spec.runtimeClassName}{"\n"}' # kata-fc +``` + +From the SDK, use the same client as in [Run code from the SDK](#4-run-code-from-the-sdk) (with the [Router token](#router-token) on `extra_headers`). Only the warm pool name changes: + +```python +sandbox = client.create_sandbox( + warmpool="kata-pool", + namespace="agent-sandbox-system", +) +try: + # A microVM has its own guest kernel. This differs from `uname -r` on the host. + print(sandbox.commands.run("uname -r").stdout) +finally: + sandbox.terminate() +``` + +| Symptom | What to do | +|---|---| +| `FailedCreatePodSandBox ... ENOENT` on a `kata-fc` pod | Devmapper is not active on that node. `systemctl status containerd-devmapper` and `ctr plugins ls \| grep devmapper`, or set `kata_runtime: "kata-qemu"` | +| Sandbox pod stuck `Pending` | No node has both `ei-kata-eligible=true` and the `katacontainers.io/kata-runtime=true` label the RuntimeClass selects. `kubectl get nodes --show-labels` | +| `RuntimeClass 'kata-fc' was not created by kata-deploy` | That chart version has no fc shim. Check `kata_version` | +| Pod runs and `uname -r` matches the host | The pod landed on `runc`. Confirm `spec.runtimeClassName` | + +```bash +kubectl logs -n kube-system -l name=kata-deploy --tail=100 +kubectl describe pod -n agent-sandbox-system -l sandbox=kata +``` + +Remove the pool, the template, and the chart: + +```bash +kubectl delete sandboxwarmpool kata-pool -n agent-sandbox-system +kubectl delete sandboxtemplate kata-sandbox-template -n agent-sandbox-system +helm uninstall kata-deploy -n kube-system +``` + +`kata-deploy` runs a cleanup hook on uninstall that removes the Kata files and the containerd configuration from each node. + +To also remove the Firecracker thin pool from a node: + +```bash +sudo systemctl disable --now containerd-devmapper.service +sudo rm -f /etc/systemd/system/containerd-devmapper.service /usr/local/bin/containerd-devmapper-setup.sh +sudo dmsetup remove containerd-thinpool +sudo rm -rf /var/lib/containerd/devmapper +# remove the "kata devmapper snapshotter (managed)" block from /etc/containerd/config.toml, then: +sudo systemctl restart containerd +``` + +OpenShell, which creates sandboxes through the same controller, is a separate guide: [OpenShell](openshell.md). + +## Re-run + +| Operation | What happens | +|---|---| +| `agent_sandbox_enabled: true` on a running stack | The playbook is idempotent. Manifests are re-applied with `kubectl apply` | +| Namespace already exists | Ansible creates it with `state: present` | +| Controller already running | Kubernetes applies the manifests. It does not create a second controller | +| Re-run | `./toolkit_manager.sh install agent-toolkit` applies the sandbox again. Running components stay | + +To move to a new `agent_sandbox_version`, set the pin in `config.agent-toolkit.yaml` and re-run `install`, or [tear the stack down](../deployment/decommission.md) and install again. See [Upgrading](#upgrading). + +## Upgrading + +The version is pinned by `agent_sandbox_version` (default `v1.0.10`). Re-running `install` re-applies the manifests for that pin. + +From an older pin (for example v0.5.0) to **v1.0.10**: + +1. Back up existing resources: + + ```bash + kubectl get sandboxes,sandboxclaims,sandboxtemplates,sandboxwarmpools -A -o yaml > backup.yaml + ``` + +2. Set `agent_sandbox_version: "v1.0.10"` in `env/local/config.agent-toolkit.yaml` (or leave the default) and run `./toolkit_manager.sh install agent-toolkit`. +3. Upgrade the SDK: `pip install --upgrade k8s-agent-sandbox==1.0.10`. +4. Drop any client that relied on a static `ROUTER_AUTH_TOKEN`. The router now requires a Kubernetes service-account Bearer token (TokenReview). +5. Keep custom resources on `apiVersion: extensions.agents.x-k8s.io/v1beta1`. + +For later versions, raise the pin, re-run `install`, and upgrade the SDK to match. + +## Troubleshooting + +| Symptom | Check | +|---|---| +| Pods not starting | `kubectl get pods -n agent-sandbox-system`, then `kubectl describe pod -n agent-sandbox-system ` | +| Controller errors | `kubectl logs -n agent-sandbox-system -l app.kubernetes.io/name=agent-sandbox` | +| Router errors | `kubectl logs -n agent-sandbox-system -l app=sandbox-router` | +| Image pull errors | Test registry access: `kubectl run test --rm -it --restart=Never --image=registry.k8s.io/agent-sandbox/python-runtime-sandbox:v1.0.10 -- echo "success"`. For air-gapped clusters, mirror the images and set `agent_sandbox_router_image` and `agent_sandbox_python_runtime_image`. | +| SDK cannot connect | `kubectl get svc -n agent-sandbox-system sandbox-router-svc`, the `/healthz` check in [Verify](#3-verify), and `kubectl get networkpolicy -n agent-sandbox-system`. Router data-plane calls need a service-account Bearer token (TokenReview). | + +## Next steps + +- [Backend connection reference](backend-connections.md#agent-sandbox): in-cluster URL +- [Configuration](../configuration/configuration.md) and [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md) +- [Meet the Agent Toolkit](../overview/meet.md#toolkit-components) +- Upstream: [agent-sandbox docs](https://agent-sandbox.sigs.k8s.io/docs/), [v1.0.10 release notes](https://github.com/kubernetes-sigs/agent-sandbox/releases/tag/v1.0.10), [SDK README](https://github.com/kubernetes-sigs/agent-sandbox/tree/v1.0.10/clients/python/agentic-sandbox-client), [PyPI: k8s-agent-sandbox](https://pypi.org/project/k8s-agent-sandbox/1.0.10/) diff --git a/docs/reference/backend-connections.md b/docs/reference/backend-connections.md new file mode 100644 index 00000000..c6457704 --- /dev/null +++ b/docs/reference/backend-connections.md @@ -0,0 +1,158 @@ +# Backend connection reference + +[← Docs index](../README.md) + +Your **application** calls the public gateway at `https://litellm.`. **Agents running inside the cluster** also need Redis, pgvector, and the sandbox. Those are ClusterIP services: they are not published on the public URL. Read passwords from Kubernetes secrets; do not hardcode them. + +All of these come up with `install agent-toolkit` unless a section says otherwise. + +## LiteLLM (API gateway) + +Present when `auth_type: litellm_vkey`. This is what browsers and `curl` hit from outside the cluster. + +| | | +|---|---| +| **Namespace** | `litellm` | +| **In-cluster** | `http://litellm.litellm.svc.cluster.local:4000` | +| **External** | `https://litellm.` | +| **Master key** | Secret `litellm-master-key`, key `master_key` | + +```bash +kubectl get secret litellm-master-key -n litellm \ + -o jsonpath='{.data.master_key}' | base64 -d +``` + +## Model inference + +Models are served behind the AI gateway as well as LiteLLM. + +| Access | URL | +|---|---| +| **In-cluster** | `http://ai-gateway.envoy-gateway-system.svc.cluster.local/llm-inference//v1` | +| **External** | `https://litellm./v1` | + +## Redis (short-term memory) + + +Redis Stack with RediSearch. A password is required (the chart will not render without one). The Service is ClusterIP only: do not change it to NodePort. + +| | | +|---|---| +| **Namespace** | `redis` | +| **Service** | `redis-stack-server.redis.svc.cluster.local:6379` | +| **URL shape** | `redis://default:@redis-stack-server.redis.svc.cluster.local:6379` | +| **Secret** | `redis-stack-server-credentials` | + +```bash +# Full URL (preferred) +kubectl get secret redis-stack-server-credentials -n redis \ + -o jsonpath='{.data.REDIS_URL}' | base64 -d + +kubectl exec -n redis redis-stack-server-0 -- sh -c \ + 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning ping' +``` + +The username `default` is required. `redis://:@...` fails with `WRONGPASS` on Redis 6+. + +Redis with no password would let any client that can reach the port read session data and run Lua and JavaScript through RedisGears. The chart refuses to render without a password. + +Leave the Service as ClusterIP. NodePort or LoadBalancer would publish Redis on every node IP in the range 30000–32767. From outside the cluster, use `kubectl port-forward`. + +Redis runs in the ambient mesh. Namespaces in the mesh can reach it. Plaintext clients from outside the mesh are refused. + +Password rotation is not automated in this release. Re-running `install` skips Redis once the release exists, so a new value in YAML does not change the live password. + +## Agent sandbox + +Isolated pods for agent-generated code. Full guide: [Agent sandbox](agent-sandbox.md). + +| | | +|---|---| +| **Namespace** | `agent-sandbox-system` | +| **Router** | `sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080` | +| **Version** | `v1.0.10` | +| **CRDs** | `sandboxes`, `sandboxtemplates`, `sandboxwarmpools` (`v1beta1`) | +| **SDK** | `pip install k8s-agent-sandbox` | +| **Default template** | `python-sandbox-template` | + +```bash +kubectl port-forward -n agent-sandbox-system svc/sandbox-router-svc 8080:8080 +curl -s http://localhost:8080/healthz +# {"status":"ok"} +``` + +## PostgreSQL + pgvector (long-term memory) + +| | | +|---|---| +| **Namespace** | `pgvector` | +| **Host** | `pgvector.pgvector.svc.cluster.local:5432` | +| **Database / user** | `agentdb` / `agentuser` | +| **Secret** | `pgvector-credentials` (key `DATABASE_URL`) | + +```bash +kubectl get secret pgvector-credentials -n pgvector \ + -o jsonpath='{.data.DATABASE_URL}' | base64 -d +# postgresql://agentuser:@pgvector.pgvector.svc.cluster.local:5432/agentdb + +kubectl exec -n pgvector pgvector-0 -- \ + psql -U agentuser -d agentdb \ + -c "SELECT extname, extversion FROM pg_extension WHERE extname='vector';" +# extname | extversion +# vector | 0.8.0 +``` + +## KubeRay (optional) + +Only if `kuberay_enabled: true`. Guide: [KubeRay](kuberay.md). + +| | | +|---|---| +| **Namespace** | `ray-system` | +| **Ray Client** | `ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001` | +| **Dashboard** | `http://ray-cluster-head-svc.ray-system.svc.cluster.local:8265` | + +```bash +kubectl get pods -n ray-system +kubectl port-forward svc/ray-cluster-head-svc 8265:8265 -n ray-system +``` + +## OpenShell (optional) + + +Off unless `openshell_enabled: true`. That also needs `agent_sandbox_enabled: true`. Full guide: [OpenShell](openshell.md). + +| | | +|---|---| +| **Gateway namespace** | `openshell-system` | +| **Gateway service** | `openshell.openshell-system.svc.cluster.local:8080` (gRPC, mTLS) | +| **Sandbox namespace** | `openshell-sandboxes` | +| **Client mTLS bundle** | Secret `openshell-client-tls` in `openshell-system` | +| **CLI** | [OpenShell v0.1.6](https://github.com/NVIDIA/OpenShell/releases/tag/v0.1.6) | +| **Provider** | `genai-gateway` (`openshell sandbox create --provider genai-gateway`) | + +```bash +kubectl port-forward -n openshell-system svc/openshell 8080:8080 +``` + +The Service is ClusterIP. The port-forward is how an admin reaches it. + +## Langfuse (traces) + +Present when `auth_type: litellm_vkey`. + +| | | +|---|---| +| **Namespace** | `langfuse` | +| **In-cluster** | `http://langfuse-web.langfuse.svc.cluster.local:3000` | +| **External** | `https://langfuse.` | + +## Related pages + +- [Single-node quickstart](../getting-started/quickstart.md): first `curl` to the gateway +- [Agent sandbox](agent-sandbox.md): templates, Kata, and the SDK +- [OpenShell](openshell.md): policy-enforced sandboxes on the same controller +- [KubeRay](kuberay.md): Ray client and dashboard +- [Configuration](../configuration/configuration.md): YAML that turns these services on +- [Guardrails](../configuration/guardrails.md): screening on the same LiteLLM gateway +- [Glossary](glossary.md) diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md new file mode 100644 index 00000000..addd6019 --- /dev/null +++ b/docs/reference/glossary.md @@ -0,0 +1,104 @@ +# Glossary + +[← Docs index](../README.md) + +Terms that appear across these guides. If a page uses a word without explaining it, the definition is here. + +## Agent + +A program that calls a language model, then takes actions (run code, call a tool, search memory) and uses the result to continue. A single chat completion is not an agent; the loop of model → action → model is. See [Meet the Agent Toolkit](../overview/meet.md#what-is-an-agent-in-this-stack). + +## Agent toolkit + +This repository: Redis, pgvector, the sandbox, and optional OpenShell and KubeRay, plus the Kubernetes and model-serving pieces a full install brings up with them. [Toolkit Manager](../overview/meet.md#which-repository-to-start-from) clones it into `ext/` and installs, updates, and tears it down. Start at [Meet the Agent Toolkit](../overview/meet.md). + +## `llm_services_autodeploy_models` + +The list of catalog names deployed during `install`. It lives in `env/local/config.agent-toolkit.yaml`. The default is `["qwen2-5-coder-14b"]`. `[]` installs with no chat model. Other names are deployed with `./model-manager deploy `. The names must exist in `models.yaml`. See [Choose a model](../getting-started/quickstart.md#3-choose-a-model). + +## Base domain (`base_domain_name`) + +The domain you set in `env/local/global_config.yaml` (default `inteltoolkits.ai`). Services are names under it: `litellm.inteltoolkits.ai` for the gateway, `langfuse.inteltoolkits.ai` for traces, `keycloak.inteltoolkits.ai` for sign-in, `grafana.inteltoolkits.ai` for dashboards. Each name must match DNS or `/etc/hosts` and the TLS certificate. See [DNS and TLS](../getting-started/prerequisites.md#2-dns-and-tls). + +## Host + +The machine you install on: a physical server or a virtual machine with Intel® hardware. On the first-run path that is **one host**, and Kubernetes treats it as the only node. See the [single-node quickstart](../getting-started/quickstart.md). + +## Node + +A host that has joined the Kubernetes cluster. A single-node install is one host. A multi-node install is several hosts, split into a control-plane node and worker nodes. See [multi-node deployment](../deployment/multi-node.md). + +## Gateway + +The HTTPS front door your application calls. With `auth_type: litellm_vkey` that is LiteLLM (`https://litellm./v1`). It speaks the OpenAI API: `/v1/chat/completions`, `/v1/models`, and so on. Apps use a virtual key; the master key is for install smoke tests. URLs: [Backend connection reference](backend-connections.md). + +## Gated model + +A Hugging Face model you cannot download until you accept its license and pass a token. Llama and Gemma are gated. `qwen2-5-coder-14b` is not. Set `HF_TOKEN` in the environment before `install` if you need one. See [Hugging Face token](../configuration/configuration.md#hugging-face-token). + +## Idempotent install + +Running `./toolkit_manager.sh install agent-toolkit` again does not start from scratch. Use it to resume a failed run or to apply YAML changes: the toolkit roles (Redis, pgvector, sandbox, KubeRay, OpenShell) upgrade on every run. See the [single-node quickstart](../getting-started/quickstart.md#4-install). + +## Inference layer + +Model serving (vLLM) and the gateway. The toolkit needs it. You get it automatically when you `install agent-toolkit`. See [What install brings up](../overview/meet.md#what-install-brings-up). + +## Init + +`./toolkit_manager.sh init agent-toolkit` copies default YAML into `env/local/` (or `env//`). Edit those files. Do not edit the copies inside this git repo as your live config. See [Which repository to start from](../overview/meet.md#which-repository-to-start-from). + +## Langfuse + +The tracing UI. Every LLM call is stored: prompt, completion, tokens, latency, which model ran. Default URL: `https://langfuse.`. Connection notes: [Backend connection reference](backend-connections.md). + +## LiteLLM + +Open-source proxy that presents many model backends as one OpenAI-compatible API. In this stack it is the gateway and the place where routers and guardrails register. See [Routing](../configuration/routing.md) and [Guardrails](../configuration/guardrails.md). + +## Master key + +The LiteLLM admin token. Stored in the Kubernetes secret `litellm-master-key` in namespace `litellm`. Use it for the install smoke test and to create virtual keys. Do not put it in application code or in git. How to read it: [Backend connection reference](backend-connections.md) and [FAQ: Where is the API key?](../faq-and-troubleshooting/frequently-asked-questions.md#api-key). + +## Virtual key + +A per-application LiteLLM API key created from the master key. Put this in agent code, not the master key. How to create one: [Access the model](https://github.com/intel/toolkit-manager/blob/main/docs/getting-started/deploy-models.md#access-the-model) and [Build your first agent](../getting-started/first-agent.md). + +## pgvector + +A PostgreSQL extension that stores embedding vectors next to ordinary rows. Used here as long-term agent memory and for RAG. URL: [Backend connection reference](backend-connections.md). Related product: [Intel® Chatbot Toolkit](https://swcatalog.intel.com/developer/docs/enterprise-rag). + +## Platform layer + +Kubernetes, storage, mesh, identity, Prometheus / Grafana. Installed first. You need it before inference or the toolkit can run. See [What install brings up](../overview/meet.md#what-install-brings-up). + +## Component + +One piece of the stack (gateway, memory, sandbox, and so on) with a default you can run immediately and replace later. See [Toolkit components](../overview/meet.md#toolkit-components). + +## RAG (Retrieval-Augmented Generation) + +Look up relevant text from a store (here: pgvector), then put it in the prompt so the model answers from your data. This toolkit provides pgvector. The full product is separate: [Intel® Chatbot Toolkit](https://swcatalog.intel.com/developer/docs/enterprise-rag). + +## Toolkit Manager + +Toolkit Manager installs, updates, and tears down Intel® Agent Toolkit. Clone [that repository](https://github.com/intel/toolkit-manager) and run commands from its root. `init agent-toolkit` clones this repository under `ext/`. See [Which repository to start from](../overview/meet.md#which-repository-to-start-from). + +## Sandbox + +A short-lived Kubernetes pod where the agent runs code. Isolated filesystem and network. Default template is a Python runtime. Guide: [Agent sandbox](agent-sandbox.md). URL: [Backend connection reference](backend-connections.md#agent-sandbox). + +## Routing + +Optional. The application calls a virtual model name; the stack selects which deployed model serves the request. Not required for the first chat completion. See [Routing](../configuration/routing.md) and the [hybrid router](../configuration/hybrid-router.md). + +## vLLM + +The engine that loads the model and serves tokens. It runs on Intel® hardware in this stack. You do not call vLLM directly; you call the gateway. See [Backend connection reference](backend-connections.md). + +## Related pages + +- [Docs index](../README.md) +- [Meet the Agent Toolkit](../overview/meet.md) +- [FAQ](../faq-and-troubleshooting/frequently-asked-questions.md) +- [Configuration](../configuration/configuration.md) diff --git a/docs/reference/kuberay.md b/docs/reference/kuberay.md new file mode 100644 index 00000000..ca9eb686 --- /dev/null +++ b/docs/reference/kuberay.md @@ -0,0 +1,244 @@ +# KubeRay + +[← Docs index](../README.md) + +KubeRay runs [Ray](https://www.ray.io/) inside the cluster: the KubeRay operator plus one Ray cluster with a head pod and autoscaled worker pods. Use it when an agent must distribute Python tasks, run actors, or scale workers on demand. It is off by default and not required for a first chat request. + +Toolkit Manager installs two components when KubeRay is enabled: + +1. **KubeRay operator**: a Kubernetes controller that manages `RayCluster` custom resources. Installed from the upstream `kuberay/kuberay-operator` Helm chart. +2. **RayCluster**: a head pod (coordinator) and worker pods (task executors), deployed from this repository's `charts/kuberay` chart and reconciled by the operator. + +## How it works + +``` + ┌──────────────────────────────────────┐ + │ ray-system namespace │ + │ │ + Agent / client │ kuberay-operator │ + ─────────────► │ watches RayCluster CR │ + ray://... │ │ │ + │ ▼ │ + │ ray-cluster-head-svc (:10001) │ + │ │ │ + │ │ schedules tasks │ + │ ▼ │ + │ worker pods (default-worker group) │ + └──────────────────────────────────────┘ +``` + +- The head pod starts with `num-cpus=0`, so Ray schedules no user tasks on it. All work runs on workers. +- In-tree autoscaling is on. The Ray autoscaler adds or removes workers between `minReplicas` and `maxReplicas` based on pending tasks. +- Ray pods tolerate the control-plane taints, so they can run on control-plane nodes. + +| Resource | Kind | Namespace | +|---|---|---| +| `kuberay-operator` | Helm release and Deployment | `ray-system` | +| `rayclusters.ray.io` | CRD (cluster-scoped, installed by the operator chart) | — | +| `ray-cluster` | Helm release and RayCluster | `ray-system` | +| `ray-cluster-head-svc` | Service (ClusterIP) | `ray-system` | +| Head pod | Pod (`ray.io/node-type=head`) | `ray-system` | +| Worker pods | Pods (`ray.io/node-type=worker`), autoscaled | `ray-system` | + +## Settings + +All keys are flat and live in `env/local/config.agent-toolkit.yaml`. The defaults come from `roles/kuberay/defaults/main.yaml`. Add only the keys you want to change. + +| Field | Default | What it means | +|---|---|---| +| `kuberay_enabled` | `false` | Install KubeRay on the next `install`. | +| `kuberay_namespace` | `ray-system` | Namespace for the operator and the Ray cluster. The addresses on this page assume the default. | +| `kuberay_operator_version` | `1.3.0` | Version of the upstream `kuberay-operator` chart. | +| `kuberay_release_name` | `ray-cluster` | Helm release and RayCluster name. The head Service is `-head-svc`. | +| `kuberay_ray_image` | `rayproject/ray:2.40.0-py312` | Image for head and workers. Clients must use the same Ray version and Python minor version. | +| `kuberay_worker_replicas` | `2` | Initial worker count. | +| `kuberay_worker_min_replicas` | `1` | Autoscaler floor. | +| `kuberay_worker_max_replicas` | `4` | Autoscaler ceiling. | +| `kuberay_worker_cpu_request` / `_limit` | `500m` / `2` | CPU per worker. | +| `kuberay_worker_memory_request` / `_limit` | `2Gi` / `4Gi` | Memory per worker. | +| `kuberay_head_cpu_request` / `_limit` | `500m` / `2` | CPU for the head pod. Passed through to the chart. | +| `kuberay_head_memory_request` / `_limit` | `2Gi` / `4Gi` | Memory for the head pod. Passed through to the chart. | +| `kuberay_dashboard_enabled` | `true` | Publish the Ray Dashboard on the gateway at `https://ray./`. | +| `kuberay_dashboard_hostname` | `ray.` | Dashboard hostname. Add it to DNS or `/etc/hosts`. | +| `kuberay_dashboard_basic_auth` | `true` | Protect the gateway route with Secret `ray-dashboard-auth` (user `ray`). | + +Example with the defaults written out: + +```yaml +# env/local/config.agent-toolkit.yaml +kuberay_enabled: true +kuberay_ray_image: rayproject/ray:2.40.0-py312 +kuberay_worker_replicas: 2 +kuberay_worker_min_replicas: 1 +kuberay_worker_max_replicas: 4 +kuberay_worker_cpu_request: "500m" +kuberay_worker_cpu_limit: "2" +kuberay_worker_memory_request: "2Gi" +kuberay_worker_memory_limit: "4Gi" +kuberay_head_cpu_request: "500m" +kuberay_head_cpu_limit: "2" +kuberay_head_memory_request: "2Gi" +kuberay_head_memory_limit: "4Gi" +kuberay_dashboard_enabled: true +``` + +Worker sizing profiles: + +| Profile | CPU request | CPU limit | Memory request | Memory limit | +|---|---|---|---|---| +| Light (development, one node) | `500m` | `2` | `1Gi` | `2Gi` | +| Medium (default) | `500m` | `2` | `2Gi` | `4Gi` | +| Heavy (multi-node, batch) | `2` | `8` | `8Gi` | `16Gi` | + +Limitations of the current role: + +- **`rayVersion`:** the RayCluster's `rayVersion` comes from the chart's `appVersion` (`2.40.0`). Changing `kuberay_ray_image` does not change it. +- **Re-runs:** `install` runs `helm upgrade --install` for the operator and the RayCluster. A **failed** prior release is removed first, then reinstalled. To force a clean chart apply after a bad state, [remove KubeRay](#6-remove-kuberay) and install again. + +## 1. Enable KubeRay + +Set the flag, plus any settings from the table, before the first `install` that enables KubeRay: + +```yaml +# env/local/config.agent-toolkit.yaml +kuberay_enabled: true +``` + +From the Toolkit Manager directory: + +```bash +./toolkit_manager.sh install agent-toolkit +``` + +For KubeRay, the installer: + +1. Creates the `ray-system` namespace. +2. Adds the `kuberay` Helm repository and installs the operator. +3. Deploys the RayCluster from `charts/kuberay`. +4. Waits until the head pod is `Running`. + +If the install stops, rerun the same command to resume. + +## 2. Verify + +```bash +# Operator, head, and worker pods should be Running +kubectl get pods -n ray-system + +# RayCluster status +kubectl get raycluster -n ray-system + +# Cluster status from inside the head pod +kubectl exec -n ray-system -it \ + $(kubectl get pod -n ray-system -l ray.io/node-type=head -o name) -- ray status + +# Ray Dashboard at http://localhost:8265 +kubectl port-forward svc/ray-cluster-head-svc 8265:8265 -n ray-system + +# Or the gateway host. User ray. Password: +kubectl get secret ray-dashboard-auth -n ray-system -o jsonpath='{.data.password}' | base64 -d; echo +# https://ray./ +``` + +Expect one `kuberay-operator` pod, one head pod, and `kuberay_worker_replicas` worker pods (2 by default). + +In-cluster addresses. They work from a pod whose namespace is labelled `istio.io/dataplane-mode=ambient`: + +| Endpoint | Address | +|---|---| +| Ray Client API | `ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001` | +| Ray Dashboard | `http://ray-cluster-head-svc.ray-system.svc.cluster.local:8265` | +| GCS (internal) | `ray-cluster-head-svc.ray-system.svc.cluster.local:6379` | + +From outside the cluster, open `https://ray./` (user `ray`, password in Secret `ray-dashboard-auth`) or use `kubectl port-forward`. Add `ray.` to `/etc/hosts` the same way as `litellm.`. See [Prerequisites](../getting-started/prerequisites.md). + +## 3. Connect a Python client + +Install the Ray version that matches the cluster image (`2.40.0` by default), on the same Python minor version (`py312` means Python 3.12). A mismatch causes connection errors. + +```bash +pip install "ray[default]==2.40.0" +``` + +From a pod in the cluster: + +```python +import ray + +ray.init("ray://ray-cluster-head-svc.ray-system.svc.cluster.local:10001") + +@ray.remote +def hello(): + return "Hello from Ray worker!" + +print(ray.get(hello.remote())) # Hello from Ray worker! +``` + +From outside the cluster, forward the client port first, then connect to `localhost`: + +```bash +kubectl port-forward svc/ray-cluster-head-svc 10001:10001 -n ray-system & +``` + +```python +import ray +ray.init("ray://localhost:10001") +``` + +## 4. Scale workers + +### Change the live cluster + +The autoscaler manages the worker count, so set its bounds rather than the replica count. This example keeps between 5 and 8 workers: + +```bash +kubectl patch raycluster ray-cluster -n ray-system --type json -p '[ + {"op":"replace","path":"/spec/workerGroupSpecs/0/maxReplicas","value":8}, + {"op":"replace","path":"/spec/workerGroupSpecs/0/minReplicas","value":5} +]' +``` + +`kubectl scale` does not work on a RayCluster. The change lasts until the RayCluster is redeployed. + +### Change the configuration + +To keep a new size across reinstalls, set it in `env/local/config.agent-toolkit.yaml`: + +```yaml +kuberay_worker_replicas: 5 +kuberay_worker_max_replicas: 8 +``` + +Re-running `install` skips KubeRay once it is installed. To apply the values, [remove KubeRay](#6-remove-kuberay), then run `./toolkit_manager.sh install agent-toolkit`. + +## 5. Upgrade Ray + +1. Choose a tag from [Ray on Docker Hub](https://hub.docker.com/r/rayproject/ray/tags). +2. Set it in `env/local/config.agent-toolkit.yaml`: + + ```yaml + kuberay_ray_image: rayproject/ray:2.41.0-py312 + ``` + +3. If the new Ray version needs a newer operator, set `kuberay_operator_version` as well. +4. [Remove KubeRay](#6-remove-kuberay), then run `./toolkit_manager.sh install agent-toolkit`. The installer does not upgrade existing Helm releases in place. +5. Update clients to the same version, for example `pip install "ray[default]==2.41.0"` on Python 3.12. + +## 6. Remove KubeRay + +```bash +helm uninstall ray-cluster -n ray-system # RayCluster +helm uninstall kuberay-operator -n ray-system # operator +kubectl delete namespace ray-system # remaining resources +``` + +Helm does not delete CRDs, so `rayclusters.ray.io` and the other `ray.io` CRDs stay in the cluster. They are reused on the next install. + +To keep later installs from adding KubeRay again, set `kuberay_enabled: false`. + +## Next steps + +- [Configuration](../configuration/configuration.md#configagent-toolkityaml): `kuberay_enabled` and the other toolkit flags +- [Backend connection reference](backend-connections.md#kuberay-optional): in-cluster URLs +- [Single-node quickstart](../getting-started/quickstart.md): leave KubeRay off for the first request +- [Troubleshooting](../faq-and-troubleshooting/troubleshooting.md) diff --git a/docs/reference/openshell.md b/docs/reference/openshell.md new file mode 100644 index 00000000..be2593e1 --- /dev/null +++ b/docs/reference/openshell.md @@ -0,0 +1,540 @@ +# OpenShell + +[← Docs index](../README.md) + +[NVIDIA OpenShell](https://github.com/NVIDIA/OpenShell) adds a policy layer on top of the [agent sandbox](agent-sandbox.md). Its gateway creates sandboxes as `agents.x-k8s.io` Sandbox custom resources. A supervisor inside every sandbox enforces: + +- Egress default-deny, with per-host and per-binary allow rules, and HTTP method and path policy +- Filesystem restrictions (Landlock, where the node kernel provides it) and seccomp +- Credential isolation: the sandbox sees a placeholder. The supervisor injects the real credential on requests to the allowed endpoint + +The install registers LiteLLM as an OpenShell provider named `genai-gateway`. Agents in OpenShell sandboxes call models through LiteLLM with a budgeted virtual key. That key never enters the sandbox. + +OpenShell is off by default (`openshell_enabled: false`). It needs `agent_sandbox_enabled: true`. + +## Supported configuration + +| Component | Version | +|---|---| +| OpenShell Helm chart and images | `0.1.6` (`oci://ghcr.io/nvidia/openshell/helm-chart`) | +| OpenShell CLI | `v0.1.6` GitHub release | +| Agent sandbox | `v1.0.10` (`agent_sandbox_enabled: true`) | +| Model proxy | LiteLLM when `auth_type: litellm_vkey`. The provider step is skipped when LiteLLM is absent | +| User authentication | Single-admin mode. The gateway is ClusterIP. Kubernetes RBAC gates access | +| CNI | A CNI that enforces `NetworkPolicy` (Calico does) | + +### Upgrading from OpenShell 0.0.x + +OpenShell 0.1.0 changed the install. Before you run this deployment against an existing 0.0.x installation, follow the upstream [0.1.0 upgrade guide](https://docs.nvidia.com/openshell/v0.1.6/upgrade/0-1-0). Back up the gateway database and the credential-encryption material. Match the gateway, driver, supervisor, CLI, and SDK versions. Remove and recreate existing sandboxes. Preserve or re-import provider profiles and credentials. Changing the version pin alone does not migrate a 0.0.x install. + +## Architecture + +Two components in this page are called a gateway: + +- **OpenShell gateway.** The OpenShell control plane. It creates and deletes sandboxes and stores policies and provider credentials. It does not proxy model traffic. +- **LiteLLM.** The toolkit's model proxy (`auth_type: litellm_vkey`). OpenShell does not deploy a second one. Sandboxes reach models only through LiteLLM. + +An agent is any program you run inside a sandbox. OpenShell does not ship an agent. The supervisor is the OpenShell process in the same pod. It enforces the policy. + +The install brings the platform up once. Each run then gets its own sandbox, created with `openshell sandbox create` (or the gateway API) and removed with `sandbox delete`. + +``` +Admin / CI / orchestrator + │ openshell CLI or API over kubectl port-forward (mTLS client cert) + ▼ +OpenShell gateway (StatefulSet openshell-0, openshell-system) + │ 1. creates Sandbox CR ▲ 3. supervisor fetches policy and + ▼ │ provider credentials (mTLS) +Agent Sandbox controller ── 2. creates pod ──┐ +(agent_sandbox_enabled) ▼ +┌─ sandbox pod default-- (openshell-sandboxes) ─────────┐ +│ agent process (your code) ──► OpenShell supervisor │ +│ egress / L7 policy, Landlock│ +│ placeholder → real key │ +└──────────────────────────────────────┬──────────────────────┘ + │ 4. allowed traffic only + ┌────────────────────────────┴──────────────────┐ + ▼ ▼ +LiteLLM (:4000) hosts allowed by the sandbox + virtual key → model backends policy (via the corporate proxy) +``` + +## How OpenShell connects to the toolkit + +### Reused components + +| Component | Used for | Changed | +|---|---|---| +| Kubernetes cluster | Gateway and sandbox pods | No | +| Agent sandbox controller `v1.0.10` | Turns OpenShell `Sandbox` resources into pods | No | +| LiteLLM (`auth_type: litellm_vkey`) | The only path from a sandbox to models | One additional virtual key | +| Model backends behind LiteLLM | Reached through LiteLLM only | No | +| Toolkit Manager (`config.agent-toolkit.yaml`, `./toolkit_manager.sh`) | Installs and re-runs OpenShell | New `openshell_enabled` switch | +| Proxy settings (`https_proxy`, `no_proxy`) | Sandbox egress is chained through the corporate proxy | No | +| CNI (Calico) | Enforces the sandbox NetworkPolicy | No | + +OpenShell does not use the agent-sandbox router, `SandboxTemplate`, `WarmPool`, or the `k8s-agent-sandbox` SDK. It creates `Sandbox` resources directly, so both ways of running sandboxes share the same controller. For the Fluent Bit limitation on legacy 0.0.116 deployments, see [Legacy 0.0.116 limitations](#legacy-00116-limitations). + +### Added by OpenShell + +| Component | Kind | Role | +|---|---|---| +| OpenShell gateway | StatefulSet + Service `openshell:8080` (mTLS) | Sandbox lifecycle API, policy and credential store | +| Supervisor | Process in every sandbox pod | Egress and HTTP enforcement, Landlock, seccomp, credential injection | +| `openshell` CLI | Binary on the admin host | Administration. The playbook uses it to register the provider | +| Provider `genai-gateway` (profile `eat-genai-gateway`) | Gateway record | LiteLLM host and port, bearer credential, allowed binaries | +| NetworkPolicy `eat-openshell-sandbox-pods` | Added by the toolkit | Pod-level network limits under the supervisor | + +### Interfaces + +| # | From | To | Interface | Configured by | +|---|---|---|---|---| +| 1 | Admin / CI | OpenShell gateway | gRPC over mTLS through `kubectl port-forward` (secret `openshell-client-tls`) | Chart. See [Verification](#verification) | +| 2 | OpenShell gateway | Kubernetes API | Creates `agents.x-k8s.io/v1beta1` `Sandbox` resources in `openshell-sandboxes` | Chart RBAC | +| 3 | Agent sandbox controller | Kubernetes API | Reconciles the resource into a pod | Toolkit, unchanged | +| 4 | Supervisor | OpenShell gateway | gRPC over mTLS: policy, credentials, events | Playbook copies the client TLS secret into the sandbox namespace | +| 5 | Agent | Supervisor | All pod egress passes through the supervisor | OpenShell | +| 6 | Supervisor | LiteLLM `:4000` | OpenAI-compatible HTTP. `Authorization: Bearer ` is rewritten to the virtual key | Provider profile. `providers_v2_enabled=true` (playbook) | +| 7 | Playbook | LiteLLM admin API | `kubectl exec` into the LiteLLM pod, `POST /key/generate` with the in-pod master key, then Secret `openshell-genai-key` | Playbook | +| 8 | LiteLLM | Model backends | Unchanged. The key's allowed models and budget apply | Toolkit, unchanged | +| 9 | Supervisor | External hosts | Only hosts in the sandbox policy, through the corporate proxy | `--policy` per sandbox. Proxy from `global_config.yaml` | + +### Where credentials live + +| Credential | Location | Visible inside a sandbox | +|---|---|---| +| LiteLLM master key | LiteLLM pod only | No | +| Virtual key `openshell-sandboxes` | Secret `openshell-genai-key` and the OpenShell gateway | No. The sandbox sees a placeholder | +| Client certificate (`openshell-client-tls`) | `openshell-system` and `openshell-sandboxes` | Mounted for the supervisor. It grants gateway admin, so restrict `pods/exec` | + +## Deployed components + +| Component | Kind | Namespace | Notes | +|---|---|---|---| +| `openshell` | StatefulSet + Service (ClusterIP :8080, mTLS) | `openshell-system` | Upstream Helm chart with `charts/openshell/values.yaml` | +| `openshell-client-tls` | Secret | `openshell-system`, `openshell-sandboxes` | Client mTLS bundle. Copied into the sandbox namespace | +| `openshell-genai-key` | Secret | `openshell-system` | LiteLLM virtual key minted inside the LiteLLM pod | +| `eat-genai-gateway` | Provider profile | gateway | LiteLLM endpoint, bearer credential, allowed binaries | +| `genai-gateway` | Provider | gateway | Attach with `--provider genai-gateway` | +| `eat-openshell-sandbox-pods` | NetworkPolicy | `openshell-sandboxes` | Pod-level limits for sandbox pods | + +## Configuration + +In `env/local/config.agent-toolkit.yaml`: + +```yaml +agent_sandbox_enabled: true +openshell_enabled: true +``` + +`openshell_enabled: true` requires `agent_sandbox_enabled: true` in the same run, or agent-sandbox CRDs already on the cluster. Otherwise the deployment exits before it installs anything. + +When OpenShell is on, `config.agent-toolkit.yaml` also sets `litellm_allow_pod_network: true` (templated from `openshell_enabled`). Sandboxes sit outside the Istio mesh, so LiteLLM must admit API calls from the pod network on its service port; sandboxes still use the minted virtual key. On a bring-your-own cluster, set `kubernetes_cluster_cidr` in `global_config.yaml` to that cluster’s pod CIDR. Add any ambient-labelled agent namespace to `litellm_allowed_namespaces` (defaults already include the gateway, LiteLLM, agent-sandbox, and KubeRay namespaces). + +Resume mode, which would skip OpenShell when the release is already `deployed` at the current pins, is not available in this release. Re-run `./toolkit_manager.sh install agent-toolkit` to apply a change. + +### Version pins + +```yaml +openshell_chart_version: "0.1.6" +openshell_image_tag: "0.1.6" +openshell_release_tag: "v0.1.6" +``` + +### Settings + +| Variable | Default | Purpose | +|---|---|---| +| `openshell_release_name` | `openshell` | Helm release and gateway Service name | +| `openshell_namespace` | `openshell-system` | Gateway namespace. Holds provider credentials | +| `openshell_sandbox_namespace` | `openshell-sandboxes` | Sandbox pods | +| `openshell_allow_unauthenticated_clusterip_only` | `false` | Set `true` to accept single-admin mode. This setting is not available in this release | +| `openshell_oidc_issuer` / `openshell_oidc_audience` | `""` / `openshell-cli` | OIDC user authentication, as an alternative to single-admin mode | +| `openshell_genai_provider_enabled` | `true` | Register the LiteLLM provider | +| `openshell_genai_key_alias` | `openshell-sandboxes` | LiteLLM virtual key alias, used for spend tracking | +| `openshell_genai_key_models` | `[]` | Models the key may use. Empty means all | +| `openshell_genai_key_max_budget` | `50` | LiteLLM budget for the key | +| `openshell_cli_dir` | `""` | Where the playbook keeps the CLI. Empty means `~/.cache/eat/openshell-cli-` (mode `0700`) | +| `openshell_workspace_storage_class` | `""` | StorageClass for sandbox workspace volumes. Empty means `local-path` when the cluster has it, otherwise the default class. Multi-node NFS clusters get a non-default `local-path` class for this. Seeding a workspace on NFS takes about 16 minutes | +| `openshell_sandbox_network_policy` | `true` | Apply `eat-openshell-sandbox-pods` | +| `openshell_upstream_proxy_cidrs` | RFC 1918 ranges | Where the corporate proxy may live (proxy port only) | +| `openshell_sandbox_egress_cidrs` | `[]` | Extra private CIDRs that sandbox policies may target | +| `openshell_sandbox_dns_cidrs` | `[]` | Extra resolvers reachable on port `53`. Empty means auto-detect NodeLocal DNSCache | + +The corporate proxy (`https_proxy` and `no_proxy` from `global_config.yaml`) is passed to the gateway, which chains sandbox egress through it. + +### Authentication + +OpenShell on Kubernetes authenticates users with OIDC. mTLS covers transport and supervisors. Choose one mode: + +- **Single-admin.** Leave `openshell_oidc_issuer` empty (the default). The gateway stays ClusterIP. Only users who can `kubectl port-forward` in `openshell-system` and read `openshell-client-tls` can reach it. +- **OIDC.** Set `openshell_oidc_issuer` (for example a Keycloak realm URL served over HTTPS). This mode is not yet validated with the toolkit. + +## Install + +```bash +# env/local/config.agent-toolkit.yaml +# agent_sandbox_enabled: true +# openshell_enabled: true +# openshell_oidc_issuer: "" # empty = single-admin via kubectl port-forward + +./toolkit_manager.sh install agent-toolkit +``` + +The `openshell` role runs four task groups: + +| Task group | Action | +|---|---| +| 1 | Prerequisites: cluster connectivity, an explicit auth mode, and the agent-sandbox `v1beta1` API | +| 2 | Namespaces, Helm install, client TLS copy into the sandbox namespace, sandbox NetworkPolicy, gateway rollout | +| 3 | LiteLLM provider: mint the virtual key, register the profile and provider through a temporary port-forward, then remove the CLI credentials | +| 4 | Summary | + +Re-running is safe. The virtual key is minted once. The provider profile is updated in place (running sandboxes pick up changes). An existing provider is kept. + +The `openshell-deploy-state` fingerprint, which would skip OpenShell on a later install while pins and settings match, is not available in this release. Edit the file and re-run `./toolkit_manager.sh install agent-toolkit` with `openshell_enabled: true`. A failed or interrupted run is retried the same way. + +## Verification + +```bash +kubectl get pods -n openshell-system +# NAME READY STATUS RESTARTS +# openshell-0 1/1 Running 0 + +kubectl get secret openshell-genai-key -n openshell-system +kubectl get networkpolicy -n openshell-sandboxes +``` + +### Connect the CLI + +Install the CLI from the [v0.1.6 release](https://github.com/NVIDIA/OpenShell/releases/tag/v0.1.6), then: + +```bash +kubectl port-forward -n openshell-system svc/openshell 8080:8080 & +export NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost + +MTLS=${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/eat/mtls +mkdir -p "$MTLS" && chmod 700 "$MTLS" +for k in ca.crt tls.crt tls.key; do + kubectl get secret openshell-client-tls -n openshell-system \ + -o jsonpath="{.data.${k//./\\.}}" | base64 -d > "$MTLS/$k" +done +chmod 600 "$MTLS"/* + +openshell gateway add https://127.0.0.1:8080 --local --name eat +openshell provider list +# NAME TYPE CREDENTIAL_KEYS CONFIG_KEYS +# genai-gateway eat-genai-gateway 1 0 +``` + +The client certificate grants full control of the gateway. Keep it on the control plane. + +Connection values are also in the [backend connection reference](backend-connections.md#openshell). + +### Run a sandbox that calls LiteLLM + +```bash +openshell sandbox create --name demo --provider genai-gateway --detach \ + --env OPENAI_BASE_URL=http://litellm.litellm.svc.cluster.local:4000/v1 + +openshell sandbox exec -n demo --no-tty -- sh -c 'echo $OPENAI_API_KEY' +# openshell:resolve:env:..._OPENAI_API_KEY <- placeholder, not the key + +openshell sandbox exec -n demo --no-tty -- sh -c \ + 'curl -s $OPENAI_BASE_URL/models -H "Authorization: Bearer $OPENAI_API_KEY"' +# {"data":[{"id":"", ...}]} <- key injected by the supervisor + +openshell sandbox exec -n demo --no-tty -- \ + curl -s -m 10 -o /dev/null -w '%{http_code}\n' https://example.com +# 000 <- denied: not allowed by any policy + +openshell logs demo --source sandbox | grep DENIED +openshell sandbox delete demo +``` + +Without `--from`, sandboxes use the OpenShell community base image. Pass `--from ` for your own agent image, and `--policy ` to allow additional endpoints. The policy schema is in the [OpenShell policy reference](https://github.com/NVIDIA/OpenShell/blob/v0.1.6/docs/reference/policy-schema.mdx). + +## Run OpenCode in a sandbox + +[OpenCode](https://opencode.ai) is preinstalled in the community sandbox image. It runs inside the sandbox and reaches the model only through the `genai-gateway` provider. The LiteLLM key stays outside the sandbox, and every other outbound connection stays denied. + +Pick a `MODEL` from the `/models` list above that can make tool calls. + +### 1. Create the sandbox and write an OpenCode config + +```bash +MODEL= + +# Deny-all network policy: the sandbox's only egress is the genai-gateway provider. +# The community image's default policy lets python and pip reach PyPI. +# Filesystem and Landlock are applied at startup, so pass this file to `sandbox create`. +# `policy set` cannot change it later. +cat > /tmp/opencode-policy.yaml <<'YAML' +version: 1 +filesystem_policy: + include_workdir: true + read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log] + read_write: [/sandbox, /tmp, /dev/null] +landlock: + compatibility: best_effort +network_policies: {} +YAML + +openshell sandbox create --name opencode --provider genai-gateway --policy /tmp/opencode-policy.yaml --detach \ + --env OPENAI_BASE_URL=http://litellm.litellm.svc.cluster.local:4000/v1 + +openshell sandbox exec -n opencode --no-tty -- sh -c 'mkdir -p ~/.config/opencode && cat > ~/.config/opencode/opencode.json' < + +openshell sandbox get agent-demo +# Phase: Ready +``` + +Use a model id returned by `GET /v1/models`. + +### 4. Run the agent + +```bash +openshell sandbox exec -n agent-demo --no-tty -- python3 /sandbox/agent.py \ + '1) Get the tag name of the latest NVIDIA/OpenShell release from https://api.github.com/repos/NVIDIA/OpenShell/releases/latest. + 2) POST the tag name to https://httpbin.org/post. + 3) Create a gist: curl -s -o /dev/null -w "%{http_code}" -X POST https://api.github.com/gists -d "{}". + Then summarize which steps worked.' +``` + +The model chooses the exact commands. A run looks like this: + +``` +$ curl -s https://api.github.com/repos/NVIDIA/OpenShell/releases/latest | grep -o '"tag_name": "[^"]*"' | cut -d'"' -f4 +exit=0 +v0.1.6 + +$ curl -s -X POST https://httpbin.org/post -H "Content-Type: application/json" -d "{\"tag_name\": \"v0.1.6\"}" +exit=56 + +$ curl -s -o /dev/null -w "%{http_code}" -X POST https://api.github.com/gists -d "{}" +exit=0 +403 + +[final] Step 1: completed ... Step 2: failed due to network/access restrictions ... Step 3: returned 403 ... +``` + +| Agent action | Result | Enforced by | +|---|---|---| +| Chat completions to LiteLLM | Allowed. Spend is recorded on the `openshell-sandboxes` key | Provider, credential injection | +| `GET api.github.com/repos/...` | Allowed | `github_api` policy, `read-only` access | +| `POST httpbin.org/post` | Blocked (`curl` exit 56) | Egress default-deny | +| `POST api.github.com/gists` | Blocked (HTTP 403) | HTTP rule: `POST` is outside `read-only` | +| `echo $OPENAI_API_KEY` | Placeholder only | Credential isolation | + +### 5. Check the policy decisions + +The model may guess why a step failed. The sandbox log records the decision: + +```bash +openshell logs agent-demo --source sandbox | grep DENIED +# ... NET:OPEN [MED] DENIED /usr/bin/curl(426) -> httpbin.org:443 [policy:- engine:opa] +# [reason:endpoint httpbin.org:443 is not allowed by any policy] +# ... HTTP:POST [MED] DENIED POST http://api.github.com:443/gists [policy:github_api engine:l7] +# [reason:L7_REQUEST deny POST api.github.com:443/gists reason=POST /gists not permitted by policy] +``` + +### 6. Clean up + +```bash +openshell sandbox delete agent-demo +``` + +## Sandbox NetworkPolicy + +The toolkit applies `eat-openshell-sandbox-pods` under the OpenShell egress policy. It selects sandbox pods that do not have `openshell.ai/boundary-role`, so the split supervisor and workload pods used by newer charts keep the chart's stricter policies. + +- **Ingress:** only from `openshell-system` +- **Egress:** kube-dns, port `53` on the NodeLocal DNSCache address (auto-detected from the `nodelocaldns` DaemonSet, or `openshell_sandbox_dns_cidrs`), `openshell-system`, LiteLLM on port `4000`, the proxy port on `openshell_upstream_proxy_cidrs`, `openshell_sandbox_egress_cidrs`, and public addresses. Private and link-local ranges are excluded from that public set. + +## Legacy 0.0.116 limitations + +These notes apply to deployments still running OpenShell 0.0.116. The toolkit default is 0.1.6. + +- A credential placeholder copied into a request body fails the request. If an agent pastes `env` output into its model context, the supervisor rejects the request with `credential_injection_failed`. Redact `openshell:resolve:env:*` from tool output before sending it to the model. +- Sandbox pod logs show warnings only. Policy decisions are written to a file inside the pod. Read them with `openshell logs `. Fluent Bit does not collect them. +- `kubectl exec` into a sandbox pod bypasses the sandbox policy. Restrict `pods/exec` in `openshell-sandboxes` with Kubernetes RBAC. +- One release name per cluster. The chart creates a cluster-scoped ClusterRole named after the release (`openshell-node-reader` for release `openshell`). A second install with the same release name in another namespace fails with a Helm ownership error. Set `openshell_release_name` to a different value. +- NetworkPolicy enforcement depends on the CNI. Some CNIs (kindnet, for example) do not block traffic from a pod to its own node, such as the API server on a single-node cluster. + +## Removal + +There is no per-component uninstall command. Set `openshell_enabled: false` in `config.agent-toolkit.yaml` so a later run does not reinstall it, then run these steps on the control plane. They use the default names. If you changed the names in `config.agent-toolkit.yaml`, use yours. + +```bash +# 1. Delete the sandboxes (CLI connected; see Verification) +openshell sandbox list +openshell sandbox delete + +# 2. Uninstall the gateway, then delete both namespaces. +# helm uninstall keeps the gateway database PVC and the credential-encryption key Secret. +# Deleting the namespaces removes them, with the Secrets and the NetworkPolicy. +helm uninstall openshell -n openshell-system --wait +kubectl delete namespace openshell-sandboxes openshell-system + +# 3. Revoke the LiteLLM virtual key (runs in the LiteLLM pod, which holds the master key) +kubectl exec -n litellm deploy/litellm -c litellm -- python -c ' +import os, urllib.request +req = urllib.request.Request("http://127.0.0.1:4000/key/delete", + b"{\"key_aliases\": [\"openshell-sandboxes\"]}", + {"Authorization": "Bearer " + os.environ["PROXY_MASTER_KEY"], "Content-Type": "application/json"}) +print(urllib.request.urlopen(req).read().decode())' + +# 4. On the admin host, gateway remove keeps the client certificate files +openshell gateway remove eat +rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/eat" ~/.cache/eat/openshell-cli-v0.1.6 +``` + +## Troubleshooting + +```bash +kubectl get pods -n openshell-system +kubectl logs -n openshell-system statefulset/openshell +kubectl get sandbox,pods -n openshell-sandboxes +openshell logs --source sandbox +``` + +| Symptom | What to do | +|---|---| +| `openshell \| Check Agent Sandbox API is served (agent_sandbox)` fails | Set `agent_sandbox_enabled: true` and install again in the same run | +| `OpenShell on Kubernetes authenticates users via OIDC only` | Set an auth mode in `config.agent-toolkit.yaml` | +| LLM call returns `policy_denied` | The calling binary is missing from the provider profile `binaries` list in `charts/openshell/genai-gateway-provider.yaml`. Edit it and re-run `./toolkit_manager.sh install agent-toolkit` with `openshell_enabled: true` | +| `transport error` / `Connection reset by peer`, or `--upload` fails with `ssh tar extract exited with status 255` | `kubectl port-forward` dropped a stream. Retry the command. For a failed upload, re-run `openshell sandbox upload `. Restart the port-forward if it exited | +| CLI hangs | Include `127.0.0.1` in `NO_PROXY`, so the CLI does not send gateway traffic through a proxy | +| Sandbox fails with `Policy fetch failed ... failed to connect to OpenShell server` | Sandbox DNS is blocked. `kubectl get netpol eat-openshell-sandbox-pods -n openshell-sandboxes -o yaml` should list the resolver from the pod's `/etc/resolv.conf` (NodeLocal DNSCache `169.254.25.10` on Kubespray). If the cluster uses another DNS cache, set `openshell_sandbox_dns_cidrs` and install again | + +## Configuration files + +| File | Role | +|---|---| +| `roles/openshell/tasks/install.yaml` | The role | +| `roles/openshell/defaults/main.yaml` | Defaults. Override them in `env/local/config.agent-toolkit.yaml` | +| `charts/openshell/values.yaml` | Helm overlay | +| `charts/openshell/genai-gateway-provider.yaml` | Provider profile | + +## Next steps + +- [Agent sandbox](agent-sandbox.md): the controller OpenShell uses, including [Kata](agent-sandbox.md#kata-containers) +- [Backend connection reference](backend-connections.md#openshell): gateway address and the port-forward +- [Configuration](../configuration/configuration.md): `openshell_enabled` +- [NVIDIA OpenShell](https://github.com/NVIDIA/OpenShell) and the [v0.1.6 release](https://github.com/NVIDIA/OpenShell/releases/tag/v0.1.6) diff --git a/docs/running-behind-proxy.md b/docs/running-behind-proxy.md deleted file mode 100644 index 260154bc..00000000 --- a/docs/running-behind-proxy.md +++ /dev/null @@ -1,28 +0,0 @@ -# Running behind a corporate proxy - -If you are working in a corporate environment where internet access is routed through a proxy, you need to configure the appropriate proxy settings for tools and scripts to work correctly. - -This is supported using proxy configuration through `env//global_config.yaml` file - ---- - -## Configuration Steps - -1. Open the configuration file: - - ```bash - env//global_config.yaml - ``` - -2. Add the following three environment variables with your proxy details: - - ```yaml - http_proxy: "http://:" - https_proxy: "http://:" - no_proxy: "localhost,127.0.0.1,..com,10.96.0.0/12,192.168.0.0/16,10.233.0.0/16,.svc,.svc.cluster.local" - ``` - - > **Note:** Make sure to include any internal domains or IPs in `no_proxy` that should bypass the proxy. `10.96.0.0/12` is the range for Kubernetes services using standard tools such as `kubeadm`. `192.168.0.0/16` are standard IPs for personal computers. `10.233.0.0/16` is a standard IP address for clusters deployed using Kubespray. - -To unset proxy from apt, please remove proxy configurations from below file -sudo nano /etc/apt/apt.conf diff --git a/docs/single-node-deployment.md b/docs/single-node-deployment.md deleted file mode 100644 index a1bd6ef1..00000000 --- a/docs/single-node-deployment.md +++ /dev/null @@ -1,486 +0,0 @@ -# Quick Start — Intel® Agent Toolkit -This guide provides step-by-step instructions on how to deploy the Intel® Agent Toolkit on a single node. - -## Table of Contents - -- [Step 1 — Base Stack](#step-1--base-stack) -- [Verify the Base Stack](#verify-the-base-stack) -- [Step 1b — Semantic Router](#step-1b--semantic-router-intelligent-query-routing) -- [Step 2 — Redis (Shared Memory Backend)](#step-2--redis-shared-memory-backend) -- [Step 2b — PostgreSQL + pgvector (Vector Store)](#step-2b--postgresql--pgvector-vector-store--long-term-memory) -- [Step 2c — Agent Sandbox (Sandboxed Code Execution)](#step-2c--agent-sandbox-sandboxed-code-execution) -- [Step 2d — OpenShell (Policy-Enforced Sandboxes)](#step-2d--openshell-policy-enforced-sandboxes) - ---- - -## Step 1 — Base Stack - -```bash -git clone -b release-2.0 https://github.com/intel/enterprise-ai-solutions.git -cd enterprise-ai-solutions -./es_auto_installer.sh configure -./es_auto_installer.sh init agent-toolkit # creates env/local/ (env name defaults to "local") -``` - -### 2. Edit `env/local/global_config.yaml` and `env/local/config.agent-toolkit.yaml` - -Open `env/local/global_config.yaml` and `env/local/config.agent-toolkit.yaml` and fill in your values: - -```yaml -# env/local/global_config.yaml -# Your base domain — this becomes the base URL for all services (e.g. litellm.) -base_domain_name: "example.com" - -# TLS certificate — self-signed by default - -# Kubernetes — provisioned by the installer by default; for a BYO cluster set: -# existing_kubernetes: /path/to/kubeconfig - -# Enable/disable stack components -observability_enabled: true - -# Proxy settings (optional, depending on network) -http_proxy: "" -https_proxy: "" -no_proxy: "" -``` - -```yaml -# env/local/config.agent-toolkit.yaml -# Model(s) to deploy — select the model(s) from the model list (ex: qwen2-5-coder-14b), separated by commas -llm_services_autodeploy_models: ["qwen2-5-coder-14b"] - -# API access: LiteLLM virtual keys (set by init agent-toolkit); "jwt" for Keycloak JWT -auth_type: "litellm_vkey" - -# Enable/disable stack components -# deploy_agenticai_plugin (Flowise agentic AI plugin): not available in this release -redis_stack_enabled: true # standalone Redis Stack in its own namespace -pgvector_enabled: true # optional: PostgreSQL 16 + pgvector — shared vector store and long-term memory backend -kuberay_enabled: false # optional: KubeRay operator — enables Ray distributed computing inside the cluster -agent_sandbox_enabled: true # optional: Agent Sandbox controller — isolated pod environments for safe code execution -openshell_enabled: false # optional: NVIDIA OpenShell policy-enforced sandboxes (requires agent_sandbox_enabled: true) -``` - ->*Note:* For proxy settings, see [running-behind-proxy.md](./running-behind-proxy.md). - -### 3. Choose your model - -Set `llm_services_autodeploy_models` in `config.agent-toolkit.yaml` to one value from the table below: - -**CPU models** - -| # | Value to set in `llm_services_autodeploy_models` | Model | -|---|---|---| -| `21` | `qwen3-coder-30b` | Qwen/Qwen3-Coder-30B-A3B-Instruct | -| `22` | `qwen2-5-coder-14b` | Qwen/Qwen2.5-Coder-14B-Instruct *(default — used by the Coding Agent)* | -| `23` | `bge-base-en` | BAAI/bge-base-en-v1.5 *(text embedding)* | -| `24` | `bge-reranker` | BAAI/bge-reranker-base *(reranking)* | -| `25` | `qwen3-30b-a3b` | Qwen/Qwen3-30B-A3B-Instruct-2507 | -| `26` | `gemma-4-26b` | google/gemma-4-26B-A4B-it | -| `27` | `llama-3-1-8b` | meta-llama/Llama-3.1-8B-Instruct | -| `28` | `llama-3-1-8b-specdec` | meta-llama/Llama-3.1-8B-Instruct *(with speculative decoding)* | -| `29` | `qwen3-coder-30b-specdec` | Qwen/Qwen3-Coder-30B-A3B-Instruct *(with speculative decoding)* | -| `30` | `qwen3-6-35b-a3b` | Qwen/Qwen3.6-35B-A3B | - -> **Memory:** a node needs the `memory:` requests of its models (in `env/local/models.yaml`) plus about 17 GiB for the rest of the stack, and 16 GiB more for Qwen3Guard while the content-safety guardrail is on. The default install requests about 131 GiB (`qwen2-5-coder-14b` 96 GiB, Qwen3Guard 16 GiB, router 2 GiB, the rest 17 GiB), so it does not fit a 128 GB node: choose a 64 GiB model there (`qwen2-5-coder-7b`, `llama-3-1-8b`). `qwen3-coder-30b` requests 160 GiB. - -> **Note:** `meta-llama/Llama-3.1-8B-Instruct` does not support parallel tool calling. Only sequential tool calls are supported with this model. - -> **Note:** For how per-model CPU/memory sizing and vLLM flags are configured under the -> hood, or to add a new model, see [Xeon (CPU) vLLM Model Configuration](xeon-model-configuration.md). - -**Speculative Decoding:** - -Models that support speculative decoding are available with a `-specdec` suffix (e.g. `qwen3-coder-30b-specdec`, `qwen2-5-coder-14b-specdec`, `llama-3-1-8b-specdec`). This technique uses a smaller draft model to generate candidate tokens quickly, which are then verified by the larger target model in parallel — reducing time-to-first-token and overall generation latency while preserving output quality. - -These models are registered in LiteLLM with a `-specdec` suffix to distinguish them from their non-speculative counterparts (e.g. `qwen3-coder-30b-specdec`). The draft model is automatically configured during deployment. - -To deploy a speculative decoding variant, set the `-specdec` model in `config.agent-toolkit.yaml`: - -```yaml -llm_services_autodeploy_models: ["qwen3-coder-30b-specdec"] -``` - -Multiple models can be deployed together using a comma-separated list: `llm_services_autodeploy_models: ["qwen3-coder-30b", "bge-base-en"]` - -### 4. Run the deployment - -```bash -export HF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxx # HuggingFace token (required to pull gated models) -./es_auto_installer.sh install agent-toolkit -``` - -**Estimated time:** 20–40 minutes on a fresh node. - -Output is also written to `env/local/logs/install-agent-toolkit-.log`. - ---- - -## Verify the Base Stack - -After Step 1 completes, verify all pods are healthy before proceeding to Step 2: - -```bash -# The installer writes the cluster's kubeconfig into the env -export KUBECONFIG=$(pwd)/env/local/kubeconfig.yaml - -# All pods should be Running -# (the vLLM pod may take an additional 10-15 min to pull the model weights) -kubectl get pods -A - -# Retrieve the LiteLLM master key -export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm -o jsonpath='{.data.master_key}' | base64 -d) - -# (Optional) If behind a corporate proxy, update no_proxy to prevent the request from being intercepted by the proxy (replace with your base_domain_name) -export no_proxy="${no_proxy},litellm.,langfuse." - -# Gateway IP: map litellm. (and the other service names) to it in /etc/hosts -kubectl get svc -n envoy-gateway-system -l gateway.envoyproxy.io/owning-gateway-name=eg-gateway \ - -o jsonpath='{.items[0].status.loadBalancer.ingress[0].ip}' - -# Confirm the model API is responding (replace with your base_domain_name; -# TLS is self-signed by default, so use curl -k): -# First, list registered models to confirm the model name: -curl -k https://litellm./v1/models \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" - -# Then test chat completions (replace with your base_domain_name, then use the model name returned by /v1/models above): -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - -d '{"model": "qwen2-5-coder-14b", - "messages": [{"role":"user","content":"Write a Python hello world"}], - "max_tokens": 100}' -``` - -> The `LITELLM_MASTER_KEY` is stored in the `litellm-master-key` Secret (key `master_key`) in the `litellm` namespace. - ---- - -## Step 1b — Semantic Router (Intelligent Query Routing) - -Semantic routing automatically directs queries to the most appropriate model based on content analysis using embeddings. This allows you to route simple queries to faster/cheaper CPU models while directing complex tasks to larger CPU models. - -**Why Use Semantic Routing?** - -- **Cost optimization:** Route simple queries to efficient models, complex ones to powerful models -- **Latency reduction:** Fast models handle straightforward requests quickly -- **Intelligent dispatch:** Coding tasks → coding-specialized models, reasoning → larger models -- **Transparent routing:** Applications use a single model name (e.g., `hybrid-router`), routing happens server-side - -> **📚 For more information:** See the official [LiteLLM Auto Routing documentation](https://docs.litellm.ai/docs/proxy/auto_routing#litellm-proxy-server) - -### Prerequisites - -- Step 1 complete and base stack verified -- At least one model deployed (you'll add an embedding model for routing and a second model to route to) - -### 1. Deploy a Second Model and an Embedding Model - -The hybrid router spreads requests over the deployed chat models, so deploy a second one. **BAAI/bge-base-en-v1.5** (`bge-base-en`) is added as well, as the embedding model for your agents. - -A second larger model i.e. **Qwen/Qwen3-Coder-30B-A3B-Instruct** with better capabilities will also be deployed alongside your existing one. - -**Update `env/local/config.agent-toolkit.yaml` to include the embedding model and second model:** - -```yaml -llm_services_autodeploy_models: ["qwen2-5-coder-14b", "bge-base-en", "qwen3-coder-30b"] -``` - -**Deploy the model:** - -*Important:* With the NRI balloon policy, the default model (`cpu: auto`) takes the free physical cores of one NUMA node. When no NUMA node has enough free cores left, a further deploy stops with `NRI pre-flight failed: not enough physical cores`. To make room, set an explicit `cpu:` for each model in `env/local/models.yaml` (see [xeon-model-configuration.md](xeon-model-configuration.md)). For a sizing guide, refer to the Intel AI Performance Advisor for [cloud instances](https://xeonprocessoradvisor.intel.com/csp-ai-performance-advisor) and [on-prem servers](https://xeonprocessoradvisor.intel.com/on-prem-ai-performance-advisor). - -After updating `models.yaml`, undeploy the existing model first, then re-run the install so all 3 models are placed with the new sizes. - -```bash -kubectl get llminferenceservices,inferenceservices -n llm-inference # see list of vllm deployments -./model-manager undeploy # uninstall the existing vllm deployment -./es_auto_installer.sh install agent-toolkit -``` - -Restart the GenAI Gateway's Deployment: -```bash -kubectl rollout restart deployment litellm -n litellm -``` - -Follow the steps to [re-verify the base stack](#verify-the-base-stack) to ensure models can be accessed. - -### 2. Access the LiteLLM UI - -Open `https://litellm./ui` in your browser (the gateway IP must be in `/etc/hosts` for that name, as in the quick-start). Without the hosts entry, port-forward the LiteLLM Service and open `http://localhost:4000/ui`: - -```bash -kubectl port-forward -n litellm svc/litellm 4000:4000 -``` - -Login credentials: -- Username: default which is `admin` -- Password: the value of `LITELLM_MASTER_KEY` - -### 3. Configure Semantic Router via UI - -**Step 3a - Verify the Embedding Model:** - -The embedding model is automatically registered in LiteLLM when deployed via `es_auto_installer.sh`. Verify it's available: - -1. Navigate to: **Models+Endpoints** → **All Models** tab -2. Look for `bge-base-en` in the models list -3. Note the model name - you'll use it in the next step (typically `bge-base-en`) - -**Step 3b - The hybrid router:** - -This release creates the `hybrid-router` model at install (`hybrid_router_enabled: true`, the default), so there is no UI step. It sorts each request by complexity and sends it to one of the deployed chat models. Models deployed after the install join it when you re-run `./es_auto_installer.sh install agent-toolkit`. Tiers and model lists: [hybrid-router.md](hybrid-router.md). - -### 4. Verify Semantic Routing - -Test that queries are being routed correctly based on content: - -**Simple query (should route to smaller model - fast response):** - -```bash -export LITELLM_MASTER_KEY=$(kubectl get secret litellm-master-key -n litellm -o jsonpath='{.data.master_key}' | base64 -d) - -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - -d '{ - "model": "hybrid-router", - "messages": [{"role":"user","content":"What is a Python list?"}], - "max_tokens": 100 - }' -``` - -**Complex query (should route to more powerful model):** - -```bash -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \ - -d '{ - "model": "hybrid-router", - "messages": [{"role":"user","content":"How to code a program in Python that implements a distributed task queue with Redis backend"}], - "max_tokens": 200 - }' -``` - -**Check routing decisions in Langfuse:** - -Navigate to the Langfuse dashboard to see which model handled each request: - -``` -https://langfuse. -``` - -Login credentials: `kubectl get secret langfuse-secrets -n langfuse -o jsonpath='{.data.admin_email}' | base64 -d` and `... -o jsonpath='{.data.admin_password}' | base64 -d`; the project is `inference`. - -Go inside the `inference` project. Under **Tracing**, select the most recent `litellm_request`, scroll down to **Metadata** → **attributes**. Look at the `llm.model_name` field to confirm routing decisions. - -### How It Works - -Requests to `hybrid-router` are classified by complexity (simple, medium, complex, reasoning) and sent to a model of that tier; a bandit then picks among the models of a tier by observed cost and latency. Details and settings: [hybrid-router.md](hybrid-router.md). - ---- - -## Step 2 — Redis (Shared Memory Backend) - -Redis is the **common memory backend** for all agentic workloads in this stack — deploy it before any use-case agent (MCP agents, etc.). - -The `charts/redis-stack` chart deploys **Redis Stack** (includes RediSearch) into its own `redis` namespace as a single persistent instance shared across all agents. - -**Automated deployment (recommended):** - -By default, Redis should already be deployed. You can check by running `kubectl get pods -n redis`. If not, follow the instructions below to deploy it. - -Set `redis_stack_enabled: true` in `env/local/config.agent-toolkit.yaml`: -```yaml -redis_stack_enabled: true -``` - -Then re-run `es_auto_installer.sh`: -```bash -./es_auto_installer.sh install agent-toolkit -``` - -The deployment script generates the password into the `redis-stack-server-credentials` Kubernetes Secret and passes it to the chart, so no manual credential setup is needed. - -**Verify it is running:** - -```bash -kubectl get pods -n redis -# NAME READY STATUS RESTARTS AGE -# redis-stack-server-0 1/1 Running 0 60s - -# Quick connectivity test (a password is required) -kubectl exec -n redis redis-stack-server-0 -- sh -c \ - 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning ping' -# PONG -``` - -**Redis URL (in-cluster) — use this in all agents:** - -The full URL, including the password, is stored in a Kubernetes Secret. Read it from there rather than hardcoding credentials: - -```bash -kubectl get secret redis-stack-server-credentials -n redis \ - -o jsonpath='{.data.REDIS_URL}' | base64 -d -# redis://default:@redis-stack-server.redis.svc.cluster.local:6379 -``` - -> This URL is the single source of truth for all agent workloads connecting to Redis within the cluster. -> Note the `default:` username — Redis 6+ rejects the `redis://:@...` form with `WRONGPASS`. - -### Redis security notes - -- **Authentication is mandatory.** The chart fails to render if no password is supplied. Redis with `nopass` allows any client that can reach the port to read and modify all agent session data and to execute arbitrary Lua and JavaScript (via RedisGears) on the server. -- **The Service is `ClusterIP`**, reachable only from inside the cluster. Do not change it to `NodePort` or `LoadBalancer` — that publishes Redis on every node IP in the 30000-32767 range. If you need external access, use `kubectl port-forward` instead. -- **Mesh-only access.** Redis runs in the ambient mesh: namespaces in the mesh reach it, plaintext clients from outside are refused. -- **Password rotation** is not automated in this release. - ---- - -## Step 2b — PostgreSQL + pgvector (Vector Store & Long-Term Memory) - -PostgreSQL 16 with the **pgvector** extension gives every agentic workload a persistent, queryable vector store for long-term memory, RAG pipelines, semantic search, and structured state storage — all within the cluster. - -**When to enable:** -- Your agent needs long-term memory that survives pod/session restarts -- You are building RAG pipelines that store and retrieve embeddings -- Use cases require structured relational + vector data in the same store -- You want a production-grade alternative to in-memory vector stores - -By default, `pgvector` should already be deployed. You can check by running `kubectl get pods -n pgvector`. If not, follow the instructions below to deploy it. - -Enable it in `env/local/config.agent-toolkit.yaml`: -```yaml -pgvector_enabled: true -``` - -Then re-run the deploy script: -```bash -./es_auto_installer.sh install agent-toolkit -``` - -**What gets deployed:** - -| Resource | Detail | -|---|---| -| Namespace | `pgvector` | -| Image | `pgvector/pgvector:pg16` (PostgreSQL 16 + pgvector extension) | -| Service | `pgvector.pgvector.svc.cluster.local:5432` | -| Database | `agentdb` | -| User | `agentuser` | -| Credentials secret | `pgvector-credentials` in the `pgvector` namespace | - -**Verify it is running:** - -```bash -kubectl get pods -n pgvector -# NAME READY STATUS RESTARTS AGE -# pgvector-0 1/1 Running 0 60s - -# Confirm pgvector extension is active -kubectl exec -n pgvector pgvector-0 -- \ - psql -U agentuser -d agentdb \ - -c "SELECT extname, extversion FROM pg_extension WHERE extname='vector';" -# extname | extversion -# --------+----------- -# vector | 0.8.0 -``` - -**Retrieve the connection string from the cluster secret:** - -```bash -kubectl get secret pgvector-credentials -n pgvector \ - -o jsonpath='{.data.DATABASE_URL}' | base64 -d -# postgresql://agentuser:@pgvector.pgvector.svc.cluster.local:5432/agentdb -``` - -**In-cluster connection string (for use in agent workloads):** - -``` -postgresql://agentuser:@pgvector.pgvector.svc.cluster.local:5432/agentdb -``` - ---- - -## Step 2c — Agent Sandbox (Sandboxed Code Execution) - -Agent Sandbox provides **isolated, ephemeral Kubernetes pods** for safe code execution. -Every sandbox is a fully self-contained pod — the agent can run arbitrary code, install -packages, and write files without touching the host or other workloads. - -By default, Agent Sandbox should already be deployed. You can check by running `kubectl get pods -n agent-sandbox-system`. If not, follow the instructions below to deploy it. - -Enable it in `env/local/config.agent-toolkit.yaml`: -```yaml -agent_sandbox_enabled: true -``` - -Then re-run the deploy script: -```bash -./es_auto_installer.sh install agent-toolkit -``` - -**What gets deployed** (all in the `agent-sandbox-system` namespace): - -| Component | Description | -|---|---| -| `agent-sandbox-controller` | Kubernetes operator that manages Sandbox pod lifecycle | -| CRDs | `sandboxes`, `sandboxtemplates`, `sandboxclaims`, `sandboxwarmpools` | -| `sandbox-router` | HTTP proxy that routes SDK requests to sandbox pods | -| `python-sandbox-template` | Default SandboxTemplate using a locally-built Python runtime | - -**Verify:** - -```bash -kubectl get pods -n agent-sandbox-system -# NAME READY STATUS RESTARTS -# agent-sandbox-controller-xxx 1/1 Running 0 -# sandbox-router-xxx 1/1 Running 0 - -kubectl get sandboxtemplate -n agent-sandbox-system -# NAME AGE -# python-sandbox-template 1m -``` - -> **In-cluster router URL** (used by the in-cluster agent): -> `http://sandbox-router-svc.agent-sandbox-system.svc.cluster.local:8080` - -For the full guide — adding custom templates, WarmPools, and SDK usage — see -**[agent-sandbox.md](agent-sandbox.md)**. - ---- - -## Step 2d — OpenShell (Policy-Enforced Sandboxes) - -NVIDIA OpenShell runs on top of Agent Sandbox and enforces egress default-deny, L7 rules, -Landlock and credential isolation inside every sandbox. The GenAI Gateway is registered as a -provider: sandboxes see a placeholder key and the supervisor injects a dedicated LiteLLM -virtual key. - -```yaml -# env/local/config.agent-toolkit.yaml -agent_sandbox_enabled: true -openshell_enabled: true -``` - -Without `openshell_oidc_issuer`, OpenShell runs in single-admin mode (ClusterIP only, reached through `kubectl port-forward` with Kubernetes RBAC); no extra setting is needed. - -```bash -./es_auto_installer.sh install agent-toolkit -``` - -**Verify:** - -```bash -kubectl get pods -n openshell-system -# NAME READY STATUS RESTARTS -# openshell-0 1/1 Running 0 -``` - -For CLI setup, running a sandbox against the GenAI Gateway, and known limitations, see -**[openshell.md](openshell.md)**. - ---- diff --git a/docs/validate-stack.md b/docs/validate-stack.md deleted file mode 100644 index d7bf57ed..00000000 --- a/docs/validate-stack.md +++ /dev/null @@ -1,149 +0,0 @@ -# Stack Validation & Preflight Checks - -Pre-install node readiness and post-deploy health checks for the -Intel® Agent Toolkit. - ---- - -## Table of Contents - -- [Overview](#overview) -- [Preflight Check — Pre-Install](#preflight-check--pre-install) -- [Validate Stack — Post-Deploy](#validate-stack--post-deploy) -- [What validate checks](#what-validate-checks) -- [Troubleshooting](#troubleshooting) - ---- - -## Overview - -| Check | When | Command | Output | -|---|---|---|---| -| Preflight | At the start of `./es_auto_installer.sh install`; standalone at any time | `ext/enterprise.agent-toolkit/playbooks/preflight-check.yml` | Report in `env//logs/health-report-latest.{json,html,txt}`; the `.txt` summary is also printed | -| Validate | After the install | `./es_auto_installer.sh validate ` | Per-component checks in the run output; any failure stops the run with its reason | - -Components that are not enabled are skipped, not reported as failures. - ---- - -## Preflight Check — Pre-Install - -Checks node readiness on every host in the inventory. No result stops the install. The only change it makes is the Kubelet DNS setting (see [Troubleshooting](#preflight-fails-on-the-kubelet-dns-file)). - -| Status | Checks | Meaning | -|---|---|---| -| **FAIL** | Time sync, Kubelet DNS file, unfinished Kubernetes install, node connection, swap in use, root and containerd disk < 10% free, external DNS, gateway reachable | Fix these; they are also listed in the `PREFLIGHT WARNING` block | -| **WARN** | CPU governor not `performance`, THP=`always`, Hugging Face token invalid | Tuning or model access; the install works | -| **PENDING** | Node resource pressure before the cluster exists; Hugging Face token not set | Checked on a later run: after the install, or with `HF_TOKEN` exported | -| **OK** | Kernel and OS version, kubelet version (`not installed` before the cluster exists), NUMA topology | Informational, recorded in the report | - -Example, on a node with the CPU governor on `powersave`: - -```text - Network connectivity [ OK ] (reachable via ICMP ping ) - Platform health [ WARN ] governor=powersave freq=3343MHz max=3900MHz - WARNING: [platform-health] CPU governor on node1 - Hint: Set performance: cpupower frequency-set -g performance - RESULT: 2 layers — 1 PASSED, 1 WARNING -``` - -### Runs with the install - -In an env inited for `agent-toolkit`, `./es_auto_installer.sh install` runs the preflight first: on a new cluster before Kubespray, otherwise before the components. -Runs with `--only` skip it. To turn it off, set `node_preflight_enabled: false` in `env//config.agent-toolkit.yaml`. -The checks are capped at 5 minutes; past that the install continues. The run output is saved to `env//logs/preflight-check.log`. - -### Run standalone - -From the `enterprise-ai-solutions` checkout, after `init agent-toolkit`. For multi-node, list the nodes in `env//inventory/hosts.yaml` first ([Multi-Node Deployment, Step 1](multi-node-deployment.md#step-1--configure-hostsyaml)): - -```bash -export HF_TOKEN= # optional: also checks the token for gated models -.venv/bin/ansible-playbook -i env//inventory/hosts.yaml \ - ext/enterprise.agent-toolkit/playbooks/preflight-check.yml -``` - -Report: `env//logs/health-report-latest.json` and `.html`; a summary is printed at the end of the run. - ---- - -## Validate Stack — Post-Deploy - -`validate` runs the validate checks of every enabled component in the target and its dependencies; `--only` limits it to the target. -A healthy stack ends with `failed=0` in the run's recap. - -### Run all checks - -```bash -./es_auto_installer.sh validate agent-toolkit -``` - -### Run a single layer or component - -```bash -./es_auto_installer.sh validate platform --only -./es_auto_installer.sh validate inference --only -./es_auto_installer.sh validate litellm --only -``` - ---- - -## What validate checks - -| Layer | Component | Checks | -|---|---|---| -| Infrastructure | kubernetes | kubectl and kubeconfig, API server reachable, node readiness, server version | -| | storage (NFS, Ceph, Trident) | CSI driver and node plugin, StorageClass, exactly one default class; Ceph health and OSDs | -| | kata_containers | kata-deploy rollout, requested RuntimeClasses | -| Platform | cert-manager, MetalLB, Envoy Gateway | Releases, controllers ready, IP pool, GatewayClass and Gateway accepted, TLS secret | -| | Istio | istiod, ztunnel on every node, mesh-wide mTLS | -| | PostgreSQL, SeaweedFS | Database cluster ready, S3 gateway ready | -| | observability | Prometheus Operator, Grafana, Node Exporter, Loki, Tempo, OTel Collector | -| | NRI balloons, NFD | Policy and DaemonSet ready, CPU feature labels on nodes | -| | Keycloak (when enabled) | Operator and instances ready | -| Inference | KServe, model services | CRDs and controllers, serving runtimes, deployed models, CPU policy | -| | LiteLLM | Deployment ready, readiness endpoint, master key; a request through the content-safety guardrail and a chat request through LiteLLM | -| | Langfuse, vLLM Semantic Router | Web and worker deployments; router and dashboard routed | -| Agent toolkit | Redis Stack, pgvector | Pods, Redis PING and RediSearch, pgvector extension and credentials | -| | Agent Sandbox | Controller, router, CRDs, templates, warm pools (and the Kata template) | -| | OpenShell, KubeRay | Gateway ready; operator and head pod | - -Not in this release: burn tests, the proxy checks and a post-deploy report file. Node-level checks (time sync, disk, swap, CPU governor, THP, DNS, gateway) are in the [preflight](#preflight-check--pre-install). - ---- - -## Troubleshooting - -### Preflight fails on NTP sync - -Ensure `chronyd` or `systemd-timesyncd` is running and synchronized on all nodes: -```bash -.venv/bin/ansible -i env//inventory/hosts.yaml all -b -m shell -a "timedatectl status | grep synchronized" -``` - -### Preflight fails on the Kubelet DNS file - -On Ubuntu and Fedora, Kubespray points kubelet at `/run/systemd/resolve/resolv.conf`, which only exists while `systemd-resolved` runs; without it, Kubernetes cannot start. -When no node runs `systemd-resolved`, the preflight writes `kube_resolv_conf: "/etc/resolv.conf"` and `resolvconf_mode: "none"` to `env//kubespray_extra.yml` (reported as **Kubelet DNS setting**) and the install continues. -It reports FAIL when some nodes run `systemd-resolved` and others do not: one setting cannot serve both, so make the nodes the same, then re-run the install. -With the preflight off (`node_preflight_enabled: false`), write the two lines yourself on such hosts. - -### Preflight fails on an unfinished Kubernetes install - -An install that stopped during `kubeadm` leaves `/var/lib/kubelet/config.yaml` on the node. A plain re-run then skips `kubeadm init` and fails later (`secrets is forbidden` on `kubeadm token create`). Reset the nodes, then install again: -```bash -./es_auto_installer.sh teardown kubernetes -./es_auto_installer.sh install agent-toolkit -``` - -### Preflight fails on a node connection - -The installer's playbook runs on the installer machine and runs some steps for each node on that node (Kata setup, CPU pinning). A node with no `ansible_connection` gets those steps run on the installer machine instead, so they report and configure the wrong machine. Add `ansible_connection: ssh` to every node reached over SSH, and `ansible_connection: local` to the machine running the installer, in `env//inventory/hosts.yaml`, then re-run the install. - -### A model is still loading - -Large models can take 5-15 minutes to load. Re-run validation once they are Ready: -```bash -kubectl get llminferenceservices,inferenceservices -n llm-inference -./es_auto_installer.sh validate inference -``` diff --git a/docs/vllm-semantic-router.md b/docs/vllm-semantic-router.md deleted file mode 100644 index 98f416c5..00000000 --- a/docs/vllm-semantic-router.md +++ /dev/null @@ -1,382 +0,0 @@ -# vLLM Semantic Router - -vLLM Semantic Router is a signal-driven decision routing framework for -Mixture-of-Models deployments. It routes every request to the best model -across local, private, and frontier backends -- guided by cost, latency, -privacy, and safety constraints. - -For more information, see [vllm-semantic-router.com](https://vllm-semantic-router.com/). - ---- - -## Architecture - -``` -Client - | - | HTTPS (external) - v -LiteLLM GenAI Gateway - | - authenticates the request - | - model="vllm-sr/auto" triggers routing - | - starts Langfuse trace - v -vLLM Semantic Router - | - extracts semantic signals from the prompt - | - evaluates routing decisions - | - selects the best model - | - routes to the appropriate backend - v -Model Backend (local vLLM, Bedrock, OpenAI, etc.) - | - runs inference - | - returns response - v -Response flows back through the chain to the client -``` - -Observability is handled via OpenTelemetry. vLLM-SR emits traces that appear -in Langfuse alongside the LiteLLM traces, giving a complete view of routing -decisions and inference performance. - -> **Note:** not available in this release. - ---- - -## Getting Started - -### Prerequisites - -- The base stack must be deployed (Kubernetes, ingress, LiteLLM, at least one model) -- `vllm_sr_enabled: true` in `env//config.inference.yaml` - -### Deploy - -Run the standard deployment script: - -```bash -./es_auto_installer.sh install agent-toolkit -``` - -The script will: -1. Discover deployed model services in the cluster -2. Deploy the vLLM-SR Helm chart -3. Wait for all containers to become healthy -4. Register `vllm-sr/auto` as a model in LiteLLM - -### Verify - -Send a request through the routing layer: - -```bash -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{ - "model": "vllm-sr/auto", - "messages": [{"role": "user", "content": "write a hello world in python"}] - }' -``` - -You can also call a model directly (bypasses routing): - -```bash -curl -k https://litellm./v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{ - "model": "qwen2-5-coder-14b", - "messages": [{"role": "user", "content": "hello"}] - }' -``` - -### Access the Dashboard - -The dashboard is exposed via the gateway on its own host, `vllm-sr.`: - -``` -https://vllm-sr./ -``` - -For example: `https://vllm-sr.example.com/` - -The dashboard serves root paths (`/login`, `/api`, `/assets`, ...) and cannot -run under a sub-path, so it gets its own host instead of sharing `litellm.` -with the GenAI Gateway (LiteLLM) UI. The router API (`/v1/route`) is not published at the gateway in this release; send requests to the `vllm-sr/auto` model through LiteLLM instead. - -Prerequisites for the dashboard host: - -- **DNS:** `vllm-sr.` must resolve to the gateway (DNS record, or - `/etc/hosts` on the node and on every client machine). -- **TLS certificate:** the certificate must cover `vllm-sr.`, either - as a SAN entry (`DNS:vllm-sr.`) or via a parent-domain wildcard - (e.g. `*.`). See [Prerequisites](prerequisites.md). Existing - certificates without it must be regenerated. -- **Corporate proxy:** add `vllm-sr.` to the browser/OS proxy bypass - list, as for `litellm.`. - -Default credentials are generated at deploy time into the `vllm-sr-dashboard` Secret -(namespace `vllm-semantic-router-system`, keys `admin-email` / `admin-password`). - ---- - -## Request Flow - -1. Client sends `POST /v1/chat/completions` with `model: "vllm-sr/auto"` -2. LiteLLM authenticates the request, starts a Langfuse trace, and forwards - to vLLM-SR -3. vLLM-SR runs semantic signal classification on the prompt -4. The decision engine evaluates routing rules top-down by priority: - - `coding-route` (priority 10): matches coding-related prompts - - `reasoning-route` (priority 50): matches analytical prompts - - `default-route` (priority 100): catch-all -5. vLLM-SR routes the request to the selected backend -6. The response flows back to the client - -There is no infinite loop because LiteLLM treats `vllm-sr/auto` and the real -model names as separate routing entries. Only `vllm-sr/auto` goes to vLLM-SR; -real model names go directly to their respective backends. - ---- - -## Configuration - -### Routing Configuration - -The routing config is defined in `core/helm-charts/vllm-sr/router-config.yaml` -as a reference, and rendered into a ConfigMap via the Helm template at -`core/helm-charts/vllm-sr/templates/configmap.yaml`. - -Key sections: - -**Signals** define how prompts are classified: - -```yaml -routing: - signals: - embeddings: - - name: coding_tasks - threshold: 0.72 - candidates: - - "write code" - - "implement function" - - "debug this" -``` - -To add a new signal category, add another embedding entry with a name, -threshold (similarity score cutoff), and a list of candidate phrases that -represent that category. - -**Decisions** define routing rules evaluated top-down by priority: - -```yaml -routing: - decisions: - - name: coding-route - description: "Route coding tasks to coder model" - priority: 10 - rules: - operator: AND - conditions: - - type: embedding - name: coding_tasks - modelRefs: - - model: qwen2-5-coder-14b - use_reasoning: false -``` - -Lower priority number means higher precedence. The first matching decision wins. - -> **Note:** not available in this release. - -**Model backends** are the models the router can route to. In normal use they -are discovered automatically at deploy time (see -[Onboarding a New Model](#onboarding-a-new-model)), so you do not edit them by -hand. - -Each backend has this shape: - -```yaml -providers: - models: - - name: qwen2-5-coder-14b # short name used in decisions - provider_model_id: "qwen2-5-coder-14b" # the model the backend serves - backend_refs: - - name: "primary" - endpoint: "qwen2-5-coder-14b-kserve-workload-svc.llm-inference.svc.cluster.local:8000" # its endpoint - protocol: "http" - weight: 100 -``` - -- `name` — the short identifier referenced in `routing.decisions`. -- `provider_model_id` — the model id the backend actually serves. -- `endpoint` — the in-cluster endpoint, `host:port`. -- `protocol` — the API style; `http` for vLLM backends. - -### Helm Values - -All configuration is in `env//config.inference.yaml`. Key settings: - -| Value | Description | -|-------|-------------| -| `vllm_sr_image_tag` | vLLM-SR container version | -| `vllm_sr_dashboard_admin_email` | Dashboard login email (default `admin@`) | -| `vllm_sr_dashboard_secret` | Secret holding the dashboard login password (default `vllm-sr-dashboard`, generated at deploy time) | -| `vllm_sr_cache_backend` | Semantic cache: `memory` or `redis` | -| `routing.enableSemanticCache` | Enable/disable response caching — not available in this release | -| `routing.cacheThreshold` | Similarity above which a cached response is reused (default `0.92`) — not available in this release | -| `vllm_sr_default_model` | Backend **name** served when the router has no better choice. Default: the toolkit's default model (`qwen2-5-coder-14b`); the first routed model when that one is not routed | -| `routing.enableJailbreakDetection` | **Not yet wired** — not available in this release | -| `routing.enablePiiDetection` | **Not yet wired** — not available in this release | -| `observability.enabled` | Enable trace export to Langfuse — not available in this release | - -### Updating the Routing Config - -After editing the settings (or `vllm_sr_config_override`, the full routing config) in `env//config.inference.yaml`, redeploy with: - -```bash -./es_auto_installer.sh install agent-toolkit -``` - -Or update only vLLM-SR: - -```bash -./es_auto_installer.sh install vllm_sr --only -``` - -The pod restarts automatically when the ConfigMap changes. - ---- - -## Onboarding a New Model - -When you deploy a model through the toolkit with vLLM-SR enabled -(`vllm_sr_enabled: true`), the model is onboarded into routing automatically. There -is no separate registration step. - -During deployment, vLLM-SR discovers the model services running in the cluster, -adds each one as a routing backend, and rebuilds its routing config. The model -then shows up in the dashboard and becomes a candidate for routing. - -To add a model: - -1. Deploy the model through the toolkit (`llm_services_autodeploy_models` in - `env//config.agent-toolkit.yaml`, then `./es_auto_installer.sh install agent-toolkit`) - with `vllm_sr_enabled: true`. -2. That's it — the model is discovered and added to routing as part of the same - deployment. - -You can confirm the model is available in the dashboard: - -``` -https://vllm-sr./ -``` - -### How routing picks up the new model - -Once a model is a backend, it participates in routing as follows: - -- The **reasoning** and **default** routes consider every model, so a new model - is immediately eligible for general and reasoning traffic. -- The **coding** route considers models whose name identifies them as coder - models. A coding model joins this route when `coder` appears in its name. - -To route a new category of prompts (for example, math or legal), add a signal -and a matching decision as described in -[Routing Configuration](#routing-configuration). - -### Verify routing - -Send a prompt and check which model answered (the `model` field of the response): - -```bash -curl -k https://litellm./v1/chat/completions \ - -H "Authorization: Bearer " \ - -H "Content-Type: application/json" \ - -d '{"model": "vllm-sr/auto", "messages": [{"role": "user", "content": "write a python function to sort a list"}]}' \ - | jq -r .model -``` - -Clients keep calling `vllm-sr/auto` as before — the router dispatches to the new -model internally, so no client changes are needed. - ---- - -## LiteLLM Integration - -vLLM-SR is registered in LiteLLM as a model called `vllm-sr/auto`. This -registration happens automatically at the end of the deployment playbook. - -Clients choose between: -- `model: "vllm-sr/auto"` -- request goes through semantic routing -- `model: ""` -- request goes directly to that model - -Both paths go through LiteLLM for authentication and spend tracking. - ---- - -## Langfuse Integration - -vLLM-SR emits OpenTelemetry traces for every routed request. These appear -in Langfuse as nested spans alongside the LiteLLM traces. - -### What Langfuse Shows - -For each request routed through vLLM-SR, Langfuse displays: - -**From LiteLLM** (`service.name: litellm`): -- Input prompt and output response -- Token counts and cost -- Total latency - -**From vLLM-SR** (`service.name: vllm-semantic-router`): -- `semantic_router.signal.evaluation` -- which signals matched, confidence score -- `semantic_router.decision.evaluation` -- which route was selected, which model -- `semantic_router.upstream.request` -- backend call latency, HTTP status - -> **Note:** not available in this release. - -Together these give full visibility into why a model was selected and how -it performed. - ---- - -## Troubleshooting - -**Pod is not becoming Ready** - -Check which container is failing: - -```bash -kubectl get pods -n vllm-semantic-router-system -o jsonpath='{range .items[0].status.containerStatuses[*]}{.name}: {.ready}{"\n"}{end}' -``` - -Common causes: -- vllm-sr container: downloading encoder model (takes 1-2 minutes on first start) -- envoy container: increase file descriptor limits if you see "Too many open files" - -**Traces not appearing in Langfuse** - -Check the vLLM-SR container for export errors: - -```bash -kubectl logs -n vllm-sr -c vllm-sr | grep "traces export" -``` - -> **Note:** not available in this release. - -**LiteLLM returns "Connection error" for vllm-sr/auto** - -Verify vLLM-SR is reachable from the litellm namespace: - -```bash -kubectl exec -n litellm deploy/litellm -c litellm -- \ - python3 -c "import socket; s=socket.socket(); s.connect(('semantic-router.envoy-gateway-system.svc.cluster.local', 80)); print('OK')" -``` - -**Dashboard shows "Failed to read config"** - -Check the dashboard container logs: - -```bash -kubectl logs -n vllm-semantic-router-system deploy/semantic-router-dashboard -``` diff --git a/docs/xeon-model-configuration.md b/docs/xeon-model-configuration.md deleted file mode 100644 index 39e26a0c..00000000 --- a/docs/xeon-model-configuration.md +++ /dev/null @@ -1,156 +0,0 @@ -# Xeon (CPU) vLLM Model Configuration - -This guide covers the `modelConfigs` structure in -[`core/helm-charts/vllm/xeon-values.yaml`](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/helm-charts/vllm/xeon-values.yaml) — how -per-model tuning is defined for CPU/Xeon deployments, and how to add a new model to it. - -## How the lookup works - -Every `helm upgrade --install` sets `LLM_MODEL_ID` to the exact Hugging Face model ID -(e.g. `--set LLM_MODEL_ID="Qwen/Qwen3-Coder-30B-A3B-Instruct"`). The chart templates use -that string as a key into the `modelConfigs` map: - -```yaml -modelConfigs: - "Qwen/Qwen3-Coder-30B-A3B-Instruct": - optimal_cpu_cores: 64 - tensor_parallel_size: 4 - pipeline_parallel_size: 1 - configMapValues: { ... } - extraCmdArgs: [ ... ] -``` - -- **[`configmap.yaml`](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/helm-charts/vllm/templates/configmap.yaml)** copies the - matched entry's `configMapValues` into the pod's ConfigMap (env vars). -- **[`deployment.yaml`](https://github.com/intel/enterprise-agent-toolkit/blob/release-1.1.0/core/helm-charts/vllm/templates/deployment.yaml)** uses - `extraCmdArgs` for the vLLM CLI args, `optimal_cpu_cores` as the CPU request/limit - (or falls back to `optimal_balloon_config.workload_cpus` from the NRI balloon policy if - not defined), and `tensor_parallel_size`/`pipeline_parallel_size` for the parallelism flags. - -If `LLM_MODEL_ID` has **no matching key** in `modelConfigs`, every one of those lookups -silently falls through to **`defaultModelConfigs`** (bottom of the file) instead — a -generic, untuned config. This is a safety net, not a substitute for adding a real entry: -an unmatched model gets generic `VLLM_CPU_KVCACHE_SPACE`/CPU sizing/CLI args that may be -wrong for its architecture (missing tool-call parser, wrong chat template, etc). - -## CPU cores and memory limits (avoiding OOM) - -**CPU core allocation:** -- **If `cpu` is a number** in the model's `env//models.yaml` entry → use that value as the CPU request/limit -- **If `cpu: auto`** → under the NRI balloon policy, model-manager takes the free physical cores of one NUMA node per TP rank on the smallest schedulable node and uses that instead - -This lets smaller models (like Llama-8B with `tp=1`) use a full NUMA node's worth of cores instead of a hardcoded minimum. - -On a node with a single NUMA node (for example one 36-core socket), `cpu: auto` on the default model leaves no balloon cores for further models, and `model-manager deploy` stops with `NRI pre-flight failed: not enough physical cores`. To deploy more models there, set an explicit `cpu:` for the default model in `env//models.yaml`. - -When picking `cpu` for a new entry, keep it a multiple of -`--tensor-parallel-size` (vLLM shards evenly across TP ranks) and within a single socket's -core count — spanning multiple NUMA nodes is unsupported for CPU deployments and can crash -(`shm.cpp thread_num mismatch`) unless `tensor_parallel_size` is explicitly forced to `1`. - -Memory (`resources.requests.memory` / `resources.limits.memory` on the pod) is **not** -derived from anything in `modelConfigs` — it's calculated once per playbook run in -`deploy-inference-models.yml`, based on `tensor_parallel_size` alone, and applied to every -model deployed in that run: - -| `tensor_parallel_size` | Memory **request** | Memory **limit** | -|---|---|---| -| 1 | 128–200Gi (capped at the limit) | fixed at 200Gi | -| 2–3 | 128–256Gi (whatever the detected socket has, capped at 256Gi) | fixed at 400Gi | -| ≥ 4 | fixed at 256Gi, regardless of actual socket size | fixed at 400Gi | - -> **TP=1 limit:** a `tensor_parallel_size: 1` pod is capped at 200Gi so its memory stays on -> the single NUMA node its cores are pinned to (one node has about 252 GiB). A larger limit -> makes NRI widen `cpuset.mems` to neighbouring nodes, and vLLM then fails to bind cores -> (`core ids=[]`). A model whose weights + KV cache + overhead exceed 200Gi (roughly 60B+ -> parameters in BF16) is OOM-killed at TP=1, so give it a higher `tensor_parallel_size` -> (2 or 4). - -> **Note:** not available in this release. - -The limit is a hard cap enforced by the kernel — if a model's real footprint (weights + -`VLLM_CPU_KVCACHE_SPACE` + engine overhead) exceeds it, the pod gets OOM-killed no matter -how much physical memory the node has. When adding a new model — especially a large one at -`tensor_parallel_size >= 4` — check that its expected footprint fits under its `memory` -value before assuming the deployment will be stable; a model that needs more gets a larger -`memory` on its `env//models.yaml` entry (or `--memory` on `./model-manager deploy`). - -**Approximate footprint per model** (BF16 weights, `Base weights = total params × 2 bytes` -— use *total* params for MoE models, not active params, since every expert's weights sit -in memory regardless; `KV cache = tensor_parallel_size × VLLM_CPU_KVCACHE_SPACE`; runtime -+ IPC buffer is a rough fixed overhead that scales loosely with TP): - -| Model | TP | Base weights | Spec draft | KV cache | Runtime/IPC buffer | Approx. total | -|---|---|---|---|---|---|---| -| Llama-3.1-8B-Instruct | 1 | 16.8 GiB | — | 40 GiB (1×40) | 12 GiB | ~69 GiB | -| Llama-3.1-8B-Instruct-Specdec | 2 | 16.8 GiB | 2.6 GiB (1B) | 80 GiB (2×40) | 16 GiB | ~116 GiB | -| Qwen2.5-Coder-14B-Instruct | 4 | 30.8 GiB | — | 160 GiB (4×40) | 22 GiB | ~214 GiB | -| Qwen3-Coder-30B-A3B-Instruct | 4 | 64.0 GiB | — | 240 GiB (4×60) | 24 GiB | ~328 GiB | -| Qwen3-Coder-30B-A3B-Instruct-Specdec | 4 | 64.0 GiB | 1.3 GiB (0.6B) | 240 GiB (4×60) | 26 GiB | ~332 GiB | -| Qwen3-30B-A3B-Instruct-2507 | 4 | 64.0 GiB | — | 240 GiB (4×60) | 24 GiB | ~328 GiB | -| google/gemma-4-26B-A4B-it | 4 | 55.0 GiB | — | 160 GiB (4×40) | 22 GiB | ~238 GiB | -| Qwen3.6-35B-A3B | 4 | 73.5 GiB | — | 200 GiB (4×50) | 26 GiB | ~300 GiB | - -These are estimates, not guarantees — but note that several of them (Qwen3-Coder-30B-A3B, -Qwen3-30B-A3B, Qwen3.6-35B-A3B) already exceed the **256Gi** fixed request the playbook -gives every `tensor_parallel_size >= 4` model today; they only stay stable because the -**400Gi** limit still covers them and Burstable QoS lets the pod use more than its request -when the node has it free. There's no margin left for anything bigger at TP=4 without -raising that ceiling. - -> **Note:** not available in this release. - -## Adding a new model - -1. **Add an entry to `env//models.yaml`** with a `name` and the exact Hugging Face `model_id`. Keep the - `# Benchmarked: ...` or `# Estimated: ...` comment convention already used by the other - entries, noting the instance type and how `cpu`/`--tensor-parallel-size` - were derived. - -2. **Sizing fields:** - - `cpu` — CPU cores requested/limited per replica, or `auto`: the free physical cores of - one NUMA node per TP rank, based on detected NUMA topology. See - [CPU cores and memory limits](#cpu-cores-and-memory-limits-avoiding-oom) for details. - - `--tensor-parallel-size` in `args` (or `--tp N` on `./model-manager deploy`) — vLLM - parallelism. These are also - read by the Ansible pre-flight validator (`validate-cpu-requirements.sh`, via a - mirrored `model_benchmark_config.yml`), so treat this file as the source of truth for - sizing, not just the Helm chart. - - > **Note:** `tensor_parallel_size` is a ceiling — the playbook auto-selects TP=1, 2, - > or 4 based on detected NUMA topology (TP=8 isn't auto-selected today, even on - > hardware that could back it). A mismatch fails with `CreateContainerError: no - > balloon for annotation`. - - > **Note:** not available in this release. - -3. **`env`** — environment variables injected into the pod. Common knobs: - | Key | Meaning | - |---|---| - | `VLLM_CPU_KVCACHE_SPACE` | KV-cache size in GB reserved per replica — raise for longer contexts/more concurrent requests, at the cost of memory headroom | - | `VLLM_CPU_NUM_OF_RESERVED_CPU` | Cores held back from the vLLM workload (e.g. for a draft model under speculative decoding) | - | `VLLM_RPC_TIMEOUT`, `VLLM_ENGINE_ITERATION_TIMEOUT_S` | Internal vLLM timeouts, generally left at the defaults used by every other entry | - | `VLLM_ALLOW_LONG_MAX_MODEL_LEN` | Lets `--max-model-len` exceed the model's default trained context | - | `HF_HUB_DISABLE_XET`, `TRITON_CACHE_DIR`, `USER` | Boilerplate — copy as-is unless you know you need to change them | - | `HF_HOME` | Only set for large models where weights should persist on the PVC (`/data`) rather than the ephemeral `/tmp` emptyDir — see the `Qwen/Qwen3.6-35B-A3B` entry for why | - -4. **`args`** — the vLLM CLI flags. The most model-specific ones: - - `--tool-call-parser` must match the model family: `llama3_json` (Llama-3.x), - `hermes` (Qwen3 non-coder), `qwen3_xml` (Qwen3-Coder / Qwen2.5-Coder), `gemma4`. - - `chat_template_file` (vLLM `--chat-template`) — only needed if the model doesn't ship a template that already - produces the tool-call format its parser expects. Templates live in - `ext/enterprise.ai-inference/model_manager/chat-templates/`; add a new `.jinja` there if the model - needs one. - - `--trust-remote-code` — required for some custom model architectures (see the - Qwen3-Coder-30B and Qwen3.6-35B entries). - -5. **`draft_model_id`** (optional) — the draft model's Hugging Face repo, fetched to - `/mnt/models/draft`, plus `args` in dot notation: - `"--speculative-config.method", "draft_model", "--speculative-config.model", "/mnt/models/draft", "--speculative-config.num_speculative_tokens", "N"`. - Speculative decoding is a separate catalog entry (e.g. `qwen3-coder-30b-specdec`), so the - base entry stays deployed without speculative decoding. - -6. **Wire it into the deploy tooling.** The catalog entry is deployable end-to-end as is: - `./model-manager deploy ` from the `enterprise-ai-solutions` checkout (or list it in - `llm_services_autodeploy_models` in `config.agent-toolkit.yaml` to deploy it on install); - `./model-manager undeploy ` removes it.