mk2878d commited on
Commit
a4a3d2d
·
verified ·
1 Parent(s): 0eff59a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +239 -67
app.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  import ast
4
  import asyncio
 
5
  import json
6
  import math
7
  import os
@@ -13,6 +14,7 @@ import tarfile
13
  import tempfile
14
  import threading
15
  import time
 
16
  import urllib.parse
17
  import urllib.request
18
  import uuid
@@ -60,7 +62,7 @@ GENERATIONS_DIR = DATA_DIR / "generations"
60
  GENERATIONS_DIR.mkdir(parents=True, exist_ok=True)
61
 
62
  # مجلد عمل مؤقت لأدوات الكود فقط — ليس جزءًا من التخزين الدائم أبدًا.
63
- SANDBOX_DIR = Path(tempfile.gettempdir()) / "llm_tool_sandbox"
64
  SANDBOX_DIR.mkdir(parents=True, exist_ok=True)
65
 
66
 
@@ -110,11 +112,11 @@ def build_latest_llama_server():
110
 
111
  if not os.path.exists("llama.cpp"):
112
  subprocess.run(["git", "clone", "https://github.com/unslothai/llama.cpp.git"], check=True)
113
- else:
114
- subprocess.run(["git", "pull"], cwd="llama.cpp", check=True)
115
 
116
- subprocess.run(["git", "fetch", "origin", "pull/144/head:mtp"], cwd="llama.cpp", check=True)
117
- subprocess.run(["git", "checkout", "mtp"], cwd="llama.cpp", check=True)
 
 
118
 
119
  env = os.environ.copy()
120
  if "/usr/local/cuda/bin" not in env.get("PATH", ""):
@@ -153,29 +155,48 @@ def _spawn_llama_process() -> subprocess.Popen:
153
  return process
154
 
155
 
156
- def monitor_llama_server(poll_interval: float = 5.0) -> None:
157
  """مراقبة داخلية للحاوية تعمل في خيط خلفي طوال عمر العملية: تتحقق دوريًا من
158
  أن llama-server حيّ ويستجيب على المنفذ، وإن توقف (انهيار/تعليق) تعيد
159
- تشغيله تلقائيًا بنفس الأمر والبيئة دون إعادة تنزيل النموذج، حتى تستطيع
160
- الطلبات الجارية/القادمة أن تُكمل الحصول على رد من النموذج بدل أن تتعطل
161
- نهائيًا."""
162
- consecutive_failures = 0
 
 
 
 
 
 
 
 
163
  while True:
164
  time.sleep(poll_interval)
165
  with _llama_process_lock:
166
  proc = _llama_process
167
- alive = proc is not None and proc.poll() is None
168
- if alive and not _is_llama_server_up(timeout=2.0):
169
- alive = False
170
- if alive:
171
- consecutive_failures = 0
 
 
 
 
 
 
 
 
 
 
172
  continue
173
 
174
- consecutive_failures += 1
175
- backoff = min(30, 2 ** consecutive_failures)
176
- print(f"[monitor] llama-server غير سليم (محاولة فشل رقم {consecutive_failures})؛ "
177
- f"إعادة التشغيل خلال {backoff}ث...")
178
- time.sleep(backoff)
 
179
  try:
180
  if proc is not None and proc.poll() is None:
181
  proc.kill()
@@ -184,14 +205,12 @@ def monitor_llama_server(poll_interval: float = 5.0) -> None:
184
  print(f"[monitor] تعذر إيقاف العملية القديمة: {e}")
185
  try:
186
  _spawn_llama_process()
187
- time.sleep(5)
188
- if _is_llama_server_up(timeout=5.0):
189
- print("[monitor] تمت إعادة تشغيل llama-server بنجاح.")
190
- consecutive_failures = 0
191
- else:
192
- print("[monitor] العملية بدأت لكن المنفذ لم يستجب بعد؛ ستُعاد المحاولة.")
193
  except Exception as e:
194
  print(f"[monitor] فشلت محاولة إعادة التشغيل: {e}")
 
 
 
195
 
196
 
197
  def start_llama_server():
@@ -289,6 +308,18 @@ def _safe_sandbox_path(user_path: str) -> Path:
289
  return candidate
290
 
291
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  def tool_get_current_datetime(_args: dict) -> str:
293
  return json.dumps({"utc_datetime": datetime.now(timezone.utc).isoformat()})
294
 
@@ -301,17 +332,40 @@ _ALLOWED_AST_NODES = (
301
  )
302
 
303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  def _safe_eval_expression(expr: str):
 
 
305
  tree = ast.parse(expr, mode="eval")
306
 
307
  def _check(node):
308
  if not isinstance(node, _ALLOWED_AST_NODES):
309
  raise ValueError(f"عنصر غير مسموح به في التعبير الحسابي: {type(node).__name__}")
 
 
310
  for child in ast.iter_child_nodes(node):
311
  _check(child)
312
 
313
  _check(tree)
314
- return eval(compile(tree, "<calculate>", "eval"), {"__builtins__": {}}, _ALLOWED_MATH_NAMES)
 
 
315
 
316
 
317
  def tool_calculate(args: dict) -> str:
@@ -343,13 +397,36 @@ def tool_web_search(args: dict) -> str:
343
  return json.dumps({"error": f"فشل البحث: {e}"})
344
 
345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  def tool_fetch_webpage(args: dict) -> str:
347
  url = str(args.get("url", "")).strip()
348
  if not url.lower().startswith(("http://", "https://")):
349
  return json.dumps({"error": "رابط http(s) صالح مطلوب"})
 
 
350
  try:
351
  req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
352
- with urllib.request.urlopen(req, timeout=15) as resp:
353
  raw = resp.read(500_000).decode("utf-8", errors="ignore")
354
  text = re.sub(r"<script.*?</script>|<style.*?</style>", " ", raw, flags=re.S | re.I)
355
  text = re.sub(r"<[^>]+>", " ", text)
@@ -432,6 +509,7 @@ def tool_execute_python(args: dict) -> str:
432
  proc = subprocess.run(
433
  [sys.executable, str(script_path)],
434
  cwd=str(SANDBOX_DIR), capture_output=True, text=True, timeout=timeout_s,
 
435
  )
436
  return json.dumps({
437
  "stdout": proc.stdout[-4000:], "stderr": proc.stderr[-4000:],
@@ -494,7 +572,8 @@ def tool_run_file(args: dict) -> str:
494
  if not runner:
495
  return json.dumps({"error": f"نوع ملف غير مدعوم: '{path.suffix}'"})
496
  cmd = runner + [str(path)] + extra_args
497
- proc = subprocess.run(cmd, cwd=str(SANDBOX_DIR), capture_output=True, text=True, timeout=20)
 
498
  return json.dumps({
499
  "command": " ".join(cmd), "exit_code": proc.returncode,
500
  "passed": proc.returncode == 0,
@@ -675,43 +754,88 @@ def call_tool(name: str, arguments: dict) -> str:
675
  MAX_TOOL_ITERATIONS = 6
676
 
677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  def _merge_tools(payload: dict) -> list[dict]:
679
- if payload.get("disable_tools"):
680
- return payload.get("tools") or []
681
  client_tools = list(payload.get("tools") or [])
682
- existing_names = {
683
- t.get("function", {}).get("name") for t in client_tools if isinstance(t, dict)
684
- }
685
  for t in TOOLS_SCHEMA:
686
  if t["function"]["name"] not in existing_names:
687
  client_tools.append(t)
688
  return client_tools
689
 
690
 
 
 
 
 
 
 
 
 
 
 
 
691
  async def _post_with_retry(client: httpx.AsyncClient, url: str, payload: dict,
692
- attempts: int = 4, wait_s: float = 3.0) -> dict:
693
- last_err: Exception | None = None
694
- for attempt in range(attempts):
 
 
 
 
 
 
695
  try:
696
- resp = await client.post(url, json=payload, timeout=httpx.Timeout(600.0, connect=120.0))
697
- resp.raise_for_status()
698
- return resp.json()
699
- except Exception as e:
700
- last_err = e
701
- print(f"[chat] محاولة {attempt + 1}/{attempts} فشلت: {e}؛ "
702
- f"ننتظر قليلاً ريثما تُعيد المراقبة الداخلية تشغيل llama-server...")
703
- await asyncio.sleep(wait_s)
704
- raise RuntimeError(f"لم يستجب llama-server بعد {attempts} محاولات: {last_err}")
 
 
 
 
 
705
 
706
 
707
  async def run_agentic_chat(client: httpx.AsyncClient, path: str, payload: dict) -> dict:
708
  """يرسل الطلب إلى llama-server م��ليًا، وإن طلب النموذج استدعاء أداة ينفذها
709
  فعليًا ويعيد النتيجة للنموذج، ويكرر ذلك حتى يصل لرد نهائي بلا tool_calls
710
- (أو حتى الحد الأقصى من التكرارات) — هذا ما 'يُكمل' رد النموذج فعليًا."""
 
 
 
711
  url = f"http://127.0.0.1:8000{path}"
712
  messages = list(payload.get("messages", []))
 
 
713
  payload = dict(payload)
714
- payload["tools"] = _merge_tools(payload)
 
 
 
 
715
  payload["stream"] = False # الحلقة الداخلية تعمل دائمًا بدون بث، والبث يُحاكى لاحقًا للعميل إن طُلب
716
 
717
  final_response: dict = {}
@@ -724,6 +848,9 @@ async def run_agentic_chat(client: httpx.AsyncClient, path: str, payload: dict)
724
  tool_calls = msg.get("tool_calls")
725
  if not tool_calls:
726
  break
 
 
 
727
  messages.append(msg)
728
  for tc in tool_calls:
729
  fn = tc.get("function", {}) or {}
@@ -732,10 +859,15 @@ async def run_agentic_chat(client: httpx.AsyncClient, path: str, payload: dict)
732
  tc_args = json.loads(fn.get("arguments") or "{}")
733
  except json.JSONDecodeError:
734
  tc_args = {}
 
 
 
 
 
735
  messages.append({
736
  "role": "tool",
737
  "tool_call_id": tc.get("id", ""),
738
- "content": call_tool(name, tc_args),
739
  })
740
  else:
741
  # تجاوزنا الحد الأقصى من جولات الأدوات: نطلب من النموذج إنهاء الرد نصيًا بدون أدوات إضافية.
@@ -752,26 +884,61 @@ async def run_agentic_chat(client: httpx.AsyncClient, path: str, payload: dict)
752
  return final_response
753
 
754
 
 
 
 
 
755
  async def _fake_sse_stream(result: dict):
756
- """بث SSE مبسّط متوافق مع صيغة OpenAI streaming، لإرجاء الرد النهائي
757
- دفعة واحدة للعملاء الذين يطلبون stream=true (بعد اكتمال حلقة الأدوات)."""
758
  choice = (result.get("choices") or [{}])[0]
759
- content = (choice.get("message", {}) or {}).get("content", "") or ""
760
- chunk = {
761
  "id": result.get("id", f"chatcmpl-{uuid.uuid4().hex}"),
762
  "object": "chat.completion.chunk",
763
  "created": result.get("created", int(time.time())),
764
  "model": result.get("model", ""),
765
- "choices": [{
766
- "index": 0,
767
- "delta": {"role": "assistant", "content": content},
768
- "finish_reason": choice.get("finish_reason", "stop"),
769
- }],
770
  }
771
- yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode("utf-8")
 
 
 
 
 
 
 
 
 
 
772
  yield b"data: [DONE]\n\n"
773
 
774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
775
  CHAT_COMPLETIONS_PATHS = {"/v1/chat/completions", "/chat/completions"}
776
 
777
 
@@ -792,17 +959,22 @@ async def proxy_middleware(request: Request, call_next):
792
  payload = None
793
 
794
  if isinstance(payload, dict):
795
- wants_stream = bool(payload.get("stream"))
796
- client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=120.0))
 
 
 
 
 
797
  try:
798
  result = await run_agentic_chat(client, path, payload)
 
 
 
799
  except Exception as e:
800
- await client.aclose()
801
  return JSONResponse({"error": f"proxy/tool error: {e}"}, status_code=502)
802
- await client.aclose()
803
-
804
- if wants_stream:
805
- return StreamingResponse(_fake_sse_stream(result), media_type="text/event-stream")
806
  return JSONResponse(result)
807
 
808
  # أي مسار آخر: تمرير خام كما في الأصل (بدون تغيير في السلوك).
@@ -850,4 +1022,4 @@ async def proxy_middleware(request: Request, call_next):
850
 
851
  if __name__ == "__main__":
852
  start_llama_server()
853
- app.launch(show_error=True)
 
2
 
3
  import ast
4
  import asyncio
5
+ import ipaddress
6
  import json
7
  import math
8
  import os
 
14
  import tempfile
15
  import threading
16
  import time
17
+ import urllib.error
18
  import urllib.parse
19
  import urllib.request
20
  import uuid
 
62
  GENERATIONS_DIR.mkdir(parents=True, exist_ok=True)
63
 
64
  # مجلد عمل مؤقت لأدوات الكود فقط — ليس جزءًا من التخزين الدائم أبدًا.
65
+ SANDBOX_DIR = (Path(tempfile.gettempdir()) / "llm_tool_sandbox").resolve()
66
  SANDBOX_DIR.mkdir(parents=True, exist_ok=True)
67
 
68
 
 
112
 
113
  if not os.path.exists("llama.cpp"):
114
  subprocess.run(["git", "clone", "https://github.com/unslothai/llama.cpp.git"], check=True)
 
 
115
 
116
+ # fetch + checkout -B يعملان حتى لو فشل البناء سابقًا وبقي الفرع mtp موجودًا
117
+ # (الأمر القديم `fetch pull/144/head:mtp` كان يفشل في المرة الثانية).
118
+ subprocess.run(["git", "fetch", "origin", "pull/144/head"], cwd="llama.cpp", check=True)
119
+ subprocess.run(["git", "checkout", "-f", "-B", "mtp", "FETCH_HEAD"], cwd="llama.cpp", check=True)
120
 
121
  env = os.environ.copy()
122
  if "/usr/local/cuda/bin" not in env.get("PATH", ""):
 
155
  return process
156
 
157
 
158
+ def monitor_llama_server(poll_interval: float = 5.0, startup_grace: float = 900.0) -> None:
159
  """مراقبة داخلية للحاوية تعمل في خيط خلفي طوال عمر العملية: تتحقق دوريًا من
160
  أن llama-server حيّ ويستجيب على المنفذ، وإن توقف (انهيار/تعليق) تعيد
161
+ تشغيله تلقائيًا بنفس الأمر والبيئة دون إعادة تنزيل النموذج.
162
+
163
+ ملاحظات:
164
+ - فترة سماح (startup_grace) أثناء تحميل النموذج: سابقًا كانت المراقبة تقتل
165
+ العملية لأن المنفذ لم يُفتح بعد (تحميل 33 ملفًا يستغرق دقائق) فتدخل في حلقة
166
+ إعادة تشغيل لا تنتهي.
167
+ - لا يُحتجز القفل أثناء النوم/الانتظار.
168
+ - العملية الحيّة لا تُعاد تشغيلها إلا بعد 3 فحوصات متتالية فاشلة."""
169
+ restarts = 0
170
+ misses = 0
171
+ ever_up = False
172
+ started_at = time.monotonic()
173
  while True:
174
  time.sleep(poll_interval)
175
  with _llama_process_lock:
176
  proc = _llama_process
177
+ process_alive = proc is not None and proc.poll() is None
178
+ port_up = process_alive and _is_llama_server_up(timeout=2.0)
179
+
180
+ if port_up:
181
+ ever_up = True
182
+ misses = 0
183
+ restarts = 0
184
+ continue
185
+
186
+ if process_alive:
187
+ # ما زال يحمّل النموذج لأول مرة بعد (إعادة) التشغيل: لا تتدخل.
188
+ if not ever_up and (time.monotonic() - started_at) < startup_grace:
189
+ continue
190
+ misses += 1
191
+ if misses < 3:
192
  continue
193
 
194
+ restarts += 1
195
+ backoff = min(30, 2 ** restarts)
196
+ print(f"[monitor] llama-server غير سليم (محاولة رقم {restarts})؛ "
197
+ f"إعادة التشغيل خلال {backoff}ث...")
198
+ time.sleep(backoff)
199
+ with _llama_process_lock:
200
  try:
201
  if proc is not None and proc.poll() is None:
202
  proc.kill()
 
205
  print(f"[monitor] تعذر إيقاف العملية القديمة: {e}")
206
  try:
207
  _spawn_llama_process()
208
+ print("[monitor] أُعيد تشغيل llama-server؛ بانتظار تحميل النموذج...")
 
 
 
 
 
209
  except Exception as e:
210
  print(f"[monitor] فشلت محاولة إعادة التشغيل: {e}")
211
+ misses = 0
212
+ ever_up = False
213
+ started_at = time.monotonic()
214
 
215
 
216
  def start_llama_server():
 
308
  return candidate
309
 
310
 
311
+ def _sandbox_env() -> dict:
312
+ """بيئة نظيفة للعمليات الفرعية: لا تُمرَّر مفاتيح/توكنات البيئة (HF_TOKEN ...)
313
+ إلى كود كتبه النموذج."""
314
+ return {
315
+ "PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),
316
+ "HOME": str(SANDBOX_DIR),
317
+ "TMPDIR": str(SANDBOX_DIR),
318
+ "LANG": "C.UTF-8",
319
+ "PYTHONIOENCODING": "utf-8",
320
+ }
321
+
322
+
323
  def tool_get_current_datetime(_args: dict) -> str:
324
  return json.dumps({"utc_datetime": datetime.now(timezone.utc).isoformat()})
325
 
 
332
  )
333
 
334
 
335
+ def _safe_pow(a, b):
336
+ """أس آمن: يمنع أسًا ضخمًا مثل 9**9**9**9 الذي يجمّد العملية بالكامل."""
337
+ if isinstance(a, int) and isinstance(b, int) and b > 0 and a.bit_length() * b > 1_000_000:
338
+ raise ValueError("الناتج كبير جدًا")
339
+ return a ** b
340
+
341
+
342
+ class _PowGuard(ast.NodeTransformer):
343
+ def visit_BinOp(self, node):
344
+ self.generic_visit(node)
345
+ if isinstance(node.op, ast.Pow):
346
+ call = ast.Call(func=ast.Name(id="__safe_pow__", ctx=ast.Load()),
347
+ args=[node.left, node.right], keywords=[])
348
+ return ast.copy_location(call, node)
349
+ return node
350
+
351
+
352
  def _safe_eval_expression(expr: str):
353
+ if len(expr) > 500:
354
+ raise ValueError("التعبير طويل جدًا")
355
  tree = ast.parse(expr, mode="eval")
356
 
357
  def _check(node):
358
  if not isinstance(node, _ALLOWED_AST_NODES):
359
  raise ValueError(f"عنصر غير مسموح به في التعبير الحسابي: {type(node).__name__}")
360
+ if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float)):
361
+ raise ValueError("الأرقام فقط مسموحة كقيم ثابتة") # يمنع "a"*10**9
362
  for child in ast.iter_child_nodes(node):
363
  _check(child)
364
 
365
  _check(tree)
366
+ tree = ast.fix_missing_locations(_PowGuard().visit(tree))
367
+ names = {**_ALLOWED_MATH_NAMES, "__safe_pow__": _safe_pow}
368
+ return eval(compile(tree, "<calculate>", "eval"), {"__builtins__": {}}, names)
369
 
370
 
371
  def tool_calculate(args: dict) -> str:
 
397
  return json.dumps({"error": f"فشل البحث: {e}"})
398
 
399
 
400
+ def _is_public_host(host: str) -> bool:
401
+ """False لعناوين localhost / الشبكات الداخلية / metadata — لمنع SSRF
402
+ (مثلًا أن يجعل النموذج الأداة تقرأ llama-server نفسه على 127.0.0.1:8000)."""
403
+ if not host:
404
+ return False
405
+ try:
406
+ infos = socket.getaddrinfo(host, None)
407
+ except socket.gaierror:
408
+ return False
409
+ return bool(infos) and all(
410
+ ipaddress.ip_address(i[4][0].split("%")[0]).is_global for i in infos
411
+ )
412
+
413
+
414
+ class _PublicOnlyRedirect(urllib.request.HTTPRedirectHandler):
415
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
416
+ if not _is_public_host(urllib.parse.urlparse(newurl).hostname or ""):
417
+ raise urllib.error.HTTPError(newurl, code, "إعادة توجيه إلى عنوان غير عام محظورة", headers, fp)
418
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
419
+
420
+
421
  def tool_fetch_webpage(args: dict) -> str:
422
  url = str(args.get("url", "")).strip()
423
  if not url.lower().startswith(("http://", "https://")):
424
  return json.dumps({"error": "رابط http(s) صالح مطلوب"})
425
+ if not _is_public_host(urllib.parse.urlparse(url).hostname or ""):
426
+ return json.dumps({"error": "الوصول إلى عناوين داخلية/محلية غير مسموح"})
427
  try:
428
  req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
429
+ with urllib.request.build_opener(_PublicOnlyRedirect).open(req, timeout=15) as resp:
430
  raw = resp.read(500_000).decode("utf-8", errors="ignore")
431
  text = re.sub(r"<script.*?</script>|<style.*?</style>", " ", raw, flags=re.S | re.I)
432
  text = re.sub(r"<[^>]+>", " ", text)
 
509
  proc = subprocess.run(
510
  [sys.executable, str(script_path)],
511
  cwd=str(SANDBOX_DIR), capture_output=True, text=True, timeout=timeout_s,
512
+ env=_sandbox_env(),
513
  )
514
  return json.dumps({
515
  "stdout": proc.stdout[-4000:], "stderr": proc.stderr[-4000:],
 
572
  if not runner:
573
  return json.dumps({"error": f"نوع ملف غير مدعوم: '{path.suffix}'"})
574
  cmd = runner + [str(path)] + extra_args
575
+ proc = subprocess.run(cmd, cwd=str(SANDBOX_DIR), capture_output=True, text=True, timeout=20,
576
+ env=_sandbox_env())
577
  return json.dumps({
578
  "command": " ".join(cmd), "exit_code": proc.returncode,
579
  "passed": proc.returncode == 0,
 
754
  MAX_TOOL_ITERATIONS = 6
755
 
756
 
757
+ class UpstreamError(Exception):
758
+ """خطأ نهائي من llama-server (مثل 400) لا يفيد معه إعادة المحاولة."""
759
+
760
+ def __init__(self, status: int, body: str):
761
+ super().__init__(f"llama-server HTTP {status}: {body[:300]}")
762
+ self.status = status
763
+ self.body = body
764
+
765
+
766
+ def _client_tool_names(payload: dict) -> set[str]:
767
+ return {
768
+ (t.get("function") or {}).get("name")
769
+ for t in (payload.get("tools") or []) if isinstance(t, dict)
770
+ }
771
+
772
+
773
  def _merge_tools(payload: dict) -> list[dict]:
 
 
774
  client_tools = list(payload.get("tools") or [])
775
+ if payload.get("disable_tools"):
776
+ return client_tools
777
+ existing_names = _client_tool_names(payload)
778
  for t in TOOLS_SCHEMA:
779
  if t["function"]["name"] not in existing_names:
780
  client_tools.append(t)
781
  return client_tools
782
 
783
 
784
+ def _local_tool_names(payload: dict) -> set[str]:
785
+ """الأدوات التي ينفذها الوسيط فعليًا. أي أداة يعرّفها العميل نفسه (أو كل
786
+ الأدوات عند disable_tools) تُترك للعميل ولا تُنفَّذ هنا."""
787
+ if payload.get("disable_tools"):
788
+ return set()
789
+ return set(TOOL_REGISTRY) - _client_tool_names(payload)
790
+
791
+
792
+ _RETRYABLE_STATUS = {502, 503, 504}
793
+
794
+
795
  async def _post_with_retry(client: httpx.AsyncClient, url: str, payload: dict,
796
+ max_wait_s: float = 600.0, wait_s: float = 3.0) -> dict:
797
+ """يعيد المحاولة فقط عند أخطاء الاتصال/503 (llama-server يُعاد تشغيله أو يحمّل
798
+ النموذج) ولمدة تصل إلى max_wait_s — سابقًا كانت 4 محاولات (~12ث) فقط، أقصر
799
+ بكثير من زمن تحميل النموذج، وكانت تعيد المحاولة أيضًا عند أخطاء 4xx بلا فائدة."""
800
+ deadline = time.monotonic() + max_wait_s
801
+ attempt = 0
802
+ last_err = "unknown"
803
+ while True:
804
+ attempt += 1
805
  try:
806
+ resp = await client.post(url, json=payload, timeout=httpx.Timeout(600.0, connect=30.0))
807
+ except httpx.TransportError as e:
808
+ last_err = repr(e)
809
+ else:
810
+ if resp.status_code < 400:
811
+ return resp.json()
812
+ if resp.status_code not in _RETRYABLE_STATUS:
813
+ raise UpstreamError(resp.status_code, resp.text)
814
+ last_err = f"HTTP {resp.status_code}"
815
+ if time.monotonic() >= deadline:
816
+ break
817
+ print(f"[chat] المحاولة {attempt} فشلت ({last_err})؛ ننتظر {wait_s}ث ريثما يعود llama-server...")
818
+ await asyncio.sleep(wait_s)
819
+ raise RuntimeError(f"لم يستجب llama-server خلال {max_wait_s:.0f} ثانية: {last_err}")
820
 
821
 
822
  async def run_agentic_chat(client: httpx.AsyncClient, path: str, payload: dict) -> dict:
823
  """يرسل الطلب إلى llama-server م��ليًا، وإن طلب النموذج استدعاء أداة ينفذها
824
  فعليًا ويعيد النتيجة للنموذج، ويكرر ذلك حتى يصل لرد نهائي بلا tool_calls
825
+ (أو حتى الحد الأقصى من التكرارات) — هذا ما 'يُكمل' رد النموذج فعليًا.
826
+
827
+ إن طلب النموذج أداة يعرّفها العميل (ليست من أدواتنا) يُرجَع الرد كما هو
828
+ للعميل ليتولاها بنفسه، بدل أن نردّ على النموذج بـ"أداة غير معروفة"."""
829
  url = f"http://127.0.0.1:8000{path}"
830
  messages = list(payload.get("messages", []))
831
+ local_names = _local_tool_names(payload)
832
+ tools = _merge_tools(payload)
833
  payload = dict(payload)
834
+ payload.pop("disable_tools", None) # حقل خاص بنا، لا يُرسل إلى llama-server
835
+ if tools:
836
+ payload["tools"] = tools
837
+ else:
838
+ payload.pop("tools", None)
839
  payload["stream"] = False # الحلقة الداخلية تعمل دائمًا بدون بث، والبث يُحاكى لاحقًا للعميل إن طُلب
840
 
841
  final_response: dict = {}
 
848
  tool_calls = msg.get("tool_calls")
849
  if not tool_calls:
850
  break
851
+ names = [((tc.get("function") or {}).get("name") or "") for tc in tool_calls]
852
+ if not all(n in local_names for n in names):
853
+ break # أدوات العميل: نعيد الرد كما هو
854
  messages.append(msg)
855
  for tc in tool_calls:
856
  fn = tc.get("function", {}) or {}
 
859
  tc_args = json.loads(fn.get("arguments") or "{}")
860
  except json.JSONDecodeError:
861
  tc_args = {}
862
+ if not isinstance(tc_args, dict):
863
+ tc_args = {}
864
+ # الأدوات متزامنة (urllib/subprocess) فتُشغَّل في خيط منفصل حتى لا
865
+ # تجمّد حلقة asyncio وكل الطلبات الأخرى أثناء تنفيذها.
866
+ result = await asyncio.to_thread(call_tool, name, tc_args)
867
  messages.append({
868
  "role": "tool",
869
  "tool_call_id": tc.get("id", ""),
870
+ "content": result,
871
  })
872
  else:
873
  # تجاوزنا الحد الأقصى من جولات الأدوات: نطلب من النموذج إنهاء الرد نصيًا بدون أدوات إضافية.
 
884
  return final_response
885
 
886
 
887
+ def _sse(obj: dict) -> bytes:
888
+ return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode("utf-8")
889
+
890
+
891
  async def _fake_sse_stream(result: dict):
892
+ """بث SSE متوافق مع صيغة OpenAI streaming: الرد النهائي دفعة واحدة (بعد اكتمال
893
+ حلقة الأدوات) ثم chunk ختامي منفصل يحمل finish_reason كما يتوقع العملاء."""
894
  choice = (result.get("choices") or [{}])[0]
895
+ msg = choice.get("message", {}) or {}
896
+ base = {
897
  "id": result.get("id", f"chatcmpl-{uuid.uuid4().hex}"),
898
  "object": "chat.completion.chunk",
899
  "created": result.get("created", int(time.time())),
900
  "model": result.get("model", ""),
 
 
 
 
 
901
  }
902
+ delta: dict = {"role": "assistant", "content": msg.get("content") or ""}
903
+ if msg.get("reasoning_content"):
904
+ delta["reasoning_content"] = msg["reasoning_content"]
905
+ if msg.get("tool_calls"):
906
+ delta["tool_calls"] = [{**tc, "index": i} for i, tc in enumerate(msg["tool_calls"])]
907
+ yield _sse({**base, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]})
908
+ final = {**base, "choices": [{"index": 0, "delta": {},
909
+ "finish_reason": choice.get("finish_reason") or "stop"}]}
910
+ if result.get("usage"):
911
+ final["usage"] = result["usage"]
912
+ yield _sse(final)
913
  yield b"data: [DONE]\n\n"
914
 
915
 
916
+ async def _agentic_sse(path: str, payload: dict):
917
+ """يشغّل الحلقة الوكيلة ويرسل تعليقات keep-alive كل 10 ثوانٍ أثناء الانتظار؛
918
+ سابقًا لم يكن يصل أي بايت للعميل طوال تنفيذ الأدوات/التفكير فكانت الاتصالات
919
+ تنقطع بسبب مهلة الخمول في البروكسي."""
920
+ client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=30.0))
921
+ task = asyncio.create_task(run_agentic_chat(client, path, payload))
922
+ try:
923
+ while True:
924
+ done, _ = await asyncio.wait({task}, timeout=10)
925
+ if done:
926
+ break
927
+ yield b": keep-alive\n\n"
928
+ try:
929
+ result = task.result()
930
+ except Exception as e:
931
+ yield _sse({"error": {"message": f"proxy/tool error: {e}"}})
932
+ yield b"data: [DONE]\n\n"
933
+ return
934
+ async for chunk in _fake_sse_stream(result):
935
+ yield chunk
936
+ finally:
937
+ if not task.done():
938
+ task.cancel()
939
+ await client.aclose()
940
+
941
+
942
  CHAT_COMPLETIONS_PATHS = {"/v1/chat/completions", "/chat/completions"}
943
 
944
 
 
959
  payload = None
960
 
961
  if isinstance(payload, dict):
962
+ if payload.get("stream"):
963
+ return StreamingResponse(
964
+ _agentic_sse(path, payload),
965
+ media_type="text/event-stream",
966
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
967
+ )
968
+ client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=30.0))
969
  try:
970
  result = await run_agentic_chat(client, path, payload)
971
+ except UpstreamError as e:
972
+ # أخطاء العميل (مثل 400) تُمرَّر بحالتها الأصلية بدل تحويلها إلى 502.
973
+ return JSONResponse({"error": {"message": e.body, "code": e.status}}, status_code=e.status)
974
  except Exception as e:
 
975
  return JSONResponse({"error": f"proxy/tool error: {e}"}, status_code=502)
976
+ finally:
977
+ await client.aclose()
 
 
978
  return JSONResponse(result)
979
 
980
  # أي مسار آخر: تمرير خام كما في الأصل (بدون تغيير في السلوك).
 
1022
 
1023
  if __name__ == "__main__":
1024
  start_llama_server()
1025
+ app.launch(show_error=True)