Alibrown commited on
Commit
2fa8acf
·
verified ·
1 Parent(s): b57b225

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +12 -512
README.md CHANGED
@@ -1,516 +1,16 @@
1
  ---
2
- title: Multi-LLM API Gateway
3
- emoji: 🛡️
4
- colorFrom: indigo
5
  colorTo: red
6
- sdk: docker
7
- pinned: true
8
- license: apache-2.0
9
- short_description: Secure Multi-LLM Gateway — (Streamable HTTP / SSE)
 
 
 
 
10
  ---
11
 
12
- # Multi-LLM API Gateway
13
-
14
- — or Universal MCP Hub (Sandboxed)
15
- — or secure AI wrapper with dual interface: REST + MCP
16
-
17
- aka: a clean, secure starting point for your own projects.
18
- Pick the description that fits your use case. They're all correct.
19
-
20
- > A production-grade **the-thing** that actually thinks about security.
21
- > Built on [PyFundaments](PyFundaments.md) — running on **simpleCity**.
22
-
23
- ```
24
- No key → no tool → no crash → no exposed secrets
25
- ```
26
-
27
- > [!WARNING]
28
- > Most MCP servers are prompts dressed up as servers. This one has a real architecture.
29
-
30
- ---
31
-
32
- > [!IMPORTANT]
33
- > This project is under active development — always use the latest release from [Codey Lab](https://github.com/Codey-LAB/Multi-LLM-API-Gateway) *(more stable builds land here first)*.
34
- > This repo ([DEV](https://github.com/VolkanSah/Multi-LLM-API-Gateway)) is where the chaos happens. 🔬 A ⭐ on the repos will be cool 😙
35
-
36
- ---
37
-
38
- ## What's new in v1.1.0 (Rebuild)
39
-
40
- > Full changelog in [`REVIEW.md`](REVIEW.md). Highlights:
41
-
42
- - **Fixed:** `/mcp` 404 (mount middleware stripped the prefix FastMCP expects) and the missing session-manager lifespan — MCP is fully functional again.
43
- - **New:** **Auto model pricing** — costs are fetched from the public OpenRouter models API + the LiteLLM community price list, cached in `db_sync` (24h TTL). Your `.pyfun [MODELS]` values always win as override. Manual cost maintenance is over.
44
- - **New:** Brave + Tavily search providers implemented with fallback chain — `web_search` registers as soon as `BRAVE_API_KEY` or `TAVILY_API_KEY` is set.
45
- - **New:** `db_query` as MCP tool (SELECT-only, app/* tables).
46
- - **Cleanup:** dead code removed, `requirements.txt` now pins `mcp>=1.10,<2` (not `fastmcp`), LF line endings.
47
-
48
- ## Why this exists
49
-
50
- The AI ecosystem is full of servers with hardcoded keys, `os.environ` scattered everywhere, zero sandboxing. One misconfigured fork and your API keys are gone.
51
-
52
- This is exactly the kind of negligence (and worse — outright fraud) that [Wall of Shames](https://github.com/Wall-of-Shames) documents: fake "AI tools" exploiting non-technical users — API wrappers dressed up as custom models, Telegram payment funnels, bought stars. If you build on open source, you should know this exists.
53
-
54
- This hub is the antidote:
55
-
56
- - **Structural sandboxing** — `app/*` can never touch `fundaments/` or `.env`. Not by convention. By design.
57
- - **Guardian pattern** — `main.py` is the only process that reads secrets. It injects validated services as a dict. `app/*` never sees the raw environment.
58
- - **Graceful degradation** — No key? Tool doesn't register. Server still starts. No crash, no error, no empty `None` floating around.
59
- - **Single source of truth** — All tool/provider/model config lives in `app/.pyfun`. Adding a provider = edit one file. No code changes.
60
-
61
- ---
62
-
63
- ## Two Interfaces — One Server
64
-
65
- This hub exposes **two completely independent interfaces** on the same hypercorn instance:
66
-
67
- ```
68
- POST /api → REST interface — for custom clients, desktop apps, CMS plugins
69
- GET+POST /mcp → MCP interface — for Claude Desktop, Cursor, Windsurf, any MCP client
70
- GET / → Health check — uptime, status
71
- ```
72
-
73
- They share the same tool registry, provider config, and fallback chain. Adding a tool once makes it available on both interfaces automatically.
74
-
75
- ### REST API (`/api`)
76
-
77
- Simple JSON POST — no protocol overhead, works with any HTTP client:
78
-
79
- ```json
80
- POST /api
81
- {"tool": "llm_complete", "params": {"prompt": "Hello", "provider": "anthropic"}}
82
- ```
83
-
84
- Used by: Desktop Client (`DESKTOP_CLIENT/hub.py`), WordPress plugin, any custom integration.
85
-
86
- ### MCP Interface (`/mcp`)
87
-
88
- Full MCP protocol — tool discovery, structured calls, streaming responses.
89
-
90
- **Primary transport: Streamable HTTP** (MCP spec 2025-11-25)
91
- **Fallback transport: SSE** (legacy, configurable via `.pyfun`)
92
-
93
- Configured via `HUB_TRANSPORT` in `app/.pyfun [HUB]`:
94
-
95
- ```ini
96
- HUB_TRANSPORT = "streamable-http" # default — MCP spec 2025-11-25
97
- # HUB_TRANSPORT = "sse" # legacy fallback for older clients
98
- ```
99
-
100
- Used by: Claude Desktop, Cursor, Windsurf, any MCP-compatible client.
101
-
102
- ---
103
-
104
- ## Architecture
105
-
106
- ```
107
- main.py (Guardian)
108
- │
109
- │ reads .env / HF Secrets
110
- │ initializes fundaments/* conditionally
111
- │ injects validated services as dict
112
- │
113
- └──► app/app.py (Orchestrator, sandboxed)
114
- │
115
- │ unpacks fundaments ONCE, at startup, never stores globally
116
- │ starts hypercorn (async ASGI)
117
- │ routes: GET / | POST /api | /mcp (transport-dependent)
118
- │
119
- ├── app/mcp.py ← FastMCP + transport handler (Streamable HTTP / SSE)
120
- ├── app/tools.py ← Tool registry (key-gated)
121
- ├── app/providers.py ← LLM + Search execution + fallback chain
122
- ├── app/models.py ← Model limits, costs, capabilities
123
- ├── app/config.py ← .pyfun parser (single source of truth)
124
- └── app/db_sync.py ← Internal SQLite IPC (app/* state only)
125
- ≠ fundaments/postgresql.py (Guardian-only)
126
- ```
127
-
128
- **The sandbox is structural:**
129
-
130
- ```python
131
- # app/app.py — fundaments unpacked ONCE, NEVER stored globally
132
- async def start_application(fundaments: Dict[str, Any]) -> None:
133
- config_service = fundaments["config"]
134
- db_service = fundaments["db"] # None if not configured
135
- encryption_service = fundaments["encryption"] # None if keys missing
136
- access_control_service = fundaments["access_control"]
137
- ...
138
- # From here: app/* reads its own config from app/.pyfun only.
139
- # fundaments are never passed into other app/* modules.
140
- ```
141
-
142
- `app/app.py` never calls `os.environ`. Never imports from `fundaments/`. Never reads `.env`.
143
- This isn't documentation. It's enforced by the import structure.
144
-
145
- ### Why Quart + hypercorn?
146
-
147
- **Quart** is async Flask — fully `async/await` native. FastMCP's handlers are async; mixing sync Flask would require thread hacks. With Quart, `/mcp` hands off directly to FastMCP — no bridging, no blocking.
148
-
149
- **hypercorn** is an ASGI server (vs. waitress/gunicorn which are WSGI). WSGI servers handle one request per thread — wrong for long-lived MCP connections. hypercorn handles both Streamable HTTP and SSE natively, and runs without extra config on HuggingFace Spaces. HTTP/2 support (`config.h2 = True`) is built-in — relevant for Streamable HTTP performance at scale.
150
-
151
- The `/mcp` route in `app.py` remains the natural interception point regardless of transport — auth checks, rate limiting, and logging can all be added there before the request reaches FastMCP.
152
-
153
- ---
154
-
155
- ## Two Databases — One Architecture
156
-
157
-
158
- ```
159
- ┌─────────────────────────────────────────────────────────────┐
160
- │ Guardian Layer (fundaments/*) │
161
- │ │
162
- │ postgresql.py → Cloud DB (e.g. Neon, Supabase) │
163
- │ asyncpg pool, SSL enforced │
164
- │ │
165
- │ user_handler.py → SQLite (users + sessions tables) │
166
- │ PBKDF2-SHA256 password hashing │
167
- │ Session validation incl. IP + UserAgent │
168
- │ Account lockout after 5 failed attempts │
169
- │ │
170
- └──────────────────────┬──────────────────────────────────────┘
171
- │ inject as fundaments dict
172
- ▼
173
- ┌─────────────────────────────────────────────────────────────┐
174
- │ App Layer (app/*) │
175
- │ │
176
- │ db_sync.py → SQLite (hub_state + tool_cache tables) │
177
- │ aiosqlite (async, non-blocking) │
178
- │ NEVER touches users/sessions tables │
179
- │ Relocated to /tmp/ on HF Spaces auto │
180
- │ │
181
- └─────────────────────────────────────────────────────────────┘
182
- ```
183
-
184
- **Table ownership — hard rule:**
185
-
186
- | Table | Owner | Access |
187
- | :--- | :--- | :--- |
188
- | `users` | `fundaments/user_handler.py` | Guardian only |
189
- | `sessions` | `fundaments/user_handler.py` | Guardian only |
190
- | `hub_state` | `app/db_sync.py` | app/* only |
191
- | `tool_cache` | `app/db_sync.py` | app/* only |
192
- | `hub_results` | PostgreSQL / Guardian | via `persist_result` tool |
193
-
194
- ---
195
-
196
- ## Tools
197
-
198
- Tools register at startup — only if the required API key exists. No key, no tool. Server always starts.
199
-
200
- | ENV Secret | Tool | Notes |
201
- | :--- | :--- | :--- |
202
- | `ANTHROPIC_API_KEY` | `llm_complete` | Claude Haiku / Sonnet / Opus |
203
- | `GEMINI_API_KEY` | `llm_complete` | Gemini 2.0 / 2.5 / 3.x Flash & Pro |
204
- | `OPENROUTER_API_KEY` | `llm_complete` | 100+ models via OpenRouter |
205
- | `HF_TOKEN` | `llm_complete` | HuggingFace Inference API |
206
- | `BRAVE_API_KEY` | `web_search` | Independent web index |
207
- | `TAVILY_API_KEY` | `web_search` | AI-optimized search with synthesized answers |
208
- | `DATABASE_URL` | `cloud DB` | e.g. Neon, Supabase |
209
- | `DATABASE_URL` | `db_query`, `persist_result` | SQLite read + PostgreSQL write |
210
- | *(always)* | `list_active_tools` | Shows key names only — never values |
211
- | *(always)* | `health_check` | Status + uptime + active transport |
212
- | *(always)* | `get_model_info` | Limits, costs, capabilities per model (auto-merged) |
213
- | *(always)* | `get_model_pricing` | Auto-fetched costs — `.pyfun` values win as override |
214
- | *(always)* | `refresh_pricing` | Force refresh from OpenRouter + LiteLLM |
215
- | *(always)* | `db_query` | Read-only SELECT on internal hub state |
216
-
217
- For all key names see [`app/.pyfun`](app/.pyfun).
218
-
219
- **Tools are configured in `.pyfun` — including system prompts:**
220
-
221
- ```ini
222
- [TOOL.code_review]
223
- active = "true"
224
- description = "Review code for bugs, security issues and improvements"
225
- provider_type = "llm"
226
- default_provider = "anthropic"
227
- timeout_sec = "60"
228
- system_prompt = "You are an expert code reviewer. Analyze the given code for bugs, security issues, and improvements. Be specific and concise."
229
- [TOOL.code_review_END]
230
- ```
231
-
232
- Current built-in tools: `llm_complete`, `code_review`, `summarize`, `translate`, `web_search`, `db_query`
233
- Future hooks (commented, ready): `image_gen`, `code_exec`, `shellmaster_2.0`, Discord, GitHub webhooks
234
-
235
- ---
236
-
237
- ## LLM Fallback Chain
238
-
239
- All LLM providers share one `llm_complete` tool. If a provider fails, the hub walks the fallback chain from `.pyfun`:
240
-
241
- ```
242
- e.g. anthropic → gemini → openrouter → huggingface
243
- ```
244
-
245
- ```ini
246
- [LLM_PROVIDER.anthropic]
247
- fallback_to = "gemini"
248
- [LLM_PROVIDER.anthropic_END]
249
-
250
- [LLM_PROVIDER.gemini]
251
- fallback_to = "openrouter"
252
- [LLM_PROVIDER.gemini_END]
253
- ```
254
-
255
- Same pattern applies to search providers (`brave → tavily`).
256
-
257
- ---
258
-
259
- ## Quick Start
260
-
261
- ### HuggingFace Spaces (recommended)
262
-
263
- 1. Fork / duplicate this Space
264
- 2. Go to **Settings → Variables and secrets**
265
- 3. Add the API keys you have (any subset works)
266
- 4. Space starts automatically — only tools with valid keys register
267
-
268
- [→ Live Demo Space](https://huggingface.co/spaces/codey-lab/Multi-LLM-API-Gateway) (no LLM keys set)
269
-
270
- ### Local / Docker
271
-
272
- ```bash
273
- git clone https://github.com/VolkanSah/Multi-LLM-API-Gateway
274
- cd Multi-LLM-API-Gateway
275
- cp example-mcp___.env .env
276
- # fill in your keys
277
- pip install -r requirements.txt
278
- python main.py
279
- ```
280
-
281
- Minimum required ENV vars (everything else is optional):
282
-
283
- ```env
284
- PYFUNDAMENTS_DEBUG=""
285
- LOG_LEVEL="INFO"
286
- LOG_TO_TMP=""
287
- ENABLE_PUBLIC_LOGS="true"
288
- HF_TOKEN=""
289
- HUB_SPACE_URL=""
290
- ```
291
-
292
- Transport is configured in `app/.pyfun [HUB]` — not via ENV.
293
-
294
- ---
295
-
296
- ## Connect an MCP Client
297
-
298
- ### Streamable HTTP (default — MCP spec 2025-11-25)
299
-
300
- ```json
301
- {
302
- "mcpServers": {
303
- "universal-mcp-hub": {
304
- "url": "https://YOUR_USERNAME-universal-mcp-hub.hf.space/mcp"
305
- }
306
- }
307
- }
308
- ```
309
-
310
- ### Streamable HTTP — Private Space (with HF token)
311
-
312
- ```json
313
- {
314
- "mcpServers": {
315
- "universal-mcp-hub": {
316
- "url": "https://YOUR_USERNAME-universal-mcp-hub.hf.space/mcp",
317
- "headers": {
318
- "Authorization": "Bearer hf_..."
319
- }
320
- }
321
- }
322
- }
323
- ```
324
-
325
- ### SSE legacy fallback (set `HUB_TRANSPORT = "sse"` in `.pyfun`)
326
-
327
- ```json
328
- {
329
- "mcpServers": {
330
- "universal-mcp-hub": {
331
- "url": "https://YOUR_USERNAME-universal-mcp-hub.hf.space/mcp"
332
- }
333
- }
334
- }
335
- ```
336
-
337
- > Same URL (`/mcp`) for both transports — the protocol is negotiated automatically.
338
- > SSE fallback is for older clients that don't support Streamable HTTP yet.
339
-
340
- ---
341
-
342
- ## Desktop Client
343
- ###### (experimental — ~80% AI generated)
344
-
345
- A full PySide6 desktop client is included in `DESKTOP_CLIENT/hub.py`.
346
- Communicates via the REST `/api` endpoint — no MCP protocol overhead.
347
- Ideal for private or non-public Spaces.
348
-
349
- ```bash
350
- pip install PySide6 httpx
351
- # optional file handling:
352
- pip install Pillow PyPDF2 pandas openpyxl
353
- python DESKTOP_CLIENT/hub.py
354
- ```
355
-
356
- **Features:**
357
- - Multi-chat with persistent history
358
- - Tool / Provider / Model selector loaded live from your Hub
359
- - File attachments: images, PDF, CSV, Excel, ZIP, source code
360
- - Connect tab with health check + auto-load
361
- - Settings: HF Token + Hub URL saved locally, never sent anywhere except your own Hub
362
- - Full request/response log with timestamps
363
- - Runs on Windows, Linux, macOS
364
-
365
- [→ Desktop Client docs](DESKTOP_CLIENT/README.md)
366
-
367
- ---
368
-
369
- ## CMS & Custom Clients
370
-
371
- | Client | Interface used | Notes |
372
- | :--- | :--- | :--- |
373
- | [Desktop Client](DESKTOP_CLIENT/hub.py) | REST `/api` | PySide6, local |
374
- | [WP AI Hub](https://github.com/VolkanSah/WP-AI-HUB/) | REST `/api` | WordPress plugin |
375
- | TYPO3 (soon) | REST `/api` | — |
376
- | Claude Desktop | MCP `/mcp` | Streamable HTTP |
377
- | Cursor / Windsurf | MCP `/mcp` | Streamable HTTP |
378
-
379
- ---
380
-
381
- ## Configuration (.pyfun)
382
-
383
- `app/.pyfun` is the single source of truth for all app behavior. Three tiers:
384
-
385
- ```
386
- LAZY: [HUB] + one [LLM_PROVIDER.*] → works
387
- NORMAL: + [SEARCH_PROVIDER.*] + [MODELS.*] → works better
388
- PRODUCTIVE: + [TOOLS] + [HUB_LIMITS] + [DB_SYNC] → full power
389
- ```
390
-
391
- Key settings in `[HUB]`:
392
-
393
- ```ini
394
- [HUB]
395
- HUB_TRANSPORT = "streamable-http" # streamable-http | sse
396
- HUB_STATELESS = "true" # true = HF Spaces safe, no session state
397
- HUB_PORT = "7860"
398
- [HUB_END]
399
- ```
400
-
401
- Adding a new LLM provider — two steps:
402
-
403
- ```ini
404
- # 1. app/.pyfun
405
- [LLM_PROVIDER.mistral]
406
- active = "true"
407
- base_url = "https://api.mistral.ai/v1"
408
- env_key = "MISTRAL_API_KEY"
409
- default_model = "mistral-large-latest"
410
- models = "mistral-large-latest, mistral-small-latest"
411
- fallback_to = ""
412
- [LLM_PROVIDER.mistral_END]
413
- ```
414
-
415
- ```python
416
- # 2. app/providers.py — uncomment the dummy
417
- _PROVIDER_CLASSES = {
418
- ...
419
- "mistral": MistralProvider, # ← uncomment to activate
420
- }
421
- ```
422
-
423
- ---
424
-
425
- ## Dependencies
426
-
427
- ```
428
- # PyFundaments Core (always required)
429
- asyncpg — async PostgreSQL pool (Guardian/cloud DB)
430
- python-dotenv — .env loading
431
- passlib — PBKDF2 password hashing in user_handler.py
432
- cryptography — encryption layer in fundaments/
433
-
434
- # MCP Hub
435
- mcp — MCP protocol + FastMCP (Streamable HTTP + SSE)
436
- httpx — async HTTP for all provider API calls
437
- quart — async Flask (ASGI) — needed for MCP + hypercorn
438
- hypercorn — ASGI server — Streamable HTTP + SSE, HF Spaces native
439
- requests — sync HTTP for tool workers
440
-
441
- # Optional (uncomment in requirements.txt as needed)
442
- # aiofiles — async file ops (ML pipelines, file uploads)
443
- # discord.py — Discord bot integration (planned)
444
- # PyNaCl — Discord signature verification
445
- # psycopg2-binary — alternative PostgreSQL driver
446
- ```
447
-
448
- > **Note:** The package is `mcp` (not `fastmcp`) — `FastMCP` is imported from `mcp.server.fastmcp`.
449
- > Streamable HTTP support requires `mcp >= 1.6.0`.
450
-
451
- ---
452
-
453
- ## Security Design
454
-
455
- - API keys live in HF Secrets / `.env` — never in `.pyfun`, never in code
456
- - `list_active_tools` returns key **names** only — never values
457
- - `db_query` is SELECT-only, enforced at application level (not just docs)
458
- - `app/*` has zero import access to `fundaments/` internals
459
- - Direct execution of `app/app.py` blocked by design — warning + null-fundaments fallback
460
- - `fundaments/` initialized conditionally — missing services degrade gracefully, never crash
461
- - Streamable HTTP uses standard Bearer headers — no token-in-URL (unlike SSE)
462
-
463
- > PyFundaments is not perfect. But it's more secure than most of what runs in production today.
464
-
465
- [→ Full Security Policy](SECURITY.md)
466
-
467
- ---
468
-
469
- ## Foundation
470
-
471
- Built on [PyFundaments](PyFundaments.md) — a security-first Python boilerplate:
472
-
473
- - `config_handler.py` — env loading with validation
474
- - `postgresql.py` — async DB pool (Guardian-only)
475
- - `encryption.py` — key-based encryption layer
476
- - `access_control.py` — role/permission management
477
- - `user_handler.py` — user lifecycle management
478
- - `security.py` — unified security manager composing the above
479
-
480
- None accessible from `app/*`. Injected as a validated dict by `main.py`.
481
-
482
- [→ PyFundaments Function Overview](PyFundaments%20–%20Function%20Overview.md)
483
- [→ Module Docs](docs/app/)
484
- [→ Source Repo](https://github.com/VolkanSah/Multi-LLM-API-Gateway)
485
-
486
- ---
487
-
488
- ## Related Projects
489
-
490
- - [Customs LLMs for free — Build Your Own LLM Service](https://github.com/VolkanSah/SmolLM2-customs/)
491
- - [WP AI Hub (WordPress Client)](https://github.com/VolkanSah/WP-AI-HUB/)
492
- - [ShellMaster (2023 precursor)](https://github.com/VolkanSah/ChatGPT-ShellMaster)
493
-
494
- ---
495
-
496
- ## History
497
-
498
- [ShellMaster](https://github.com/VolkanSah/ChatGPT-ShellMaster) (2023, MIT) was the precursor — browser-accessible shell for ChatGPT with session memory, built before MCP was a concept. Universal MCP Hub is its natural evolution: same idea, proper architecture, dual interface.
499
-
500
- ---
501
-
502
- ## License
503
-
504
- Dual-licensed:
505
-
506
- - [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0)
507
- - [Ethical Security Operations License v1.1 (ESOL)](ESOL) — mandatory, non-severable
508
-
509
- By using this software you agree to all ethical constraints defined in ESOL v1.1.
510
-
511
- ---
512
-
513
- *Architecture, security decisions, and PyFundaments by Volkan Kücükbudak.*
514
- *Built with Claude (Anthropic) as a typing assistant for docs (and the occasional bug).*
515
-
516
- > crafted with passion — just wanted to understand how it works, don't actually need it, have a CLI 😄
 
1
  ---
2
+ title: ZeroGPU Mini-Trainer
3
+ emoji: ⚡
4
+ colorFrom: yellow
5
  colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 5.49.1
8
+ app_file: app.py
9
+ pinned: false
10
+ hf_oauth: true
11
+ hf_oauth_scopes:
12
+ - read-repos
13
+ - write-repos
14
  ---
15
 
16
+ LoRA-Fine-Tuning für kleine SmolLM-Modelle auf ZeroGPU. Jeder Nutzer loggt sich ein und nutzt seine eigene Tagesquote.