[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-108035":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":22,"topics":23,"createdAt":10,"pushedAt":31,"updatedAt":32,"readmeContent":33,"aiSummary":34,"trendingCount":16,"starSnapshotCount":16,"syncStatus":17,"lastSyncTime":35,"discoverSource":36},108035,"xhub","XGrowthLab\u002Fxhub","XGrowthLab","A self-hosted AI gateway for enterprises. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]","https:\u002F\u002Fqiniu.github.io\u002Fxhub\u002Fen",null,"TypeScript",72,5,1,17,0,2,42.3,"MIT License",false,"main",true,[24,25,26,27,28,29,30],"ai-gateway","anthropic","gemini","litellm","openai","seeddance","tokenhub","2026-11-23 12:00:36","2026-11-23 09:12:09","\u003Cdiv align=\"center\">\n\n# XHub\n\n### A self-hosted AI gateway for enterprises\n\n**Connect models. Govern enterprise AI. Power applications and agents.**\n\nGive business applications, internal tools, and AI agents a shared model endpoint.\nManage models, access, cost, security, routing, and operations on your own infrastructure.\n\n[![Self-hosted](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FSelf--hosted-Yes-0891B2)](docs\u002Fgetting-started.md)\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-blue.svg)](LICENSE)\n[![OpenAI compatible](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FAPI-OpenAI%20compatible-412991)](#connect-your-applications)\n[![Go](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FGo-1.25-00ADD8?logo=go&logoColor=white)](go.mod)\n[![Docker Compose](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FDeploy-Docker%20Compose-2496ED?logo=docker&logoColor=white)](docker-compose.yml)\n[![Code Quality](https:\u002F\u002Fgithub.com\u002Fqiniu\u002Fxhub\u002Factions\u002Fworkflows\u002Fquality.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Fqiniu\u002Fxhub\u002Factions\u002Fworkflows\u002Fquality.yml)\n[![Coverage Status](https:\u002F\u002Fcodecov.io\u002Fgh\u002Fqiniu\u002Fxhub\u002Fbranch\u002Fmain\u002Fgraph\u002Fbadge.svg)](https:\u002F\u002Fcodecov.io\u002Fgh\u002Fqiniu\u002Fxhub)\n\n**English** | [简体中文](README.zh-CN.md)\n\n[Why XHub](#why-xhub) · [Enterprise AI capabilities](#enterprise-ai-capabilities-managed-together) · [Console preview](#console-preview) · [Docker installation](#docker-installation-and-usage) · [Documentation](#documentation)\n\n\u003C\u002Fdiv>\n\nXHub is an **MIT-licensed, self-hosted AI gateway for teams using multiple model providers**. Give applications a shared endpoint and separate virtual keys, manage model access and budgets, and inspect usage through a web console. Platform teams manage shared AI resources while business teams connect applications within their assigned permissions.\n\n**Distinct XHub capabilities:** Compose enterprise pre-call checks in XGo, inherit routing templates through key\u002Fteam\u002Forganization scopes, continue agent calls with Responses history, retain per-request price snapshots, and deduplicate settlement for supported asynchronous media tasks. Model catalogs, Playground, and call tracing connect these capabilities to everyday use.\n\n[Website and online documentation](https:\u002F\u002Fqiniu.github.io\u002Fxhub\u002Fen\u002F) · [Static website deployment](website\u002FREADME.md)\n\n![XHub console: browse available models, capabilities, and prices](docs\u002Fassets\u002Fconsole-models.png)\n\n## Why XHub?\n\nAs AI adoption grows from one application to multiple departments, model access needs a shared management layer.\n\n| Enterprise challenge | How XHub helps |\n| --- | --- |\n| Each application integrates providers separately | Use an OpenAI-compatible API and public model names while the gateway manages upstream deployments |\n| Shared provider keys make access hard to restrict or revoke | Issue personal and service virtual keys with model access scoped by team, project, and key |\n| AI spend grows without clear ownership | Review usage and calculated costs by user, key, team, and project; configure budgets and rate limits |\n| Failure handling and traffic allocation live in each application | Centralize deployment weights, routing strategies, retries, timeouts, and fallbacks |\n| A few platform administrators handle every access request | Delegate organization and team responsibilities for members, projects, and service keys |\n| Failed calls and configuration changes are difficult to trace | Use request logs, usage records, and administrative audit events for investigation |\n\n## Enterprise AI capabilities, managed together\n\n| Capability area | What XHub provides | Enterprise value |\n| --- | --- | --- |\n| Models and protocols | Provider credentials, model catalogs, multiple deployments, public model names, protocol adaptation, and native forwarding | A shared application endpoint and centralized model supply management |\n| Organization and access | Organizations, teams, projects, scoped roles, personal and service keys, model permissions, and access revocation | Model access aligned with your organization and responsibilities |\n| Cost and quotas | Usage dimensions, budgets, RPM\u002FTPM, catalog and manual rates, cache pricing, time windows, and historical price snapshots | Cost ownership, reconciliation, and usage controls |\n| Routing and reliability | Weighted splits, load\u002Flatency\u002Fcost\u002Fusage strategies, model groups, categorized fallbacks, retries, timeouts, and failure cooldowns | Deployment and request policies tailored to each business |\n| Security and programmable guardrails | Keywords, regular expressions, secret detection, XGo scripts, external moderation adapters, blocking, redaction, and execution records | Business policies enforced in the request path |\n| Agents and sessions | Chat, Responses, Messages, Gemini\u002FVertex dialogue endpoints, tool calls, history continuation, and session tracing | Support for business assistants, coding agents, and multi-turn tool workflows |\n| Multimodal and media tasks | Deployment-specific image, audio, embedding, rerank, and video operations, with asynchronous result and usage tracking | Shared management for dialogue, retrieval, and content generation |\n| Testing and operations | Model discovery, Playground, configuration diagnostics, request and error logs, audit records, and health checks | Provider validation, daily administration, and problem investigation |\n\n### Model access: shared protocols and native capabilities\n\nManage provider credentials, deployments, public model names, and supported endpoints together. Dialogue endpoints cover OpenAI Chat\u002FResponses, Anthropic Messages, and Gemini\u002FVertex, with conversion between supported dialogue structures and registered native forwarding paths. Applications use agreed model names while platform teams manage the deployments behind them.\n\nProvider discovery and catalogs help administrators configure models and let business users inspect available models, capabilities, and prices. Available operations depend on the provider and deployment capabilities.\n\n### Organization governance: platform control and team autonomy\n\nOrganize resources into organizations, teams, and projects, with platform, organization, and team administrators alongside ordinary members. Platform teams set model and budget boundaries; organization and team administrators manage members and projects within their scope. Members get their own model catalog and call records.\n\nGive people personal keys and applications team or project service keys. Keys support model scopes, budgets, expiration, rotation, blocking, and deletion. Removing a member preserves personal keys; subsequent requests must pass current membership, key scope, and billing authorization checks. Model permissions narrow through these scopes, with management and data access checked by the backend.\n\n### Cost management: usage with traceable pricing\n\nReview usage and calculated costs by user, key, team, and project. Configure budgets and RPM\u002FTPM allocations on organization, team, user, and API Key pages. Pricing supports catalog and manual rates, input\u002Foutput and cache read\u002Fwrite distinctions, token, picture, second, and query units, and peak\u002Foff-peak windows.\n\nEach call retains its applied price snapshot, so later price changes preserve historical pricing evidence. Gateway response caching and provider prompt caching are recorded separately to support usage and cost reconciliation. Available measurement dimensions depend on the upstream data reported.\n\n### Routing and reliability: policies for each business\n\nConfigure weighted traffic splits and deployment selection based on load, cost, latency, or usage through model settings and routing templates. Organize models into routing groups and define fallback chains for general errors, context limits, and upstream content-policy errors. Combine them with retries, timeouts, and failure cooldowns.\n\nOrganizations, teams, and keys can select or inherit routing templates. Session affinity and complete response caching for non-streaming calls are supported. Cross-model fallback happens only before response bytes are sent and can be disabled with `disable_fallbacks:true`; pinned continuations, native asynchronous creation, and Responses background requests are not replayed on another model.\n\n### Security guardrails: built-in rules and business customization\n\nApply keyword, RE2 regular-expression, secret-detection, and custom XGo checks to applicable Chat\u002FResponses text. Rules can run by default or on demand, in priority order, with blocking, redaction, modification, or non-blocking flags and records of actual execution.\n\nXGo guardrails can combine HTTP, JSON, and LLM calls for business checks. Implemented adapters connect OpenAI Moderation, Lakera, Azure, Bedrock, Presidio, and remote LiteLLM guardrails. The console supports draft testing, configuration validation, and rule management. The current execution stage is pre-call; see the [guardrail guide](docs\u002Fdevelopment\u002Fen\u002Fguardrails.md) for coverage.\n\n### Agents and sessions: context and cost across turns\n\nHandle multi-turn messages and tool-call structures in supported dialogue protocols. Continue Responses history through `previous_response_id` so subsequent turns can send incremental input. Associate sessions, call IDs, keys, and usage to trace consecutive requests from business assistants and coding agents.\n\nThe Playground supports streaming and non-streaming calls, session continuation, and complete curl examples to validate real requests and results before application integration.\n\n### Multimodal and asynchronous tasks: a shared management layer\n\nConnect image generation\u002Fediting, speech generation\u002Ftranscription, embeddings, reranking, and other operations according to declared deployment capabilities and their implementations. Video task transports include Volcengine Ark, Qiniu Seedance, and registered Fal queues. Protocol, model, and pricing support depends on the deployment.\n\nSupported asynchronous tasks can be created and queried, with links between the original request, terminal results, and usage. Logs show running, completed, or failed states; repeated completion queries deduplicate settlement. See the [runtime reference](docs\u002Fdevelopment\u002Fen\u002Fruntime.md) and [Qiniu Fal extension](docs\u002Fdevelopment\u002Fen\u002Fqiniu-fal.md) for provider-specific operations and pricing boundaries.\n\n### Operations: from provider validation to investigation\n\nManage credentials, deployments, access, routing, guardrails, and usage through the English and Chinese console. Validate models and endpoints in the Playground, diagnose missing credentials or unavailable deployments, inspect request and error logs for failure stages, upstream responses, and pricing evidence, and review key administrative actions through audit records.\n\nSelf-host the Go gateway, web console, and data stores. Your organization manages the runtime environment and access policies. Health checks help investigate service and dependency state; model requests go to the provider endpoints you configure.\n\n## From platform setup to business use\n\n1. **Connect providers.** Add credentials and deployments, publish model names, and configure routing.\n2. **Create organizations and teams.** Assign administrators, add members, and set team model access and budgets. Create projects as needed.\n3. **Issue keys for people and applications.** Use personal keys for members and service keys for team or project applications.\n4. **Validate in the Playground, then integrate.** Check available models and responses before connecting applications to the gateway API.\n5. **Manage adoption over time.** Review usage and cost, adjust deployments and routing, revoke access, and investigate problems through logs.\n\n## How it works\n\n```mermaid\nflowchart LR\n    Apps[Business apps \u002F Internal tools \u002F AI agents] -->|API + virtual key| Gateway[XHub Enterprise AI Gateway]\n    Platform[Platform and team admins] --> Console[XHub Console]\n    Console -->|Configuration \u002F Access \u002F Usage \u002F Testing| Gateway\n    Gateway -->|Route and forward| Providers[Configured AI providers]\n    Gateway --- DB[(PostgreSQL)]\n    Gateway --- Redis[(Redis · optional)]\n```\n\nThe gateway listens on `4000` and the console on `3000` by default. PostgreSQL stores configuration, identities, and usage. Redis provides shared runtime state; it is optional when running from source and included in the Compose stack.\n\n## Console preview\n\n**A model catalog for business teams.** The model page shown above displays the models available to the current account, their capabilities and prices, with access to Playground testing.\n\n**A shared configuration workspace for platform teams.** Manage provider credentials, deployments, and public model names in Models + Endpoints.\n\n![XHub console: model deployments and provider credentials](docs\u002Fassets\u002Fconsole-deployments.png)\n\n*Screenshots show a configured local instance. A fresh installation starts without model deployments.*\n\n## Enterprise use cases\n\n| Use case | How to use XHub |\n| --- | --- |\n| Enterprise AI platform | Connect providers, publish a model catalog, and assign departmental and project access and budgets |\n| Business applications and internal assistants | Give applications service keys and centrally manage model endpoints, routing, and cost ownership |\n| Coding agents and multi-turn workflows | Connect supported dialogue protocols, handle tool calls and history continuation, and trace session usage |\n| Knowledge retrieval and RAG | Manage dialogue, embedding, and rerank deployments with model access for retrieval workflows |\n| Content and media production | Configure image, audio, and video models and inspect supported task results, status, and usage |\n| Policy-sensitive AI access | Apply text guardrails and custom checks, restrict model scopes, and control access to logs |\n\nStart with one team and one application, then expand along your organizational structure.\n\n## Docker installation and usage\n\n### 1. Prepare your environment\n\nInstall [Docker Desktop](https:\u002F\u002Fdocs.docker.com\u002Fdesktop\u002F) on macOS\u002FWindows, or [Docker Engine](https:\u002F\u002Fdocs.docker.com\u002Fengine\u002Finstall\u002F) and the [Compose plugin](https:\u002F\u002Fdocs.docker.com\u002Fcompose\u002Finstall\u002Flinux\u002F) on Linux. Start Docker and check:\n\n```bash\ndocker version\ndocker compose version\n```\n\nThe current deployment builds on your host and packages the output into Docker images. You also need **Git, Go 1.25, Node.js ≥24.14.1, npm ≥11.10.0**, and a readable system CA bundle. The build script detects the common Debian\u002FUbuntu, RHEL, macOS, and Alpine paths; set `XHUB_CA_CERT_FILE` for another location. The build script requires Bash; on Windows, install these tools inside WSL2 Linux and enable Docker Desktop WSL integration. The script supports amd64\u002Farm64 and downloads Linux Node.js from npmmirror. See the [installation guide](docs\u002Fgetting-started.md) for complete requirements.\n\n### 2. Build and start\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fqiniu\u002Fxhub.git\ncd xhub\nbash deploy\u002Fbuild.sh\ndocker compose up -d --no-build\ndocker compose ps\n```\n\nThe build script creates local `xhub-gateway` and `xhub-console` images. Compose starts the gateway, console, PostgreSQL, and Redis. PostgreSQL data is stored in the `xhub-pg` named volume. Use a fresh database for your first installation.\n\n| Service | Purpose and address |\n| --- | --- |\n| Web console | [http:\u002F\u002Flocalhost:3000\u002Flogin](http:\u002F\u002Flocalhost:3000\u002Flogin) for models, teams, and policies |\n| Gateway API | [http:\u002F\u002Flocalhost:4000](http:\u002F\u002Flocalhost:4000) for SDKs, applications, and agents |\n| PostgreSQL | Host port `5433` for configuration, identity, and usage storage |\n| Redis | Internal Compose service for shared runtime state |\n\n### 3. Sign in and connect your first model\n\nThe initial local administrator is `admin@xhub.local` \u002F `admin-pass-1234`. Change the password after signing in, then:\n\n1. Add provider credentials, a deployment, and a public model name in **Models + Endpoints**.\n2. Create an organization and team, set model access and budgets, and add members. Create projects as needed.\n3. Issue personal keys for members and service keys for applications.\n4. Test in the Playground, then connect applications using the gateway URL and virtual keys.\n\nA fresh installation starts without model deployments. Follow the [user and administration guide](docs\u002Fuser-guide.md) for complete steps.\n\n### 4. Operate and update\n\n```bash\n# Follow gateway and console logs\ndocker compose logs -f gateway console\n\n# Restart application services\ndocker compose restart gateway console\n\n# Stop services and retain the PostgreSQL volume\ndocker compose down\n\n# Start again\ndocker compose up -d --no-build\n```\n\nBack up your database before updating. From the repository directory, pull the new version, rebuild, and recreate the application containers:\n\n```bash\ngit pull --ff-only\nbash deploy\u002Fbuild.sh\ndocker compose up -d --no-build --force-recreate gateway console\n```\n\nFor a server deployment, set `NEXT_PUBLIC_BASE_URL` to the browser-accessible gateway URL before building, and set Compose's `XHUB_PUBLIC_ORIGIN` to the same public API URL. Keep the console container's `XHUB_GATEWAY_ORIGIN` set to a reachable internal gateway address. Gateway settings, including initial administrator credentials, are in `configs\u002Fconfig.docker.yaml`; rebuild images after changing them. Initial password configuration only creates accounts that do not exist; change an existing account's password in the console. See [deployment configuration](docs\u002Fgetting-started.md#deployment-configuration) for details.\n\n## Run from source\n\nFor local development or independently managed PostgreSQL\u002FRedis, follow the [source installation guide](docs\u002Fgetting-started.md#run-from-source) to start the Go gateway and Next.js console separately. The gateway and console still use ports `4000` and `3000`; applications connect the same way.\n\n## Connect your applications\n\nInstall the client with `pip install openai`. Use your XHub virtual key and the public model name you configured:\n\n```python\nfrom openai import OpenAI\n\nclient = OpenAI(\n    api_key=\"YOUR_XHUB_VIRTUAL_KEY\",\n    base_url=\"http:\u002F\u002Flocalhost:4000\u002Fv1\",\n)\n\nresponse = client.chat.completions.create(\n    model=\"YOUR_PUBLIC_MODEL_NAME\",\n    messages=[{\"role\": \"user\", \"content\": \"Hello, XHub!\"}],\n)\nprint(response.choices[0].message.content)\n```\n\nSDK requests go to the **gateway on port 4000**; port 3000 serves the web console. Check the configured deployment's capabilities before integrating other operations.\n\n## Documentation\n\n| Guide | What it covers |\n| --- | --- |\n| [Installation and running guide](docs\u002Fgetting-started.md) | Docker, source setup, first request, and deployment configuration |\n| [User and administration guide](docs\u002Fuser-guide.md) | Model setup, members and keys, routing, cost review, and troubleshooting |\n| [Permission rules](docs\u002Fdevelopment\u002Fen\u002Fpermissions.md) | Platform, organization, team, and member access scopes |\n| [Runtime behavior and limits](docs\u002Fdevelopment\u002Fen\u002Fruntime.md) | Budgets, protocols, cache, idempotency, and multiple gateway instances |\n| [Documentation index](docs\u002FREADME.md) | User guides and implementation references |\n| [Developer and coding-agent guide](docs\u002Fdevelopment\u002Fen\u002FREADME.md) | Code map, invariants, and checks for a change |\n| [Testing](docs\u002Fdevelopment\u002Fen\u002Ftesting.md) | Unit tests, backend regression, and browser E2E |\n\nInstallation and customer guides are available in English and Chinese. Central development references are in Chinese; package-level `readme.md` \u002F `readme_cn.md` files provide bilingual code guides.\n\n## Project status and deployment references\n\nXHub is actively evolving. Evaluate production requirements against the [runtime reference](docs\u002Fdevelopment\u002Fen\u002Fruntime.md), [permission rules](docs\u002Fdevelopment\u002Fen\u002Fpermissions.md), and [guardrail guide](docs\u002Fdevelopment\u002Fen\u002Fguardrails.md). Budgets do not reserve request costs; shared limits, caching, and idempotency have implementation boundaries across instances. Reconcile calculated costs with provider bills. Enterprise identity supports independently managed OIDC Code + PKCE and [SAML 2.0 login](docs\u002Fdevelopment\u002Fen\u002Fsaml-login.md), plus SCIM user\u002Fgroup provisioning; enterprise login requires an active provisioned identity. Real identity-provider tenants require separate validation; this repository does not promise commercial SLAs or compliance certifications.\n\n## License\n\nXHub is licensed under the [MIT License](LICENSE), allowing commercial use, modification, and redistribution subject to retaining the copyright and permission notice. Third-party dependencies and incorporated materials retain their own licenses and notices, including [provider catalog attribution](internal\u002Fcatalog\u002Fpublicdata\u002Fprovider_fields.LICENSE). The software is provided without warranty.\n\n## Contributing\n\nXHub is actively evolving. [Open an issue](https:\u002F\u002Fgithub.com\u002Fqiniu\u002Fxhub\u002Fissues) with an enterprise use case or reproduction steps, improve the documentation, or submit a pull request. For code changes, follow the [developer guide](docs\u002Fdevelopment\u002Fen\u002FREADME.md) and the relevant module's validation requirements.\n\n### Hierarchical quota allocation\n\nBudgets follow **Organization → Team → Person → API Key**, in USD. Each person belongs to at most one team. Fixed child budgets reserve their unused amounts; sibling allocations and consumed money must fit within the parent budget. Blank budgets share the parent's unreserved balance; zero blocks spending. An organization budget of $1,000 can allocate $500 + $300 + $200 across teams, but cannot allocate another dollar. Personal keys without an explicit team binding still bill the owner's sole team. Service keys bill a separate business account. Use a separate unlimited organization and team for unrestricted business usage.\n\nRPM and TPM follow the same hierarchy: team allocations sum within the organization, personal allocations within the team, and key allocations within the person. Fixed values reserve minute capacity; blank values share the unreserved remainder; zero blocks calls. Blank intermediates pass fixed descendant allocations upward. Over-allocation rolls back the save. Admission atomically counts the unique ownership path and rejected calls consume no rate capacity. TPM uses the incoming token estimate; windows are UTC calendar minutes. Multiple gateway instances need shared Redis.\n\nSee [quota management](docs\u002Fquota-management.md) for examples, administrator permissions, membership changes, historical spending, and the request-admission\u002Fsettlement boundary.\nFor code ownership, allocation invariants, admission and accounting flow, and layered test commands, see [quota implementation and verification](docs\u002Fdevelopment\u002Fen\u002Fquota-chain.md).\nQuota acceptance uses fresh temporary ownership chains for each budget and RPM\u002FTPM check, verifies rejection before any upstream call and successful billed recovery, then deletes all temporary resources. Existing allocations and spending remain intact. The actual acceptance script is covered by a local gateway\u002Fdatabase regression test; see [acceptance dataset documentation](docs\u002Ftestdata\u002Freal-acceptance\u002FREADME.md).\n","XHub 是一个企业级自托管 AI 网关，用于统一接入和管理多种大模型服务。它提供 OpenAI 兼容 API 接口，支持 Bedrock、Azure、Anthropic、Vertex AI、vLLM 等 100+ 模型后端，具备成本追踪、请求守卫（guardrails）、负载均衡、细粒度访问控制、调用日志与审计等核心能力。基于 Docker Compose 快速部署，内置 Web 控制台用于模型浏览、用量分析与预算配置。适用于需在私有基础设施上集中治理多模型调用、保障安全合规、分摊 AI 成本并支撑内部应用与智能体开发的中大型企业平台团队。","2026-11-24 04:33:21","CREATED_QUERY"]