|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from typing import Literal |
| 6 | +from collections.abc import Iterator, Sequence |
| 7 | + |
| 8 | + |
| 9 | +FailureCode = Literal[ |
| 10 | + "rate_limited", |
| 11 | + "authentication_failed", |
| 12 | + "timeout", |
| 13 | + "connection_error", |
| 14 | + "invalid_request", |
| 15 | + "provider_error", |
| 16 | + "empty_response", |
| 17 | + "unexpected_error", |
| 18 | +] |
| 19 | + |
| 20 | +EventType = Literal["output_text", "completed", "failed"] |
| 21 | + |
| 22 | + |
| 23 | +@dataclass(frozen=True) |
| 24 | +class ConversationTurn: |
| 25 | + role: Literal["user", "assistant"] |
| 26 | + content: str |
| 27 | + |
| 28 | + |
| 29 | +@dataclass(frozen=True) |
| 30 | +class ChatHarnessIdentity: |
| 31 | + key: str |
| 32 | + display_name: str |
| 33 | + model_display_name: str |
| 34 | + provider_name: str | None = None |
| 35 | + version: str | None = None |
| 36 | + |
| 37 | + |
| 38 | +@dataclass(frozen=True) |
| 39 | +class ChatHarnessCapabilities: |
| 40 | + supports_streaming: bool = False |
| 41 | + supports_tools: bool = False |
| 42 | + supports_context_builders: bool = False |
| 43 | + |
| 44 | + |
| 45 | +@dataclass(frozen=True) |
| 46 | +class ChatHarnessObservability: |
| 47 | + model: str | None = None |
| 48 | + provider: str | None = None |
| 49 | + request_id: str | None = None |
| 50 | + tags: dict[str, str] = field(default_factory=dict) |
| 51 | + |
| 52 | + |
| 53 | +@dataclass(frozen=True) |
| 54 | +class ChatHarnessFailure: |
| 55 | + code: FailureCode |
| 56 | + message: str |
| 57 | + retryable: bool |
| 58 | + detail: str | None = None |
| 59 | + |
| 60 | + |
| 61 | +@dataclass(frozen=True) |
| 62 | +class ChatHarnessRequest: |
| 63 | + message: str |
| 64 | + conversation_history: tuple[ConversationTurn, ...] = () |
| 65 | + request_id: str | None = None |
| 66 | + chat_session_id: int | None = None |
| 67 | + client_id: str | None = None |
| 68 | + metadata: dict[str, str] = field(default_factory=dict) |
| 69 | + |
| 70 | + def __post_init__(self) -> None: |
| 71 | + object.__setattr__(self, "conversation_history", tuple(self.conversation_history)) |
| 72 | + object.__setattr__(self, "metadata", dict(self.metadata)) |
| 73 | + |
| 74 | + |
| 75 | +@dataclass(frozen=True) |
| 76 | +class ChatHarnessResult: |
| 77 | + output_text: str | None = None |
| 78 | + finish_reason: str = "completed" |
| 79 | + failure: ChatHarnessFailure | None = None |
| 80 | + observability: ChatHarnessObservability = field(default_factory=ChatHarnessObservability) |
| 81 | + metadata: dict[str, str] = field(default_factory=dict) |
| 82 | + |
| 83 | + def __post_init__(self) -> None: |
| 84 | + object.__setattr__(self, "metadata", dict(self.metadata)) |
| 85 | + if self.failure is None and not self.output_text: |
| 86 | + raise ValueError("Successful harness results require output_text.") |
| 87 | + if self.failure is not None and self.output_text is not None: |
| 88 | + raise ValueError("Failed harness results cannot include output_text.") |
| 89 | + |
| 90 | + |
| 91 | +@dataclass(frozen=True) |
| 92 | +class ChatHarnessEvent: |
| 93 | + event_type: EventType |
| 94 | + output_text: str | None = None |
| 95 | + failure: ChatHarnessFailure | None = None |
| 96 | + observability: ChatHarnessObservability = field(default_factory=ChatHarnessObservability) |
| 97 | + sequence: int = 0 |
| 98 | + metadata: dict[str, str] = field(default_factory=dict) |
| 99 | + |
| 100 | + def __post_init__(self) -> None: |
| 101 | + object.__setattr__(self, "metadata", dict(self.metadata)) |
| 102 | + |
| 103 | + |
| 104 | +class ChatHarnessExecutionError(RuntimeError): |
| 105 | + """Raised when a harness fails with a normalized failure.""" |
| 106 | + |
| 107 | + def __init__(self, failure: ChatHarnessFailure): |
| 108 | + self.failure = failure |
| 109 | + super().__init__(failure.message) |
| 110 | + |
| 111 | + |
| 112 | +class ChatHarness(ABC): |
| 113 | + """App-facing contract for harness implementations.""" |
| 114 | + |
| 115 | + @property |
| 116 | + @abstractmethod |
| 117 | + def identity(self) -> ChatHarnessIdentity: |
| 118 | + """Return stable harness identity and display metadata.""" |
| 119 | + |
| 120 | + @property |
| 121 | + def capabilities(self) -> ChatHarnessCapabilities: |
| 122 | + return ChatHarnessCapabilities() |
| 123 | + |
| 124 | + @abstractmethod |
| 125 | + def run(self, request: ChatHarnessRequest) -> ChatHarnessResult: |
| 126 | + """Execute one harness request and return the normalized result.""" |
| 127 | + |
| 128 | + def run_events(self, request: ChatHarnessRequest) -> Iterator[ChatHarnessEvent]: |
| 129 | + result = self.run(request) |
| 130 | + if result.output_text is not None: |
| 131 | + yield ChatHarnessEvent( |
| 132 | + event_type="output_text", |
| 133 | + output_text=result.output_text, |
| 134 | + observability=result.observability, |
| 135 | + metadata=result.metadata, |
| 136 | + sequence=0, |
| 137 | + ) |
| 138 | + if result.failure is not None: |
| 139 | + yield ChatHarnessEvent( |
| 140 | + event_type="failed", |
| 141 | + failure=result.failure, |
| 142 | + observability=result.observability, |
| 143 | + metadata=result.metadata, |
| 144 | + sequence=1, |
| 145 | + ) |
| 146 | + return |
| 147 | + yield ChatHarnessEvent( |
| 148 | + event_type="completed", |
| 149 | + output_text=result.output_text, |
| 150 | + observability=result.observability, |
| 151 | + metadata=result.metadata, |
| 152 | + sequence=1, |
| 153 | + ) |
| 154 | + |
| 155 | + |
| 156 | +class BaseAgent(ChatHarness, ABC): |
| 157 | + """Compatibility layer for the legacy non-harness agent interface.""" |
| 158 | + |
| 159 | + @property |
| 160 | + @abstractmethod |
| 161 | + def display_name(self) -> str: |
| 162 | + """Return the display name for the agent to be shown in the header.""" |
| 163 | + |
| 164 | + @property |
| 165 | + @abstractmethod |
| 166 | + def model_display_name(self) -> str: |
| 167 | + """Return a user-friendly display name for the model.""" |
| 168 | + |
| 169 | + @property |
| 170 | + def identity(self) -> ChatHarnessIdentity: |
| 171 | + return ChatHarnessIdentity( |
| 172 | + key=self.__class__.__name__.lower(), |
| 173 | + display_name=self.display_name, |
| 174 | + model_display_name=self.model_display_name, |
| 175 | + ) |
| 176 | + |
| 177 | + def run(self, request: ChatHarnessRequest) -> ChatHarnessResult: |
| 178 | + try: |
| 179 | + response_text = self.process_message( |
| 180 | + request.message, |
| 181 | + request.conversation_history, |
| 182 | + ) |
| 183 | + except ValueError: |
| 184 | + raise |
| 185 | + except Exception as exc: |
| 186 | + raise ChatHarnessExecutionError(self.normalize_exception(exc)) from exc |
| 187 | + return ChatHarnessResult( |
| 188 | + output_text=response_text, |
| 189 | + observability=ChatHarnessObservability( |
| 190 | + model=self.model_display_name, |
| 191 | + request_id=request.request_id, |
| 192 | + ), |
| 193 | + ) |
| 194 | + |
| 195 | + def normalize_exception(self, exc: Exception) -> ChatHarnessFailure: |
| 196 | + return ChatHarnessFailure( |
| 197 | + code="unexpected_error", |
| 198 | + message="Harness execution failed.", |
| 199 | + retryable=False, |
| 200 | + detail=str(exc), |
| 201 | + ) |
| 202 | + |
| 203 | + @abstractmethod |
| 204 | + def process_message( |
| 205 | + self, |
| 206 | + message: str, |
| 207 | + conversation_history: Sequence[ConversationTurn] | None = None, |
| 208 | + ) -> str: |
| 209 | + """Process a user message and return a response.""" |
0 commit comments