ai-synapse 4.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. ai_synapse-4.0.0/LICENSE +21 -0
  2. ai_synapse-4.0.0/PKG-INFO +257 -0
  3. ai_synapse-4.0.0/README.md +213 -0
  4. ai_synapse-4.0.0/ai_engine/__init__.py +25 -0
  5. ai_synapse-4.0.0/ai_engine/_engine.py +121 -0
  6. ai_synapse-4.0.0/ai_engine/_exceptions.py +89 -0
  7. ai_synapse-4.0.0/ai_engine/anthropic.py +33 -0
  8. ai_synapse-4.0.0/ai_engine/openai.py +120 -0
  9. ai_synapse-4.0.0/ai_engine/py.typed +0 -0
  10. ai_synapse-4.0.0/ai_engine/resources/__init__.py +2 -0
  11. ai_synapse-4.0.0/ai_engine/resources/chat.py +135 -0
  12. ai_synapse-4.0.0/ai_engine/resources/models.py +48 -0
  13. ai_synapse-4.0.0/ai_engine/types/__init__.py +171 -0
  14. ai_synapse-4.0.0/ai_synapse.egg-info/PKG-INFO +257 -0
  15. ai_synapse-4.0.0/ai_synapse.egg-info/SOURCES.txt +88 -0
  16. ai_synapse-4.0.0/ai_synapse.egg-info/dependency_links.txt +1 -0
  17. ai_synapse-4.0.0/ai_synapse.egg-info/requires.txt +21 -0
  18. ai_synapse-4.0.0/ai_synapse.egg-info/top_level.txt +2 -0
  19. ai_synapse-4.0.0/core/__init__.py +1 -0
  20. ai_synapse-4.0.0/core/advanced_features.py +217 -0
  21. ai_synapse-4.0.0/core/ai_engine.py +2044 -0
  22. ai_synapse-4.0.0/core/api_versioning.py +133 -0
  23. ai_synapse-4.0.0/core/batch.py +134 -0
  24. ai_synapse-4.0.0/core/billing.py +262 -0
  25. ai_synapse-4.0.0/core/caching.py +215 -0
  26. ai_synapse-4.0.0/core/capabilities.py +305 -0
  27. ai_synapse-4.0.0/core/chat_intelligence.py +279 -0
  28. ai_synapse-4.0.0/core/config_sync.py +300 -0
  29. ai_synapse-4.0.0/core/enterprise.py +336 -0
  30. ai_synapse-4.0.0/core/error_codes.py +224 -0
  31. ai_synapse-4.0.0/core/health_monitor.py +198 -0
  32. ai_synapse-4.0.0/core/infrastructure.py +286 -0
  33. ai_synapse-4.0.0/core/intelligent_router.py +440 -0
  34. ai_synapse-4.0.0/core/latency_tracker.py +158 -0
  35. ai_synapse-4.0.0/core/load_test.py +186 -0
  36. ai_synapse-4.0.0/core/logging_sla.py +293 -0
  37. ai_synapse-4.0.0/core/middleware.py +199 -0
  38. ai_synapse-4.0.0/core/model_cache.py +202 -0
  39. ai_synapse-4.0.0/core/plugin_system.py +189 -0
  40. ai_synapse-4.0.0/core/provider_requests.py +454 -0
  41. ai_synapse-4.0.0/core/py.typed +0 -0
  42. ai_synapse-4.0.0/core/rate_limit_manager.py +128 -0
  43. ai_synapse-4.0.0/core/request_queue.py +105 -0
  44. ai_synapse-4.0.0/core/response_cache.py +200 -0
  45. ai_synapse-4.0.0/core/session_backup.py +243 -0
  46. ai_synapse-4.0.0/core/statistics_manager.py +253 -0
  47. ai_synapse-4.0.0/core/stress_test.py +313 -0
  48. ai_synapse-4.0.0/core/usage_tracker.py +125 -0
  49. ai_synapse-4.0.0/core/workflow_engine.py +322 -0
  50. ai_synapse-4.0.0/pyproject.toml +70 -0
  51. ai_synapse-4.0.0/setup.cfg +4 -0
  52. ai_synapse-4.0.0/tests/test_advanced_features.py +171 -0
  53. ai_synapse-4.0.0/tests/test_ai_engine.py +356 -0
  54. ai_synapse-4.0.0/tests/test_api_versioning.py +124 -0
  55. ai_synapse-4.0.0/tests/test_batch_search.py +227 -0
  56. ai_synapse-4.0.0/tests/test_billing.py +124 -0
  57. ai_synapse-4.0.0/tests/test_branching.py +110 -0
  58. ai_synapse-4.0.0/tests/test_caching.py +163 -0
  59. ai_synapse-4.0.0/tests/test_capabilities.py +136 -0
  60. ai_synapse-4.0.0/tests/test_chat_db.py +283 -0
  61. ai_synapse-4.0.0/tests/test_chat_features.py +181 -0
  62. ai_synapse-4.0.0/tests/test_chat_intelligence.py +142 -0
  63. ai_synapse-4.0.0/tests/test_chat_router.py +216 -0
  64. ai_synapse-4.0.0/tests/test_cli.py +67 -0
  65. ai_synapse-4.0.0/tests/test_config.py +83 -0
  66. ai_synapse-4.0.0/tests/test_edge_cases.py +166 -0
  67. ai_synapse-4.0.0/tests/test_enterprise.py +184 -0
  68. ai_synapse-4.0.0/tests/test_error_codes.py +119 -0
  69. ai_synapse-4.0.0/tests/test_health_monitor.py +254 -0
  70. ai_synapse-4.0.0/tests/test_infrastructure.py +192 -0
  71. ai_synapse-4.0.0/tests/test_integration.py +187 -0
  72. ai_synapse-4.0.0/tests/test_intelligence.py +179 -0
  73. ai_synapse-4.0.0/tests/test_intelligent_router.py +172 -0
  74. ai_synapse-4.0.0/tests/test_latency_tracker.py +102 -0
  75. ai_synapse-4.0.0/tests/test_load_testing.py +224 -0
  76. ai_synapse-4.0.0/tests/test_logging_sla.py +126 -0
  77. ai_synapse-4.0.0/tests/test_middleware.py +160 -0
  78. ai_synapse-4.0.0/tests/test_model_cache.py +168 -0
  79. ai_synapse-4.0.0/tests/test_platform.py +138 -0
  80. ai_synapse-4.0.0/tests/test_plugin_system.py +91 -0
  81. ai_synapse-4.0.0/tests/test_rate_limit_manager.py +86 -0
  82. ai_synapse-4.0.0/tests/test_request_queue.py +179 -0
  83. ai_synapse-4.0.0/tests/test_response_cache.py +135 -0
  84. ai_synapse-4.0.0/tests/test_sdk_battle.py +341 -0
  85. ai_synapse-4.0.0/tests/test_server.py +393 -0
  86. ai_synapse-4.0.0/tests/test_session_backup.py +151 -0
  87. ai_synapse-4.0.0/tests/test_statistics_manager.py +189 -0
  88. ai_synapse-4.0.0/tests/test_upload.py +118 -0
  89. ai_synapse-4.0.0/tests/test_websocket_manager.py +200 -0
  90. ai_synapse-4.0.0/tests/test_workflow_engine.py +89 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MiHiR
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,257 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-synapse
3
+ Version: 4.0.0
4
+ Summary: Free multi-provider AI SDK — drop-in OpenAI & Anthropic compatibility with 27 free providers
5
+ Author: AI Engine Contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/mihir0209/AI_engine
8
+ Project-URL: Documentation, https://github.com/mihir0209/AI_engine/tree/main/docs
9
+ Project-URL: Repository, https://github.com/mihir0209/AI_engine
10
+ Project-URL: Issues, https://github.com/mihir0209/AI_engine/issues
11
+ Keywords: ai,llm,openai,anthropic,inference,free-ai,groq,gemini,sdk
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: requests>=2.28.0
25
+ Requires-Dist: python-dotenv>=0.19.0
26
+ Requires-Dist: pydantic>=2.5.0
27
+ Provides-Extra: server
28
+ Requires-Dist: aiohttp>=3.8.0; extra == "server"
29
+ Requires-Dist: fastapi>=0.104.0; extra == "server"
30
+ Requires-Dist: uvicorn[standard]>=0.24.0; extra == "server"
31
+ Requires-Dist: jinja2>=3.1.0; extra == "server"
32
+ Requires-Dist: python-multipart>=0.0.6; extra == "server"
33
+ Requires-Dist: aiofiles>=23.0.0; extra == "server"
34
+ Requires-Dist: prometheus-client>=0.17.0; extra == "server"
35
+ Requires-Dist: slowapi>=0.1.0; extra == "server"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
38
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
39
+ Requires-Dist: pytest-timeout>=2.0.0; extra == "dev"
40
+ Requires-Dist: pytest-asyncio>=0.20.0; extra == "dev"
41
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
42
+ Requires-Dist: openai>=2.0.0; extra == "dev"
43
+ Dynamic: license-file
44
+
45
+ # AI Synapse — Free Multi-Provider AI SDK
46
+
47
+ [![Tests](https://img.shields.io/badge/tests-573%20passing-brightgreen)]()
48
+ [![Providers](https://img.shields.io/badge/providers-27%20enabled-blue)]()
49
+ [![Python](https://img.shields.io/badge/python-3.10%2B-3776AB)]()
50
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)]()
51
+ [![OpenAI Compatible](https://img.shields.io/badge/OpenAI-Compatible-412991)]()
52
+ [![Docker](https://img.shields.io/badge/Docker-Ready-2496ED)]()
53
+
54
+ > **Stop paying for AI inference.** Drop-in `from ai_engine import OpenAI` — routes through 27+ free providers with automatic failover and intelligent routing.
55
+
56
+ ---
57
+
58
+ ## Free Providers
59
+
60
+ ### No API Key Required (Truly Free)
61
+
62
+ | Provider | Model | Endpoint |
63
+ |----------|-------|----------|
64
+ | **Pollinations** | openai | `text.pollinations.ai/openai` |
65
+ | **Hermes** | Hermes-3-Llama | `hermes.ai.unturf.com/v1` |
66
+ | **G4F Groq** | llama-3.3-70b | `g4f.space/api/groq` |
67
+ | **G4F Gemini** | gemini-2.5-flash | `g4f.space/api/gemini` |
68
+ | **G4F NVIDIA** | nemotron-3 | `g4f.space/api/nvidia` |
69
+ | **OpenCode Zen** | north-mini-code | `opencode.ai/zen/v1` |
70
+
71
+ ### Free Tier APIs (Signup Required)
72
+
73
+ | Provider | Free Tier | Signup |
74
+ |----------|-----------|--------|
75
+ | **Groq** | 30 RPM, 14,400 RPD | [console.groq.com](https://console.groq.com) |
76
+ | **OpenRouter** | 23 free models | [openrouter.ai](https://openrouter.ai) |
77
+ | **Gemini** | 5-30 RPM | [aistudio.google.com](https://aistudio.google.com) |
78
+ | **NVIDIA** | 40 RPM | [build.nvidia.com](https://build.nvidia.com) |
79
+ | **Cerebras** | 30 RPM | [cloud.cerebras.ai](https://cloud.cerebras.ai) |
80
+ | **Cloudflare** | 10K neurons/day | [dash.cloudflare.com](https://dash.cloudflare.com) |
81
+ | **GitHub** | Varies | [github.com/marketplace](https://github.com/marketplace/models) |
82
+ | **Vercel** | $5/month free | [vercel.com](https://vercel.com) |
83
+ | **Cohere** | 20 RPM, 1K/month | [cohere.com](https://cohere.com) |
84
+ | **Mistral** | 1 RPS, 500K tokens/min | [console.mistral.ai](https://console.mistral.ai) |
85
+ | **HuggingFace** | $0.10/month | [huggingface.co](https://huggingface.co) |
86
+ | **Kilo** | Auto free routing | [app.kilo.ai](https://app.kilo.ai) |
87
+
88
+ ### Custom Providers (Your Keys)
89
+
90
+ | Provider | Models | Signup |
91
+ |----------|--------|--------|
92
+ | **hcnsec** | [Various](https://api.hcnsec.cn/pricing) | [api.hcnsec.cn](https://api.hcnsec.cn) |
93
+ | **LLM7** | [Various](https://docs.llm7.io/guides/models) | [llm7.io](https://llm7.io) |
94
+ | **PaxSenix** | [Various](https://api.paxsenix.org/v1/models) | [api.paxsenix.org](https://api.paxsenix.org) |
95
+
96
+ ### Self-Hosted Options
97
+
98
+ | Provider | Setup | Models |
99
+ |----------|-------|--------|
100
+ | **GPT4Free** | `docker run -p 8080:8080 hlohaus789/g4f` | GPT-4o, Claude, Gemini |
101
+ | **Ollama** | `curl -fsSL https://ollama.com/install.sh \| sh` | Llama, Mistral, etc. |
102
+
103
+ ---
104
+
105
+ ## Quick Start
106
+
107
+ ### Option 1: Free Tier APIs (Recommended)
108
+
109
+ ```bash
110
+ # 1. Copy environment template
111
+ cp .env.example .env
112
+
113
+ # 2. Get free API keys (see guide below)
114
+ # 3. Add keys to .env file
115
+ # 4. Start server
116
+ python server.py
117
+ ```
118
+
119
+ ### Option 2: Self-Hosted (No API Keys Needed)
120
+
121
+ ```bash
122
+ # Start g4f server
123
+ docker run -d -p 8080:8080 hlohaus789/g4f
124
+
125
+ # Start AI Engine
126
+ python server.py
127
+ ```
128
+
129
+ ---
130
+
131
+ ## For Developers
132
+
133
+ ### OpenAI SDK Compatible
134
+
135
+ ```python
136
+ from openai import OpenAI
137
+
138
+ client = OpenAI(
139
+ base_url="http://localhost:8000/v1",
140
+ api_key="dummy" # Not needed for free providers
141
+ )
142
+
143
+ # Chat completion
144
+ response = client.chat.completions.create(
145
+ model="gpt-4",
146
+ messages=[{"role": "user", "content": "Hello!"}]
147
+ )
148
+ print(response.choices[0].message.content)
149
+
150
+ # Streaming
151
+ stream = client.chat.completions.create(
152
+ model="gpt-4",
153
+ messages=[{"role": "user", "content": "Tell me a story"}],
154
+ stream=True
155
+ )
156
+ for chunk in stream:
157
+ if chunk.choices[0].delta.content:
158
+ print(chunk.choices[0].delta.content, end="")
159
+ ```
160
+
161
+ ### cURL
162
+
163
+ ```bash
164
+ curl http://localhost:8000/v1/chat/completions \
165
+ -H "Content-Type: application/json" \
166
+ -d '{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello!"}]}'
167
+ ```
168
+
169
+ ### JavaScript
170
+
171
+ ```javascript
172
+ import OpenAI from 'openai';
173
+
174
+ const client = new OpenAI({
175
+ baseURL: 'http://localhost:8000/v1',
176
+ apiKey: 'dummy'
177
+ });
178
+
179
+ const response = await client.chat.completions.create({
180
+ model: 'gpt-4',
181
+ messages: [{ role: 'user', content: 'Hello!' }]
182
+ });
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Features
188
+
189
+ ### Core
190
+ - OpenAI-compatible API with streaming
191
+ - Automatic provider failover
192
+ - Intelligent key rotation
193
+ - Response caching with TTL
194
+
195
+ ### Intelligence
196
+ - Task-based model selection
197
+ - Cost optimization
198
+ - Latency tracking
199
+ - A/B testing
200
+
201
+ ### Enterprise
202
+ - Multi-tenancy with quotas
203
+ - RBAC (Admin/User/Viewer)
204
+ - Audit logging
205
+ - Billing tracking
206
+
207
+ ### Platform
208
+ - Plugin system
209
+ - Workflow engine
210
+ - CLI tool
211
+ - Docker deployment
212
+
213
+ ---
214
+
215
+ ## API Endpoints
216
+
217
+ | Endpoint | Method | Description |
218
+ |----------|--------|-------------|
219
+ | `/v1/chat/completions` | POST | Chat completions (OpenAI-compatible, supports `stream: true`) |
220
+ | `/v1/models` | GET/POST | List all models |
221
+ | `/api/providers` | GET | List providers |
222
+ | `/api/health/{name}/ping` | POST | Live health ping for a provider |
223
+ | `/api/capabilities` | GET | Provider/model capabilities (vision, etc.) |
224
+ | `/api/status` | GET | Engine status |
225
+ | `/api/statistics` | GET | Usage statistics |
226
+ | `/health` | GET | Health check |
227
+ | `/metrics` | GET | Prometheus metrics |
228
+ | `/docs` | GET | Swagger UI (interactive API explorer) |
229
+ | `/redoc` | GET | ReDoc API documentation |
230
+
231
+ ### Rate Limit Headers
232
+
233
+ All API responses include:
234
+ - `X-RateLimit-Limit` — Max requests per minute
235
+ - `X-RateLimit-Remaining` — Remaining requests in current window
236
+
237
+ ---
238
+
239
+ ## Documentation
240
+
241
+ - [API Reference](docs/API.md)
242
+ - [User Guide](docs/USER_GUIDE.md)
243
+ - [Deployment Guide](docs/DEPLOYMENT.md)
244
+ - [Security Guide](docs/SECURITY.md)
245
+ - [Provider Setup](docs/collect_api.md)
246
+
247
+ ---
248
+
249
+ ## Contributing
250
+
251
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
252
+
253
+ ---
254
+
255
+ ## License
256
+
257
+ MIT License - See [LICENSE](LICENSE)
@@ -0,0 +1,213 @@
1
+ # AI Synapse — Free Multi-Provider AI SDK
2
+
3
+ [![Tests](https://img.shields.io/badge/tests-573%20passing-brightgreen)]()
4
+ [![Providers](https://img.shields.io/badge/providers-27%20enabled-blue)]()
5
+ [![Python](https://img.shields.io/badge/python-3.10%2B-3776AB)]()
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)]()
7
+ [![OpenAI Compatible](https://img.shields.io/badge/OpenAI-Compatible-412991)]()
8
+ [![Docker](https://img.shields.io/badge/Docker-Ready-2496ED)]()
9
+
10
+ > **Stop paying for AI inference.** Drop-in `from ai_engine import OpenAI` — routes through 27+ free providers with automatic failover and intelligent routing.
11
+
12
+ ---
13
+
14
+ ## Free Providers
15
+
16
+ ### No API Key Required (Truly Free)
17
+
18
+ | Provider | Model | Endpoint |
19
+ |----------|-------|----------|
20
+ | **Pollinations** | openai | `text.pollinations.ai/openai` |
21
+ | **Hermes** | Hermes-3-Llama | `hermes.ai.unturf.com/v1` |
22
+ | **G4F Groq** | llama-3.3-70b | `g4f.space/api/groq` |
23
+ | **G4F Gemini** | gemini-2.5-flash | `g4f.space/api/gemini` |
24
+ | **G4F NVIDIA** | nemotron-3 | `g4f.space/api/nvidia` |
25
+ | **OpenCode Zen** | north-mini-code | `opencode.ai/zen/v1` |
26
+
27
+ ### Free Tier APIs (Signup Required)
28
+
29
+ | Provider | Free Tier | Signup |
30
+ |----------|-----------|--------|
31
+ | **Groq** | 30 RPM, 14,400 RPD | [console.groq.com](https://console.groq.com) |
32
+ | **OpenRouter** | 23 free models | [openrouter.ai](https://openrouter.ai) |
33
+ | **Gemini** | 5-30 RPM | [aistudio.google.com](https://aistudio.google.com) |
34
+ | **NVIDIA** | 40 RPM | [build.nvidia.com](https://build.nvidia.com) |
35
+ | **Cerebras** | 30 RPM | [cloud.cerebras.ai](https://cloud.cerebras.ai) |
36
+ | **Cloudflare** | 10K neurons/day | [dash.cloudflare.com](https://dash.cloudflare.com) |
37
+ | **GitHub** | Varies | [github.com/marketplace](https://github.com/marketplace/models) |
38
+ | **Vercel** | $5/month free | [vercel.com](https://vercel.com) |
39
+ | **Cohere** | 20 RPM, 1K/month | [cohere.com](https://cohere.com) |
40
+ | **Mistral** | 1 RPS, 500K tokens/min | [console.mistral.ai](https://console.mistral.ai) |
41
+ | **HuggingFace** | $0.10/month | [huggingface.co](https://huggingface.co) |
42
+ | **Kilo** | Auto free routing | [app.kilo.ai](https://app.kilo.ai) |
43
+
44
+ ### Custom Providers (Your Keys)
45
+
46
+ | Provider | Models | Signup |
47
+ |----------|--------|--------|
48
+ | **hcnsec** | [Various](https://api.hcnsec.cn/pricing) | [api.hcnsec.cn](https://api.hcnsec.cn) |
49
+ | **LLM7** | [Various](https://docs.llm7.io/guides/models) | [llm7.io](https://llm7.io) |
50
+ | **PaxSenix** | [Various](https://api.paxsenix.org/v1/models) | [api.paxsenix.org](https://api.paxsenix.org) |
51
+
52
+ ### Self-Hosted Options
53
+
54
+ | Provider | Setup | Models |
55
+ |----------|-------|--------|
56
+ | **GPT4Free** | `docker run -p 8080:8080 hlohaus789/g4f` | GPT-4o, Claude, Gemini |
57
+ | **Ollama** | `curl -fsSL https://ollama.com/install.sh \| sh` | Llama, Mistral, etc. |
58
+
59
+ ---
60
+
61
+ ## Quick Start
62
+
63
+ ### Option 1: Free Tier APIs (Recommended)
64
+
65
+ ```bash
66
+ # 1. Copy environment template
67
+ cp .env.example .env
68
+
69
+ # 2. Get free API keys (see guide below)
70
+ # 3. Add keys to .env file
71
+ # 4. Start server
72
+ python server.py
73
+ ```
74
+
75
+ ### Option 2: Self-Hosted (No API Keys Needed)
76
+
77
+ ```bash
78
+ # Start g4f server
79
+ docker run -d -p 8080:8080 hlohaus789/g4f
80
+
81
+ # Start AI Engine
82
+ python server.py
83
+ ```
84
+
85
+ ---
86
+
87
+ ## For Developers
88
+
89
+ ### OpenAI SDK Compatible
90
+
91
+ ```python
92
+ from openai import OpenAI
93
+
94
+ client = OpenAI(
95
+ base_url="http://localhost:8000/v1",
96
+ api_key="dummy" # Not needed for free providers
97
+ )
98
+
99
+ # Chat completion
100
+ response = client.chat.completions.create(
101
+ model="gpt-4",
102
+ messages=[{"role": "user", "content": "Hello!"}]
103
+ )
104
+ print(response.choices[0].message.content)
105
+
106
+ # Streaming
107
+ stream = client.chat.completions.create(
108
+ model="gpt-4",
109
+ messages=[{"role": "user", "content": "Tell me a story"}],
110
+ stream=True
111
+ )
112
+ for chunk in stream:
113
+ if chunk.choices[0].delta.content:
114
+ print(chunk.choices[0].delta.content, end="")
115
+ ```
116
+
117
+ ### cURL
118
+
119
+ ```bash
120
+ curl http://localhost:8000/v1/chat/completions \
121
+ -H "Content-Type: application/json" \
122
+ -d '{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello!"}]}'
123
+ ```
124
+
125
+ ### JavaScript
126
+
127
+ ```javascript
128
+ import OpenAI from 'openai';
129
+
130
+ const client = new OpenAI({
131
+ baseURL: 'http://localhost:8000/v1',
132
+ apiKey: 'dummy'
133
+ });
134
+
135
+ const response = await client.chat.completions.create({
136
+ model: 'gpt-4',
137
+ messages: [{ role: 'user', content: 'Hello!' }]
138
+ });
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Features
144
+
145
+ ### Core
146
+ - OpenAI-compatible API with streaming
147
+ - Automatic provider failover
148
+ - Intelligent key rotation
149
+ - Response caching with TTL
150
+
151
+ ### Intelligence
152
+ - Task-based model selection
153
+ - Cost optimization
154
+ - Latency tracking
155
+ - A/B testing
156
+
157
+ ### Enterprise
158
+ - Multi-tenancy with quotas
159
+ - RBAC (Admin/User/Viewer)
160
+ - Audit logging
161
+ - Billing tracking
162
+
163
+ ### Platform
164
+ - Plugin system
165
+ - Workflow engine
166
+ - CLI tool
167
+ - Docker deployment
168
+
169
+ ---
170
+
171
+ ## API Endpoints
172
+
173
+ | Endpoint | Method | Description |
174
+ |----------|--------|-------------|
175
+ | `/v1/chat/completions` | POST | Chat completions (OpenAI-compatible, supports `stream: true`) |
176
+ | `/v1/models` | GET/POST | List all models |
177
+ | `/api/providers` | GET | List providers |
178
+ | `/api/health/{name}/ping` | POST | Live health ping for a provider |
179
+ | `/api/capabilities` | GET | Provider/model capabilities (vision, etc.) |
180
+ | `/api/status` | GET | Engine status |
181
+ | `/api/statistics` | GET | Usage statistics |
182
+ | `/health` | GET | Health check |
183
+ | `/metrics` | GET | Prometheus metrics |
184
+ | `/docs` | GET | Swagger UI (interactive API explorer) |
185
+ | `/redoc` | GET | ReDoc API documentation |
186
+
187
+ ### Rate Limit Headers
188
+
189
+ All API responses include:
190
+ - `X-RateLimit-Limit` — Max requests per minute
191
+ - `X-RateLimit-Remaining` — Remaining requests in current window
192
+
193
+ ---
194
+
195
+ ## Documentation
196
+
197
+ - [API Reference](docs/API.md)
198
+ - [User Guide](docs/USER_GUIDE.md)
199
+ - [Deployment Guide](docs/DEPLOYMENT.md)
200
+ - [Security Guide](docs/SECURITY.md)
201
+ - [Provider Setup](docs/collect_api.md)
202
+
203
+ ---
204
+
205
+ ## Contributing
206
+
207
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
208
+
209
+ ---
210
+
211
+ ## License
212
+
213
+ MIT License - See [LICENSE](LICENSE)
@@ -0,0 +1,25 @@
1
+ """AI Synapse SDK — Drop-in OpenAI & Anthropic compatibility with free multi-provider routing."""
2
+
3
+ __version__ = "4.0.0"
4
+
5
+ from .openai import OpenAI, AsyncOpenAI
6
+ from ._engine import AIEngine, get_engine, set_engine, _global_config
7
+ from ._exceptions import (
8
+ AIEngineError,
9
+ OpenAIError,
10
+ BadRequestError,
11
+ AuthenticationError,
12
+ RateLimitError,
13
+ InternalServerError,
14
+ NotFoundError,
15
+ )
16
+
17
+ # Lazy Anthropic import (not implemented yet)
18
+ try:
19
+ from .anthropic import Anthropic, AsyncAnthropic
20
+ except ImportError:
21
+ pass
22
+
23
+ def use(**kwargs):
24
+ """Configure global AI Engine settings (late configuration)."""
25
+ _global_config.update(kwargs)
@@ -0,0 +1,121 @@
1
+ """Shared AI Synapse engine singleton — initialized once, used by all SDK classes."""
2
+ import os
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Dict, Any, Optional
7
+
8
+ logger = logging.getLogger("ai_engine")
9
+
10
+ _global_config: Dict[str, Any] = {}
11
+ _engine_instance = None
12
+
13
+
14
+ def _load_config_json(config_path: str = None) -> Dict[str, Any]:
15
+ """Load config from JSON file."""
16
+ if config_path:
17
+ path = Path(config_path)
18
+ else:
19
+ # Default: config.json next to this package
20
+ path = Path(__file__).parent / "config.json"
21
+
22
+ if path.exists():
23
+ with open(path) as f:
24
+ return json.load(f)
25
+ return {}
26
+
27
+
28
+ def _resolve_config(config=None, cdn_config=None, **kwargs) -> Dict[str, Any]:
29
+ """Merge config from: JSON file → constructor args → env vars → defaults."""
30
+ # 1. Load from config.json
31
+ if isinstance(config, str):
32
+ base = _load_config_json(config)
33
+ elif isinstance(config, dict):
34
+ base = config.copy()
35
+ else:
36
+ base = _load_config_json()
37
+
38
+ # 2. Merge global config
39
+ base.update(_global_config)
40
+
41
+ # 3. Merge constructor kwargs
42
+ if "api_keys" in kwargs:
43
+ base.setdefault("api_keys", {}).update(kwargs["api_keys"])
44
+ for key in ("timeout", "max_retries", "default_provider"):
45
+ if key in kwargs:
46
+ base[key] = kwargs[key]
47
+ if cdn_config is not None:
48
+ base["cdn_config_url"] = cdn_config
49
+
50
+ # 4. Environment variable overrides
51
+ env_prefix = "AI_ENGINE_"
52
+ env_map = {
53
+ "AI_ENGINE_CDN_CONFIG": "cdn_config_url",
54
+ "AI_ENGINE_TIMEOUT": "timeout",
55
+ "AI_ENGINE_DEFAULT_PROVIDER": "default_provider",
56
+ }
57
+ for env_var, config_key in env_map.items():
58
+ val = os.environ.get(env_var)
59
+ if val is not None:
60
+ base[config_key] = int(val) if config_key == "timeout" else val
61
+
62
+ # 5. API key env vars: AI_ENGINE_API_KEY_{PROVIDER}
63
+ for env_key, env_val in os.environ.items():
64
+ if env_key.startswith("AI_ENGINE_API_KEY_"):
65
+ provider = env_key[len("AI_ENGINE_API_KEY_"):].lower()
66
+ base.setdefault("api_keys", {})[provider] = env_val
67
+
68
+ return base
69
+
70
+
71
+ def _init_engine(config: Dict[str, Any]):
72
+ """Initialize AI_engine from merged config."""
73
+ import sys
74
+ sys.path.insert(0, str(Path(__file__).parent.parent))
75
+ from core.ai_engine import AI_engine
76
+
77
+ # Apply provider overrides
78
+ engine = AI_engine(verbose=False)
79
+
80
+ # Set API keys from config
81
+ api_keys = config.get("api_keys", {})
82
+ for provider_name, key in api_keys.items():
83
+ if provider_name in engine.providers:
84
+ engine.providers[provider_name]["api_keys"] = [key]
85
+ engine.providers[provider_name]["enabled"] = True
86
+
87
+ # Apply provider priority/enable overrides
88
+ provider_overrides = config.get("providers", {})
89
+ for provider_name, overrides in provider_overrides.items():
90
+ if provider_name in engine.providers:
91
+ for k, v in overrides.items():
92
+ engine.providers[provider_name][k] = v
93
+
94
+ return engine
95
+
96
+
97
+ def get_engine(config=None, **kwargs):
98
+ """Get or create the shared engine singleton."""
99
+ global _engine_instance
100
+ if _engine_instance is None:
101
+ resolved = _resolve_config(config, **kwargs)
102
+ _engine_instance = _init_engine(resolved)
103
+ return _engine_instance
104
+
105
+
106
+ def set_engine(engine):
107
+ """Manually set the engine singleton."""
108
+ global _engine_instance
109
+ _engine_instance = engine
110
+
111
+
112
+ def reset_engine():
113
+ """Reset the engine (for testing)."""
114
+ global _engine_instance
115
+ _engine_instance = None
116
+
117
+
118
+ # Re-export for convenience
119
+ class AIEngine:
120
+ """Advanced AI Engine client with provider-specific features."""
121
+ pass