
Teljes kódot kijavítva vissza küldöd. minden egyes karaktert...
Prompt
Teljes kódot kijavítva vissza küldöd. minden egyes karaktert leírsz, nem rövidítesz. minden hibát kijavítasz. egy fájl marad. ne írj semmi mást csak a teljes kódot es kommentek nem lehetnek benne! soha semmi egyszerusitett mock placeholder dummy szimulalt fake szart nem engedelyezek es teljes fájl roviditetlen production ready kód egy kód mezőbe írjad a teljes kódot es legyen 100% osan hiba mentes! """ AgentOS – Abstract base class for all worker types. Every worker receives a WorkerInput, performs its specialized work, and returns a strictly typed WorkerResult. Workers may NOT directly access the database; all state mutations go through the orchestrator. """ from __future__ import annotations import abc import time import uuid from typing import Any, Dict, Optional from core.config import settings from core.logging_config import get_logger from schemas.worker import ResourceUsage, ToolCallRecord, WorkerInput, WorkerResult logger = get_logger(__name__) class BaseWorker(abc.ABC): """Abstract base for all AgentOS workers.""" #: One of the capability class constants from the registry capability_class: str = "base" def __init__(self) -> None: self._tool_calls: list[ToolCallRecord] = [] # ── Public entry point ──────────────────────────────────────────────────── async def execute(self, worker_input: WorkerInput) -> WorkerResult: """ Execute the worker and return a structured result. Wraps _run() with timing, error handling, and result normalisation. Workers MUST NOT override this method; override _run() instead. """ self._tool_calls = [] start = time.monotonic() logger.info( "Worker starting", capability=self.capability_class, subtask_id=str(worker_input.subtask_id), task_id=str(worker_input.task_id), ) try: result = await self._run(worker_input) except Exception as exc: elapsed = time.monotonic() - start logger.error( "Worker failed with unhandled exception", capability=self.capability_class, subtask_id=str(worker_input.subtask_id), error=str(exc), exc_info=True, ) return WorkerResult( subtask_id=worker_input.subtask_id, status="failed", summary=f"Worker failed: {type(exc).__name__}: {exc}", error_code="WORKER_UNHANDLED_EXCEPTION", error_message=str(exc), error_details={"exception_type": type(exc).__name__}, tool_call_records=list(self._tool_calls), elapsed_seconds=elapsed, confidence_estimate=0.0, resource_usage=ResourceUsage(elapsed_wall_seconds=elapsed), ) elapsed = time.monotonic() - start result = result.model_copy( update={ "elapsed_seconds": elapsed, "tool_call_records": list(self._tool_calls) + list(result.tool_call_records), } ) logger.info( "Worker completed", capability=self.capability_class, subtask_id=str(worker_input.subtask_id), status=result.status, confidence=result.confidence_estimate, elapsed_ms=int(elapsed * 1000), ) return result # ── Abstract method ──────────────────────────────────────────────────────── @abc.abstractmethod async def _run(self, worker_input: WorkerInput) -> WorkerResult: """ Perform the worker's specialized work. Must return a WorkerResult with status="completed", "failed", or "needs_repair". Workers receive only the minimal context in worker_input.inputs. They MUST NOT access the database directly. """ # ── Protected helpers ────────────────────────────────────────────────────── def _record_tool_call( self, tool_name: str, input_summary: Optional[str] = None, output_summary: Optional[str] = None, elapsed_ms: Optional[int] = None, success: bool = True, error: Optional[str] = None, tokens_used: Optional[int] = None, ) -> None: """Append a ToolCallRecord to the running audit log.""" import datetime self._tool_calls.append( ToolCallRecord( tool_name=tool_name, invoked_at=datetime.datetime.now(tz=datetime.timezone.utc), input_summary=input_summary, output_summary=output_summary, elapsed_ms=elapsed_ms, success=success, error=error, tokens_used=tokens_used, ) ) async def _llm_call( self, system_prompt: str, user_prompt: str, response_format: Optional[Dict[str, Any]] = None, temperature: float = 0.3, max_tokens: Optional[int] = None, ) -> tuple[str, int]: """ Make one LLM call and return (content, tokens_used). Records the call in the tool audit log. """ import time as _time from schemas.provider import ChatCompletionRequest, ChatMessage from services.providers.router import routed_chat_completion start = _time.monotonic() req = ChatCompletionRequest( messages=[ ChatMessage(role="system", content=system_prompt), ChatMessage(role="user", content=user_prompt), ], temperature=temperature, max_tokens=max_tokens or settings.FIREWORKS_MAX_TOKENS, response_format=response_format, reasoning_effort="max", reasoning_history="preserved", ) try: response = await routed_chat_completion(req) elapsed_ms = int((_time.monotonic() - start) * 1000) self._record_tool_call( tool_name="llm_chat_completion", input_summary=f"system={system_prompt[:80]!r} user={user_prompt[:80]!r}", output_summary=f"tokens={response.usage.total_tokens} finish={response.finish_reason}", elapsed_ms=elapsed_ms, success=True, tokens_used=response.usage.total_tokens, ) return response.content, response.usage.total_tokens except Exception as exc: elapsed_ms = int((_time.monotonic() - start) * 1000) self._record_tool_call( tool_name="llm_chat_completion", input_summary=f"system={system_prompt[:80]!r} user={user_prompt[:80]!r}", elapsed_ms=elapsed_ms, success=False, error=str(exc), ) raise