-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
319 lines (260 loc) · 11.1 KB
/
server.py
File metadata and controls
319 lines (260 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
from __future__ import annotations
import base64
import glob
import json
import logging
import os
import subprocess
from typing import Optional
import ollama
import requests
from dotenv import load_dotenv
from flask import Flask, abort, jsonify, request
from opentelemetry import metrics, trace
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from .redis_helper import REDIS_CONNECTION
# Configure logger
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s - %(message)s')
logger = logging.getLogger('ai-server')
# Load environment variables from .env file
load_dotenv()
# OpenTelemetry endpoint configuration
OTEL_EXPORTER_OTLP_ENDPOINT = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4317')
# Configure OpenTelemetry - Shared Resource (identifies this service)
resource = Resource.create({"service.name": "ai-server"})
# ========== TRACES CONFIGURATION ==========
# TracerProvider: Factory for creating tracers (for distributed tracing)
tracer_provider = TracerProvider(resource=resource)
# OTLP Trace Exporter: Sends traces to collector
otlp_trace_exporter = OTLPSpanExporter(endpoint=OTEL_EXPORTER_OTLP_ENDPOINT, insecure=True)
span_processor = BatchSpanProcessor(otlp_trace_exporter)
tracer_provider.add_span_processor(span_processor)
# Set the global tracer provider (FlaskInstrumentor will use this)
trace.set_tracer_provider(tracer_provider)
tracer = trace.get_tracer("ai-server.tracer")
# ========== METRICS CONFIGURATION ==========
# OTLP Metric Exporter: Sends metrics to collector
otlp_metric_exporter = OTLPMetricExporter(endpoint=OTEL_EXPORTER_OTLP_ENDPOINT, insecure=True)
# PeriodicExportingMetricReader: Collects and exports metrics every 10 seconds
metric_reader = PeriodicExportingMetricReader(
exporter=otlp_metric_exporter, export_interval_millis=10000 # Export every 10 seconds
)
# MeterProvider: Factory for creating meters (for metrics collection)
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
# Set the global meter provider (FlaskInstrumentor will use this for HTTP metrics)
metrics.set_meter_provider(meter_provider)
app = Flask('AI server')
FlaskInstrumentor().instrument_app(app)
# Configuration from environment variables
DEFAULT_MODEL = os.getenv('DEFAULT_MODEL', 'deepseek-coder-v2:latest')
# Llama.cpp configuration
LLAMA_CPP_CLI = os.getenv('LLAMA_CPP_CLI', '/data1/llama.cpp/bin/llama-cli')
GGUF_DIR = os.getenv('GGUF_DIR', '/data1/GGUF')
# Llama server configuration
# e.g., http://localhost:8080 or localhost:8080
_llama_server_url = os.getenv('LLAMA_SERVER_URL')
LLAMA_SERVER_URL = (
f"http://{_llama_server_url}"
if _llama_server_url and not _llama_server_url.startswith(('http://', 'https://'))
else _llama_server_url
)
SCHEMA_KEY = "schema"
def _build_messages(content: str, system_prompt: Optional[str] = None, image_files: Optional[list] = None) -> list:
"""Build messages list with optional system prompt."""
messages = []
if system_prompt:
messages.append({'role': 'system', 'content': system_prompt})
messages.append({'role': 'user', 'content': content})
if image_files:
messages[-1]["images"] = [base64.b64encode(image_file.read()).decode("utf-8") for image_file in image_files]
return messages
def chat_with_llama_server_http(
model: str,
content: str,
system_prompt: Optional[str] = None,
timeout: int = 300,
image_files: Optional[list] = None,
json_schema: Optional[dict] = None,
model_options: Optional[dict] = None,
) -> str:
"""Handle chat using llama-server HTTP API."""
if not LLAMA_SERVER_URL:
raise Exception("LLAMA_SERVER_URL environment variable not set")
try:
messages = _build_messages(content, system_prompt, image_files=[]) # TODO: Pass image files
if not model_options:
model_options = {}
payload = {'model': model, 'messages': messages, **model_options}
if json_schema:
payload['json_schema'] = json_schema[SCHEMA_KEY]
if 'stream' not in payload:
payload['stream'] = False
response = requests.post(
f'{LLAMA_SERVER_URL}/v1/chat/completions',
json=payload,
headers={'Content-Type': 'application/json'},
timeout=timeout,
)
if response.status_code == 200:
data = response.json()
if 'choices' in data and len(data['choices']) > 0:
return data['choices'][0]['message']['content']
else:
raise Exception("Invalid response format from llama-server")
else:
raise Exception(f"Llama-server HTTP error")
except requests.Timeout:
raise Exception(f"Llama-server request timed out for model {model}")
except requests.RequestException as e:
raise Exception(f"Llama-server request failed: {str(e)}")
def resolve_model_path(model: str) -> Optional[str]:
"""Resolve model name to full GGUF file path using glob pattern."""
pattern = os.path.join(GGUF_DIR, model, "*.gguf")
matches = glob.glob(pattern)
return matches[0] if matches else None
def is_llamacpp_available(model: str) -> bool:
"""Check if model is available in llama.cpp."""
return resolve_model_path(model) is not None
def chat_with_ollama(
model: str,
content: str,
system_prompt: Optional[str] = None,
image_files: Optional[list] = None,
json_schema: Optional[dict] = None,
model_options: Optional[dict] = None,
) -> str:
"""Handle chat using ollama."""
messages = _build_messages(content, system_prompt, image_files)
response = ollama.chat(
model=model,
messages=messages,
stream=False,
format=json_schema[SCHEMA_KEY] if json_schema else None,
options=model_options,
)
return response.message.content
def chat_with_llamacpp(
model: str,
content: str,
system_prompt: Optional[str] = None,
timeout: int = 300,
image_files: Optional[list] = None,
model_options: Optional[dict] = None,
json_schema: Optional[dict] = None,
) -> str:
"""Handle chat using llama.cpp CLI."""
model_path = resolve_model_path(model)
if not model_path:
raise ValueError(f"Model not found: {model}")
cmd = [LLAMA_CPP_CLI, '-m', model_path, '--n-gpu-layers', '40', '-p', content, '-n', '512', '--single-turn']
if json_schema:
raw_schema = json_schema[SCHEMA_KEY] if SCHEMA_KEY in json_schema else json_schema
cmd += ["--json-schema", json.dumps(raw_schema)]
# Add system prompt if provided
if system_prompt:
cmd.extend(['--system-prompt', system_prompt])
if model_options:
for key, value in model_options.items():
cmd.extend(['--model-option', key, value])
if image_files:
pass # TODO: pass image files
try:
result = subprocess.run(cmd, capture_output=True, text=False, timeout=timeout, check=True)
stdout_text = result.stdout.decode('utf-8', errors='replace')
# Strip whitespace and return the response
response = stdout_text.strip()
return response if response else "No response generated."
except subprocess.TimeoutExpired:
raise Exception(f"Llama.cpp request timed out for model {model}")
except subprocess.CalledProcessError as e:
stderr_text = ""
if e.stderr:
stderr_text = e.stderr.decode('utf-8', errors='replace')
raise Exception(f"Llama.cpp failed for {model}: {stderr_text.strip() if stderr_text else 'Unknown error'}")
except FileNotFoundError:
raise Exception("Llama.cpp CLI not found")
def chat_with_model(
model: str,
content: str,
llama_mode: str = "cli",
system_prompt: Optional[str] = None,
image_files: Optional[list] = None,
model_options: Optional[dict] = None,
json_schema: Optional[dict] = None,
) -> str:
"""Route chat request based on llama_mode: server (external), cli, or ollama fallback; and with optional system prompt."""
if is_llamacpp_available(model):
if llama_mode == "server":
if not LLAMA_SERVER_URL:
raise Exception("LLAMA_SERVER_URL environment variable not set for server mode")
return chat_with_llama_server_http(
model,
content,
system_prompt=system_prompt,
image_files=image_files,
json_schema=json_schema,
model_options=model_options,
)
elif llama_mode == "cli":
return chat_with_llamacpp(
model,
content,
system_prompt=system_prompt,
image_files=image_files,
json_schema=json_schema,
model_options=model_options,
)
else:
raise ValueError(f"Invalid llama_mode: '{llama_mode}'. Valid options are 'server' or 'cli'.")
else:
# Model not available in llama.cpp, use ollama
return chat_with_ollama(
model,
content,
system_prompt=system_prompt,
image_files=image_files,
json_schema=json_schema,
model_options=model_options,
)
def authenticate() -> str:
"""Authenticate the given request using an API key."""
api_key = request.headers.get('X-API-KEY')
client_ip = request.remote_addr
endpoint = request.path
if not api_key:
logger.warning(f"Missing API key from {client_ip} at {endpoint}")
abort(401, description="Missing API key")
user = REDIS_CONNECTION.get(f"api-key:{api_key}")
if not user:
logger.warning(f"Invalid API key attempt from {client_ip} at {endpoint}")
abort(401, description="Invalid API key")
return user
@app.route('/chat', methods=['POST'])
def chat():
"""Handle chat request with optional llama_mode and system prompt parameters."""
authenticate()
model = request.form.get('model', DEFAULT_MODEL)
content = request.form.get('content', '')
llama_mode = request.form.get('llama_mode', 'cli')
system_prompt = request.form.get('system_prompt')
image_files = list(request.files.values())
model_options = request.form.get('model_options')
json_schema = request.form.get('json_schema')
if json_schema:
json_schema = json.loads(json_schema)
if not content.strip():
abort(400, description='Missing prompt content')
response_content = chat_with_model(
model, content, llama_mode, system_prompt, image_files, model_options=model_options, json_schema=json_schema
)
return jsonify(response_content)
@app.errorhandler(Exception)
def internal_error(error):
return jsonify({"error": str(error)}), 500