local-ai-runtime 0.1.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.
- local_ai_runtime-0.1.0/LICENSE +21 -0
- local_ai_runtime-0.1.0/PKG-INFO +29 -0
- local_ai_runtime-0.1.0/README.md +214 -0
- local_ai_runtime-0.1.0/pyproject.toml +40 -0
- local_ai_runtime-0.1.0/setup.cfg +4 -0
- local_ai_runtime-0.1.0/src/backend/__init__.py +0 -0
- local_ai_runtime-0.1.0/src/backend/controllers/__init__.py +0 -0
- local_ai_runtime-0.1.0/src/backend/controllers/chat_controller.py +42 -0
- local_ai_runtime-0.1.0/src/backend/controllers/model_controller.py +15 -0
- local_ai_runtime-0.1.0/src/backend/models/__init__.py +2 -0
- local_ai_runtime-0.1.0/src/backend/models/chat_message.py +80 -0
- local_ai_runtime-0.1.0/src/backend/models/model_config.py +145 -0
- local_ai_runtime-0.1.0/src/backend/routes/__init__.py +0 -0
- local_ai_runtime-0.1.0/src/backend/routes/chat.py +92 -0
- local_ai_runtime-0.1.0/src/backend/routes/config.py +75 -0
- local_ai_runtime-0.1.0/src/backend/routes/conversations.py +76 -0
- local_ai_runtime-0.1.0/src/backend/routes/metrics.py +11 -0
- local_ai_runtime-0.1.0/src/backend/routes/models.py +29 -0
- local_ai_runtime-0.1.0/src/backend/routes/status.py +24 -0
- local_ai_runtime-0.1.0/src/backend/server.py +41 -0
- local_ai_runtime-0.1.0/src/backend/services/__init__.py +0 -0
- local_ai_runtime-0.1.0/src/backend/services/conversation_service.py +76 -0
- local_ai_runtime-0.1.0/src/backend/services/inference_service.py +189 -0
- local_ai_runtime-0.1.0/src/backend/services/metrics_service.py +36 -0
- local_ai_runtime-0.1.0/src/backend/services/model_service.py +88 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime/__init__.py +2 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime/cli.py +31 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime/config.py +44 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime/server.py +68 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime.egg-info/PKG-INFO +29 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime.egg-info/SOURCES.txt +50 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime.egg-info/dependency_links.txt +1 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime.egg-info/entry_points.txt +2 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime.egg-info/requires.txt +30 -0
- local_ai_runtime-0.1.0/src/local_ai_runtime.egg-info/top_level.txt +3 -0
- local_ai_runtime-0.1.0/src/model_runtime/__init__.py +1 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/__init__.py +22 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/anthropic_backend.py +130 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/base.py +71 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/gemini_backend.py +133 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/llama_cpp.py +151 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/ollama.py +139 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/openai_backend.py +110 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/openai_compatible.py +117 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/registry.py +94 -0
- local_ai_runtime-0.1.0/src/model_runtime/backends/vllm.py +171 -0
- local_ai_runtime-0.1.0/src/model_runtime/chat_template_auto.py +78 -0
- local_ai_runtime-0.1.0/src/model_runtime/detector.py +219 -0
- local_ai_runtime-0.1.0/src/model_runtime/inference_engine.py +208 -0
- local_ai_runtime-0.1.0/src/model_runtime/model_loader.py +69 -0
- local_ai_runtime-0.1.0/src/model_runtime/prompt_formatter.py +149 -0
- local_ai_runtime-0.1.0/src/model_runtime/tokenizer_adapter.py +58 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Elie Khalil
|
|
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,29 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: local-ai-runtime
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local AI chat runtime — BYOK hybrid inference (local GGUF, ollama, vLLM, OpenAI, Anthropic, Gemini, any OpenAI-compatible)
|
|
5
|
+
Requires-Python: >=3.14
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: fastapi>=0.100.0
|
|
8
|
+
Requires-Dist: uvicorn>=0.20.0
|
|
9
|
+
Requires-Dist: pydantic>=2.0.0
|
|
10
|
+
Requires-Dist: httpx>=0.25.0
|
|
11
|
+
Provides-Extra: llama-cpp
|
|
12
|
+
Requires-Dist: llama-cpp-python>=0.2.0; extra == "llama-cpp"
|
|
13
|
+
Provides-Extra: ollama
|
|
14
|
+
Provides-Extra: vllm
|
|
15
|
+
Provides-Extra: openai
|
|
16
|
+
Requires-Dist: openai>=1.0.0; extra == "openai"
|
|
17
|
+
Provides-Extra: anthropic
|
|
18
|
+
Requires-Dist: anthropic>=0.20.0; extra == "anthropic"
|
|
19
|
+
Provides-Extra: gemini
|
|
20
|
+
Requires-Dist: google-generativeai>=0.3.0; extra == "gemini"
|
|
21
|
+
Provides-Extra: hf
|
|
22
|
+
Requires-Dist: huggingface-hub>=0.20.0; extra == "hf"
|
|
23
|
+
Provides-Extra: all
|
|
24
|
+
Requires-Dist: llama-cpp-python>=0.2.0; extra == "all"
|
|
25
|
+
Requires-Dist: openai>=1.0.0; extra == "all"
|
|
26
|
+
Requires-Dist: anthropic>=0.20.0; extra == "all"
|
|
27
|
+
Requires-Dist: google-generativeai>=0.3.0; extra == "all"
|
|
28
|
+
Requires-Dist: huggingface-hub>=0.20.0; extra == "all"
|
|
29
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
# local-ai-runtime
|
|
2
|
+
|
|
3
|
+
> BYOK hybrid local AI chat runtime — run any model from anywhere.
|
|
4
|
+
> Local GGUF (llama.cpp), Ollama, vLLM, OpenAI, Anthropic, Gemini, or any OpenAI-compatible endpoint.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Quick Start
|
|
9
|
+
|
|
10
|
+
### macOS (recommended via Homebrew)
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
brew install local-ai-runtime
|
|
14
|
+
local-ai-runtime
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
### Any platform (uvx)
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
uvx local-ai-runtime
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
On macOS, you'll be prompted to use Homebrew instead for better native performance.
|
|
24
|
+
|
|
25
|
+
### Development
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
git clone https://github.com/youruser/local-ai-runtime.git
|
|
29
|
+
cd local-ai-runtime
|
|
30
|
+
|
|
31
|
+
# Install dependencies with uv
|
|
32
|
+
uv sync
|
|
33
|
+
|
|
34
|
+
# Start the backend
|
|
35
|
+
uv run local-ai-runtime
|
|
36
|
+
|
|
37
|
+
# Start the frontend (separate terminal)
|
|
38
|
+
cd frontend && npm install && npm run dev
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## What This Is
|
|
44
|
+
|
|
45
|
+
A self-hosted AI chat application that supports **any inference backend** via BYOK (Bring Your Own Key):
|
|
46
|
+
|
|
47
|
+
| Backend | Type | Config |
|
|
48
|
+
|---------|------|--------|
|
|
49
|
+
| **llama-cpp** | Local GGUF | `model_file` in config |
|
|
50
|
+
| **Ollama** | Local | `ollama` running locally |
|
|
51
|
+
| **vLLM** | Local | `vllm serve` running |
|
|
52
|
+
| **OpenAI** | API (paid) | `OPENAI_API_KEY` env var |
|
|
53
|
+
| **Anthropic** | API (paid) | `ANTHROPIC_API_KEY` env var |
|
|
54
|
+
| **Gemini** | API (free tier) | `GEMINI_API_KEY` env var |
|
|
55
|
+
| **OpenAI-compatible** | API (any) | Any LiteLLM/LM Studio/etc. |
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## Architecture
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
┌─────────────────────────────────────────────────┐
|
|
63
|
+
│ FRONTEND │
|
|
64
|
+
│ Vite + React (dark theme chat UI) │
|
|
65
|
+
└────────────────────┬────────────────────────────┘
|
|
66
|
+
│ HTTP + SSE
|
|
67
|
+
▼
|
|
68
|
+
┌─────────────────────────────────────────────────┐
|
|
69
|
+
│ BACKEND API │
|
|
70
|
+
│ FastAPI (Python) │
|
|
71
|
+
│ Routes: /chat /chat/stream /models /config │
|
|
72
|
+
└────────────────────┬────────────────────────────┘
|
|
73
|
+
│
|
|
74
|
+
▼
|
|
75
|
+
┌─────────────────────────────────────────────────┐
|
|
76
|
+
│ BYOK BACKEND SYSTEM │
|
|
77
|
+
│ ┌───────────┐ ┌─────────┐ ┌─────────────────┐ │
|
|
78
|
+
│ │ llama-cpp │ │ ollama │ │ openai/anthropic│
|
|
79
|
+
│ └───────────┘ └─────────┘ └─────────────────┘ │
|
|
80
|
+
│ ┌─────────┐ ┌───────┐ ┌────────────────────┐ │
|
|
81
|
+
│ │ vLLM │ │ gemini│ │ openai_compatible │ │
|
|
82
|
+
│ └─────────┘ └───────┘ └────────────────────┘ │
|
|
83
|
+
└─────────────────────────────────────────────────┘
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Configuration
|
|
89
|
+
|
|
90
|
+
All configuration lives in `config/`. **Zero hardcoded values.**
|
|
91
|
+
|
|
92
|
+
### server.config.json
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
{
|
|
96
|
+
"host": "0.0.0.0",
|
|
97
|
+
"port": 8000,
|
|
98
|
+
"log_level": "info",
|
|
99
|
+
"cors_origins": ["http://localhost:5173"],
|
|
100
|
+
"models_dir": "./models"
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### model.config.json
|
|
105
|
+
|
|
106
|
+
```json
|
|
107
|
+
{
|
|
108
|
+
"backend_type": "llama-cpp",
|
|
109
|
+
"model_file": "mistral-7b-instruct.Q4_K_M.gguf",
|
|
110
|
+
"chat_template": "auto",
|
|
111
|
+
"context_length": 4096,
|
|
112
|
+
"system_prompt": "You are a helpful assistant.",
|
|
113
|
+
"generation": {
|
|
114
|
+
"temperature": 0.7,
|
|
115
|
+
"max_new_tokens": 512
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Set `backend_type` to any supported backend. For API backends, configure in `api_backends` section and set the corresponding API key environment variable.
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Model Detection
|
|
125
|
+
|
|
126
|
+
Models are auto-detected from GGUF metadata:
|
|
127
|
+
|
|
128
|
+
- Architecture (llama, mistral, phi, qwen, etc.)
|
|
129
|
+
- Chat template (auto-mapped from architecture)
|
|
130
|
+
- Context length
|
|
131
|
+
- Quantization level
|
|
132
|
+
- Parameter count
|
|
133
|
+
|
|
134
|
+
No manual configuration needed — drop a `.gguf` file in `models/` and it works.
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Chat Templates
|
|
139
|
+
|
|
140
|
+
Chat templates are auto-detected from:
|
|
141
|
+
|
|
142
|
+
1. **Model metadata** — GGUF files contain architecture info that maps to templates
|
|
143
|
+
2. **Conversation patterns** — the system detects `[INST]`, `<|im_start|>`, etc. from messages
|
|
144
|
+
|
|
145
|
+
Supported templates: `chatml`, `llama3`, `llama2`, `mistral`, `alpaca`, `raw`, or `auto`.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## API Endpoints
|
|
150
|
+
|
|
151
|
+
| Method | Path | Description |
|
|
152
|
+
|--------|------|-------------|
|
|
153
|
+
| `GET` | `/status` | Health check, model state |
|
|
154
|
+
| `GET` | `/models` | List available model files |
|
|
155
|
+
| `GET` | `/models/detect` | Auto-detect model metadata |
|
|
156
|
+
| `GET` | `/config` | Get active configuration |
|
|
157
|
+
| `PUT` | `/config` | Update configuration |
|
|
158
|
+
| `GET` | `/config/backends` | List available backends |
|
|
159
|
+
| `POST` | `/chat` | Send message, get response |
|
|
160
|
+
| `POST` | `/chat/stream` | Stream response (SSE) |
|
|
161
|
+
| `GET` | `/conversations` | List conversations |
|
|
162
|
+
| `POST` | `/conversations` | Create conversation |
|
|
163
|
+
| `GET` | `/metrics` | Performance metrics |
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## Directory Structure
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
local-ai-runtime/
|
|
171
|
+
├── local_ai_runtime/ # New CLI + config system
|
|
172
|
+
│ ├── cli.py # Entry point (uvx local-ai-runtime)
|
|
173
|
+
│ ├── config.py # Config loader
|
|
174
|
+
│ └── server.py # FastAPI app factory
|
|
175
|
+
├── backend/ # API routes + services
|
|
176
|
+
│ ├── routes/ # FastAPI routers
|
|
177
|
+
│ ├── services/ # Business logic
|
|
178
|
+
│ ├── controllers/ # Request handlers
|
|
179
|
+
│ └── models/ # Data classes
|
|
180
|
+
├── model_runtime/ # Inference layer
|
|
181
|
+
│ ├── backends/ # BYOK adapter system
|
|
182
|
+
│ │ ├── base.py # Abstract Backend interface
|
|
183
|
+
│ │ ├── registry.py # Dynamic backend loading
|
|
184
|
+
│ │ ├── llama_cpp.py # llama.cpp backend
|
|
185
|
+
│ │ ├── ollama.py # Ollama backend
|
|
186
|
+
│ │ ├── vllm.py # vLLM backend
|
|
187
|
+
│ │ ├── openai_backend.py # OpenAI API
|
|
188
|
+
│ │ ├── anthropic_backend.py # Anthropic API
|
|
189
|
+
│ │ ├── gemini_backend.py # Google Gemini
|
|
190
|
+
│ │ └── openai_compatible.py # Any OpenAI-compatible
|
|
191
|
+
│ ├── detector.py # GGUF metadata detection
|
|
192
|
+
│ ├── chat_template_auto.py # Auto chat template
|
|
193
|
+
│ ├── prompt_formatter.py # Template formatting
|
|
194
|
+
│ └── inference_engine.py # Legacy engine wrapper
|
|
195
|
+
├── frontend/ # Vite + React UI
|
|
196
|
+
│ ├── app.jsx # Root component
|
|
197
|
+
│ ├── components/ # ChatWindow, InputBar, ModelSelector
|
|
198
|
+
│ └── styles/ # Dark theme CSS
|
|
199
|
+
├── config/ # JSON config files
|
|
200
|
+
├── models/ # GGUF files (gitignored)
|
|
201
|
+
├── huggingface/ # HF download support
|
|
202
|
+
├── pyproject.toml # uv project config
|
|
203
|
+
└── .python-version # Python 3.12
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## Requirements
|
|
209
|
+
|
|
210
|
+
- Python 3.11+
|
|
211
|
+
- Node.js 18+ (for frontend)
|
|
212
|
+
- uv (package manager)
|
|
213
|
+
- For local inference: llama-cpp-python, ollama, or vllm
|
|
214
|
+
- For API inference: API keys as environment variables
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "local-ai-runtime"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Local AI chat runtime — BYOK hybrid inference (local GGUF, ollama, vLLM, OpenAI, Anthropic, Gemini, any OpenAI-compatible)"
|
|
5
|
+
requires-python = ">=3.14"
|
|
6
|
+
dependencies = [
|
|
7
|
+
"fastapi>=0.100.0",
|
|
8
|
+
"uvicorn>=0.20.0",
|
|
9
|
+
"pydantic>=2.0.0",
|
|
10
|
+
"httpx>=0.25.0",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
llama-cpp = ["llama-cpp-python>=0.2.0"]
|
|
15
|
+
ollama = []
|
|
16
|
+
vllm = []
|
|
17
|
+
openai = ["openai>=1.0.0"]
|
|
18
|
+
anthropic = ["anthropic>=0.20.0"]
|
|
19
|
+
gemini = ["google-generativeai>=0.3.0"]
|
|
20
|
+
hf = ["huggingface-hub>=0.20.0"]
|
|
21
|
+
all = [
|
|
22
|
+
"llama-cpp-python>=0.2.0",
|
|
23
|
+
"openai>=1.0.0",
|
|
24
|
+
"anthropic>=0.20.0",
|
|
25
|
+
"google-generativeai>=0.3.0",
|
|
26
|
+
"huggingface-hub>=0.20.0",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
local-ai-runtime = "src.local_ai_runtime.cli:main"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["src"]
|
|
34
|
+
include = ["local_ai_runtime*", "model_runtime*", "backend*"]
|
|
35
|
+
|
|
36
|
+
[dependency-groups]
|
|
37
|
+
dev = [
|
|
38
|
+
"ruff>=0.1.0",
|
|
39
|
+
"pytest>=7.0.0",
|
|
40
|
+
]
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Controller for chat request handling."""
|
|
2
|
+
|
|
3
|
+
from fastapi import HTTPException
|
|
4
|
+
|
|
5
|
+
from services.inference_service import generate_response, InferenceError
|
|
6
|
+
from models.chat_message import ChatMessage, Role
|
|
7
|
+
from services.conversation_service import get_conversation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def handle_chat_request(request) -> dict:
|
|
11
|
+
user_message = ChatMessage(role=Role.USER, content=request.message)
|
|
12
|
+
|
|
13
|
+
conversation_history = None
|
|
14
|
+
if request.conversation_id:
|
|
15
|
+
conv = get_conversation(request.conversation_id)
|
|
16
|
+
if conv:
|
|
17
|
+
conversation_history = [
|
|
18
|
+
ChatMessage(role=Role(m["role"]), content=m["content"])
|
|
19
|
+
for m in conv["messages"]
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
result = await generate_response(
|
|
24
|
+
message=user_message,
|
|
25
|
+
conversation_id=request.conversation_id,
|
|
26
|
+
conversation_history=conversation_history,
|
|
27
|
+
)
|
|
28
|
+
except InferenceError as e:
|
|
29
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
30
|
+
|
|
31
|
+
# Auto-save user message and assistant response to conversation
|
|
32
|
+
if request.conversation_id:
|
|
33
|
+
from services.conversation_service import add_message_to_conversation
|
|
34
|
+
add_message_to_conversation(request.conversation_id, "user", request.message)
|
|
35
|
+
add_message_to_conversation(request.conversation_id, "assistant", result.content)
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
"response": result.content,
|
|
39
|
+
"model": result.model_name,
|
|
40
|
+
"tokens_used": result.tokens_used,
|
|
41
|
+
"finish_reason": result.finish_reason,
|
|
42
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Controller for model management request handling."""
|
|
2
|
+
|
|
3
|
+
from services.model_service import scan_model_directory, get_active_config
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def list_available_models() -> dict:
|
|
7
|
+
models = scan_model_directory()
|
|
8
|
+
return {"models": models}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_active_model() -> dict:
|
|
12
|
+
config = get_active_config()
|
|
13
|
+
if config is None:
|
|
14
|
+
return {"active_model": None}
|
|
15
|
+
return config.to_dict()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# backend/models/chat_message.py
|
|
2
|
+
#
|
|
3
|
+
# Data model for a single chat message.
|
|
4
|
+
#
|
|
5
|
+
# STATUS: DEFINED — This can be used now even before inference works.
|
|
6
|
+
# It's a plain data class with no dependencies.
|
|
7
|
+
#
|
|
8
|
+
# Usage:
|
|
9
|
+
# from models.chat_message import ChatMessage, Role
|
|
10
|
+
# msg = ChatMessage(role=Role.USER, content="Hello!")
|
|
11
|
+
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Role(str, Enum):
|
|
17
|
+
"""
|
|
18
|
+
The role of the entity producing a message.
|
|
19
|
+
Mirrors the convention used in most chat template formats.
|
|
20
|
+
"""
|
|
21
|
+
SYSTEM = "system"
|
|
22
|
+
USER = "user"
|
|
23
|
+
ASSISTANT = "assistant"
|
|
24
|
+
|
|
25
|
+
# Future: tool call results
|
|
26
|
+
# TOOL = "tool"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ChatMessage:
|
|
30
|
+
"""
|
|
31
|
+
Represents a single message in a conversation.
|
|
32
|
+
|
|
33
|
+
Attributes:
|
|
34
|
+
role (Role) — Who produced this message
|
|
35
|
+
content (str) — The text content
|
|
36
|
+
timestamp (datetime) — When this message was created (UTC)
|
|
37
|
+
id (str|None) — Optional unique ID for this message
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, role: Role, content: str, timestamp: datetime | None = None, id: str | None = None):
|
|
41
|
+
self.role = role
|
|
42
|
+
self.content = content
|
|
43
|
+
self.timestamp = timestamp or datetime.now(timezone.utc)
|
|
44
|
+
self.id = id
|
|
45
|
+
|
|
46
|
+
def to_dict(self) -> dict:
|
|
47
|
+
return {
|
|
48
|
+
"role": self.role.value,
|
|
49
|
+
"content": self.content,
|
|
50
|
+
"timestamp": self.timestamp.isoformat(),
|
|
51
|
+
"id": self.id,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
def __repr__(self) -> str:
|
|
55
|
+
preview = self.content[:60] + "..." if len(self.content) > 60 else self.content
|
|
56
|
+
return f"ChatMessage(role={self.role.value}, content='{preview}')"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Conversation:
|
|
60
|
+
"""
|
|
61
|
+
A list of ChatMessages forming a conversation thread.
|
|
62
|
+
|
|
63
|
+
TODO (Phase 4.1): Add persistence, conversation ID, title generation.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, id: str | None = None):
|
|
67
|
+
self.id = id
|
|
68
|
+
self.messages: list[ChatMessage] = []
|
|
69
|
+
|
|
70
|
+
def add_message(self, message: ChatMessage) -> None:
|
|
71
|
+
self.messages.append(message)
|
|
72
|
+
|
|
73
|
+
def get_messages(self) -> list[ChatMessage]:
|
|
74
|
+
return self.messages
|
|
75
|
+
|
|
76
|
+
def to_dict(self) -> dict:
|
|
77
|
+
return {
|
|
78
|
+
"id": self.id,
|
|
79
|
+
"messages": [m.to_dict() for m in self.messages],
|
|
80
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Data models for model configuration and inference I/O."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
CHAT_TEMPLATES = {
|
|
8
|
+
"auto",
|
|
9
|
+
"chatml",
|
|
10
|
+
"llama3",
|
|
11
|
+
"llama2",
|
|
12
|
+
"mistral",
|
|
13
|
+
"alpaca",
|
|
14
|
+
"raw",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
BACKEND_TYPES = {
|
|
18
|
+
"llama-cpp",
|
|
19
|
+
"ollama",
|
|
20
|
+
"vllm",
|
|
21
|
+
"openai",
|
|
22
|
+
"anthropic",
|
|
23
|
+
"gemini",
|
|
24
|
+
"openai_compatible",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class GenerationParams:
|
|
30
|
+
"""Parameters controlling text generation."""
|
|
31
|
+
temperature: float = 0.7
|
|
32
|
+
top_p: float = 0.9
|
|
33
|
+
top_k: int = 40
|
|
34
|
+
repeat_penalty: float = 1.1
|
|
35
|
+
max_new_tokens: int = 512
|
|
36
|
+
min_new_tokens: int = 1
|
|
37
|
+
seed: int = -1
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> dict:
|
|
40
|
+
return {
|
|
41
|
+
"temperature": self.temperature,
|
|
42
|
+
"top_p": self.top_p,
|
|
43
|
+
"top_k": self.top_k,
|
|
44
|
+
"repeat_penalty": self.repeat_penalty,
|
|
45
|
+
"max_new_tokens": self.max_new_tokens,
|
|
46
|
+
"min_new_tokens": self.min_new_tokens,
|
|
47
|
+
"seed": self.seed,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class ModelConfig:
|
|
53
|
+
"""Complete configuration for one model — all from config, no hardcoded defaults."""
|
|
54
|
+
model_file: str = ""
|
|
55
|
+
backend_type: str = "llama-cpp"
|
|
56
|
+
chat_template: str = "auto"
|
|
57
|
+
context_length: int = 4096
|
|
58
|
+
system_prompt: str = "You are a helpful assistant."
|
|
59
|
+
n_gpu_layers: int = 0
|
|
60
|
+
generation: GenerationParams = field(default_factory=GenerationParams)
|
|
61
|
+
profile_name: Optional[str] = None
|
|
62
|
+
models_dir: str = "./models"
|
|
63
|
+
# API backend overrides
|
|
64
|
+
openai_model: str = ""
|
|
65
|
+
anthropic_model: str = ""
|
|
66
|
+
gemini_model: str = ""
|
|
67
|
+
ollama_model: str = ""
|
|
68
|
+
vllm_model: str = ""
|
|
69
|
+
compatible_model: str = ""
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict:
|
|
72
|
+
return {
|
|
73
|
+
"profile_name": self.profile_name,
|
|
74
|
+
"backend_type": self.backend_type,
|
|
75
|
+
"model_file": self.model_file,
|
|
76
|
+
"chat_template": self.chat_template,
|
|
77
|
+
"context_length": self.context_length,
|
|
78
|
+
"system_prompt": self.system_prompt,
|
|
79
|
+
"n_gpu_layers": self.n_gpu_layers,
|
|
80
|
+
"models_dir": self.models_dir,
|
|
81
|
+
"generation": self.generation.to_dict(),
|
|
82
|
+
"openai_model": self.openai_model,
|
|
83
|
+
"anthropic_model": self.anthropic_model,
|
|
84
|
+
"gemini_model": self.gemini_model,
|
|
85
|
+
"ollama_model": self.ollama_model,
|
|
86
|
+
"vllm_model": self.vllm_model,
|
|
87
|
+
"compatible_model": self.compatible_model,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
@classmethod
|
|
91
|
+
def from_dict(cls, data: dict) -> "ModelConfig":
|
|
92
|
+
gen_data = data.get("generation", {})
|
|
93
|
+
generation = GenerationParams(
|
|
94
|
+
temperature=gen_data.get("temperature", 0.7),
|
|
95
|
+
top_p=gen_data.get("top_p", 0.9),
|
|
96
|
+
top_k=gen_data.get("top_k", 40),
|
|
97
|
+
repeat_penalty=gen_data.get("repeat_penalty", 1.1),
|
|
98
|
+
max_new_tokens=gen_data.get("max_new_tokens", 512),
|
|
99
|
+
seed=gen_data.get("seed", -1),
|
|
100
|
+
)
|
|
101
|
+
return cls(
|
|
102
|
+
model_file=data.get("model_file", ""),
|
|
103
|
+
backend_type=data.get("backend_type", "llama-cpp"),
|
|
104
|
+
chat_template=data.get("chat_template", "auto"),
|
|
105
|
+
context_length=data.get("context_length", 4096),
|
|
106
|
+
system_prompt=data.get("system_prompt", "You are a helpful assistant."),
|
|
107
|
+
n_gpu_layers=data.get("n_gpu_layers", 0),
|
|
108
|
+
generation=generation,
|
|
109
|
+
profile_name=data.get("profile_name"),
|
|
110
|
+
models_dir=data.get("models_dir", "./models"),
|
|
111
|
+
openai_model=data.get("openai_model", ""),
|
|
112
|
+
anthropic_model=data.get("anthropic_model", ""),
|
|
113
|
+
gemini_model=data.get("gemini_model", ""),
|
|
114
|
+
ollama_model=data.get("ollama_model", ""),
|
|
115
|
+
vllm_model=data.get("vllm_model", ""),
|
|
116
|
+
compatible_model=data.get("compatible_model", ""),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class InferenceRequest:
|
|
122
|
+
"""Internal representation of an inference request."""
|
|
123
|
+
prompt: str
|
|
124
|
+
system_prompt: str = ""
|
|
125
|
+
max_tokens: int = 512
|
|
126
|
+
temperature: float = 0.7
|
|
127
|
+
top_p: float = 0.9
|
|
128
|
+
top_k: int = 40
|
|
129
|
+
repeat_penalty: float = 1.1
|
|
130
|
+
seed: int = -1
|
|
131
|
+
stop_tokens: list[str] = field(default_factory=list)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass
|
|
135
|
+
class InferenceResponse:
|
|
136
|
+
"""Internal representation of an inference response."""
|
|
137
|
+
text: str
|
|
138
|
+
tokens_prompt: int = 0
|
|
139
|
+
tokens_generated: int = 0
|
|
140
|
+
finish_reason: str = "stop"
|
|
141
|
+
model_name: str = ""
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def tokens_used(self) -> int:
|
|
145
|
+
return self.tokens_prompt + self.tokens_generated
|
|
File without changes
|