contiai / apps /api /app /agents /case_study /runner.py
aliabozahra315's picture
Claude Opus 5.5
Deploy 9e83dee: case study revision, text_image, simulation_game, interactive_activities, dna_microlearning (founder-only preview)
258a360
Raw History Blame Contribute Delete
5.1 kB
"""Running one agent and insisting on valid JSON - cell [8].
Ported from `case_study_pipeline.ipynb`. The notebook was one namespace, so
each module re-imports the ones before it; every prompt and every standard is
the notebook's text, compared character by character by the fidelity test.
"""
from __future__ import annotations
import asyncio # noqa: F401
import datetime # noqa: F401
import html # noqa: F401
import json # noqa: F401
import pathlib # noqa: F401
import re # noqa: F401
from typing import Any, Callable, Literal, Optional # noqa: F401
from pydantic import ( # noqa: F401
BaseModel,
ConfigDict,
Field,
ValidationError,
model_validator,
)
from app.agents.case_study.helpers import * # noqa: F403
from app.agents.case_study.llms import * # noqa: F403
_SEM: Optional[asyncio.Semaphore] = None
_SEM_LOOP = None
def _sem() -> asyncio.Semaphore:
global _SEM, _SEM_LOOP
loop = asyncio.get_event_loop()
if _SEM is None or _SEM_LOOP is not loop:
_SEM, _SEM_LOOP = asyncio.Semaphore(RUN_CONFIG["max_concurrency"]), loop
return _SEM
async def kickoff_crew(agent: Agent, description: str, expected_output: str) -> str:
"""كل وكيل = Crew مستقل. لا نمرر inputs لـ kickoff (البرومبتات فيها JSON بأقواس {})."""
task = Task(description=description, agent=agent, expected_output=expected_output)
crew = Crew(agents=[agent], tasks=[task], process=Process.sequential, verbose=RUN_CONFIG["verbose"])
async with _sem():
result = await crew.kickoff_async()
return str(getattr(result, "raw", result))
def _with_try(prompt: str, attempt: int) -> str:
first, _, rest = prompt.partition("\n")
first = re.sub(r"\s*#TRY=\d+", "", first)
return f"{first} #TRY={attempt}\n{rest}"
ValidateFn = Callable[[Any], tuple[list[str], list[str]]] # → (أخطاء هيكلية, ملاحظات أسلوبية)
async def run_json_task(agent_factory: Callable[[], Agent], prompt: str, Schema: type[BaseModel], label: str,
extra_validate: Optional[ValidateFn] = None,
expected_output: str = "كائن JSON واحد صالح فقط مطابق للهيكل المطلوب، دون أي نص قبله أو بعده.") -> BaseModel:
"""يشغّل الوكيل ← يستخرج JSON ← Schema.model_validate ← extra_validate.
- خطأ هيكلي: يُعاد مع التغذية الراجعة حتى max_retries، ثم PipelineError (أو آخر نسخة صالحة هيكليًا).
- ملاحظة أسلوبية: يُعاد حتى style_retries، ثم يُقبل ويُسجَّل في QA_LOG."""
hard_fails, style_used, attempt = 0, 0, 0
feedback, last_ok, last_soft = "", None, []
while True:
attempt += 1
full = _with_try(prompt, attempt) + feedback
raw = await kickoff_crew(agent_factory(), full, expected_output)
hard, soft, obj = [], [], None
try:
obj = Schema.model_validate(parse_json_safe(raw))
except ValidationError as e:
hard = [f"{'.'.join(str(x) for x in er['loc'])}: {er['msg']}" for er in e.errors()[:12]]
except ValueError as e:
hard = [str(e)]
if obj is not None and extra_validate:
hard, soft = extra_validate(obj)
if hard:
hard_fails += 1
log(f"↻ {label}: مخرج هيكلي غير صالح (محاولة {attempt}): {hard[:3]}")
if hard_fails > RUN_CONFIG["max_retries"]:
if last_ok is not None:
qa(label, "style_accepted", last_soft)
return last_ok
raise PipelineError(f"{label}: فشل التحقق الهيكلي بعد {hard_fails} محاولات:\n- " + "\n- ".join(hard))
feedback = ("\n\n### تصحيح إلزامي — رُفض مخرجك السابق للأسباب التالية:\n- " + "\n- ".join(hard) +
"\nأعد إخراج JSON كاملًا بنفس الهيكل بعد إصلاح كل ما سبق.\n"
f"مخرجك السابق (مقتطع):\n{str(raw)[:5000]}")
continue
# `PLATFORM_CONFIG` was declared beside `RUN_CONFIG` and never read,
# so every style note still bought a second call. Read here.
if soft and style_used < PLATFORM_CONFIG.get("style_retries", RUN_CONFIG["style_retries"]):
style_used += 1
last_ok, last_soft = obj, soft
log(f"↻ {label}: ملاحظات أسلوبية ({len(soft)}) — إعادة للتحسين")
feedback = ("\n\n### ملاحظات أسلوبية يجب معالجتها (مع الحفاظ على كل ما هو صحيح):\n- " + "\n- ".join(soft) +
f"\nمخرجك السابق:\n{str(raw)[:5000]}")
continue
qa(label, "style_accepted", soft)
if soft:
log(f"⚠ {label}: قُبل مع {len(soft)} ملاحظة أسلوبية (مسجلة في تقرير الجودة)")
return obj