Spaces:
Running on Zero
Running on Zero
Download backend/turns.py from reflection/iris: direct link, hf CLI and curl.
- Browser
- Download file 6.69 kB
-
https://huggingface.co/spaces/reflection/iris/resolve/main/backend/turns.py
- Command line
-
hf download hf://spaces/reflection/iris/backend/turns.py
-
curl -L -o turns.py https://huggingface.co/spaces/reflection/iris/resolve/main/backend/turns.py
6.69 kB
| """Per-tab history, guest Bash, and the streamed browser contract.""" | |
| import asyncio | |
| import contextlib | |
| import dataclasses | |
| import json | |
| import time | |
| from collections.abc import AsyncGenerator, AsyncIterator | |
| import httpx | |
| from backend import beam_client | |
| from backend import workspace as guest | |
| CUTOFF = -1.618 | |
| _MAX_CALLS = 6 | |
| class Session: | |
| workspace: guest.Workspace = dataclasses.field( | |
| default_factory=guest.Workspace | |
| ) | |
| history: list[beam_client.Message] = dataclasses.field( | |
| default_factory=lambda: [beam_client.SYSTEM_MESSAGE] | |
| ) | |
| visible_messages: list[dict[str, str]] = dataclasses.field( | |
| default_factory=list | |
| ) | |
| active_request: asyncio.Task[object] | None = None | |
| # Each pending turn owns a prefix of visible_messages, even if later turns finish first. | |
| pending_score_ends: dict[int, int] = dataclasses.field( | |
| default_factory=dict[int, int] | |
| ) | |
| turns: int = 0 | |
| completed_turn: int = 0 | |
| stopped: bool = False | |
| closed: bool = False | |
| last_used: float = dataclasses.field(default_factory=time.monotonic) | |
| def expired(self, now: float) -> bool: | |
| """Return whether the workspace has been idle for 30 minutes.""" | |
| return self.active_request is None and now - self.last_used > 1800 | |
| def close(self) -> None: | |
| """Invalidate the session and interrupt all outstanding turn streams.""" | |
| self.closed = True | |
| self.pending_score_ends.clear() | |
| if self.active_request is not None: | |
| self.active_request.cancel() | |
| async def _pieces( | |
| history: list[beam_client.Message], | |
| workspace: guest.Workspace, | |
| client: beam_client.BeamClient, | |
| ) -> AsyncGenerator[beam_client.Piece]: | |
| command = None | |
| for pass_number in range(_MAX_CALLS + 1): | |
| reasoning = '' | |
| reply = '' | |
| action = None | |
| missing_score = False | |
| async with contextlib.aclosing( | |
| client.stream_completion( | |
| history, | |
| tool_command=command, | |
| allow_tools=pass_number < _MAX_CALLS, | |
| ) | |
| ) as stream: | |
| async for item in stream: | |
| if isinstance(item, beam_client.Finish): | |
| action = item | |
| else: | |
| if item['source'] == 'Beam' and item.get('score') is None: | |
| missing_score = True | |
| if item['channel'] == 'reasoning': | |
| reasoning += item.get('display', item['text']) | |
| elif item['channel'] == 'reply': | |
| reply += item.get('display', item['text']) | |
| yield item | |
| if action is None: | |
| raise ValueError('Missing Beam finish') | |
| if action.reason in ('stop', 'length'): | |
| if reply.strip() or reasoning: | |
| history.append({ | |
| 'role': 'assistant', | |
| 'content': reply, | |
| 'reasoning_content': reasoning, | |
| }) | |
| return | |
| if pass_number == _MAX_CALLS or action.reason != 'tool_calls': | |
| raise ValueError('Unexpected tool call') | |
| command = guest.command_from(action.call) | |
| result = ( | |
| 'Tool call skipped because a probe score was unavailable.' | |
| if missing_score | |
| else await workspace.run(command) | |
| ) | |
| history.append({ | |
| 'role': 'assistant', | |
| 'content': reply or None, | |
| 'reasoning_content': reasoning, | |
| 'tool_calls': [action.call], | |
| }) | |
| history.append({ | |
| 'role': 'tool', | |
| 'tool_call_id': action.call['id'], | |
| 'content': result, | |
| }) | |
| async def events( | |
| session: Session, | |
| session_id: str, | |
| prompt: str, | |
| connection: contextlib.AbstractAsyncContextManager[beam_client.BeamClient], | |
| ) -> AsyncIterator[bytes]: | |
| """Stream a Beam turn and retain its visible conversation for scoring.""" | |
| turn = session.turns | |
| def emit(kind: str, **fields: object) -> bytes: | |
| return ( | |
| json.dumps({'type': kind, 'turn': turn, **fields}, allow_nan=False) + '\n' | |
| ).encode() | |
| if session.closed: | |
| return | |
| session.active_request = asyncio.current_task() | |
| try: | |
| yield emit( | |
| 'start', | |
| prompt=prompt, | |
| cutoff=CUTOFF, | |
| **({'id': session_id} if turn == 1 else {}), | |
| ) | |
| user = {'role': 'user', 'content': prompt} | |
| # Commit the model history and guest files together after generation succeeds. | |
| history = [*session.history, user] | |
| workspace = dataclasses.replace(session.workspace) | |
| reply = '' | |
| async with connection as client: | |
| waiting = False | |
| try: | |
| async with asyncio.timeout(600): | |
| while not await client.ready(): | |
| waiting = True | |
| yield emit('beam_status', ready=False) | |
| await asyncio.sleep(5) | |
| except TimeoutError: | |
| yield emit( | |
| 'error', | |
| message='Beam is still unavailable. Please try again in a few minutes.', | |
| ) | |
| return | |
| if waiting: | |
| yield emit('beam_status', ready=True) | |
| async with ( | |
| asyncio.timeout(90), | |
| contextlib.aclosing(_pieces(history, workspace, client)) as stream, | |
| ): | |
| async for piece in stream: | |
| if piece['channel'] == 'reply': | |
| reply += piece.get('display', piece['text']) | |
| logit = piece.get('logit') | |
| session.stopped = ( | |
| logit is not None | |
| and piece['owner'] == 'assistance' | |
| and logit >= CUTOFF | |
| ) | |
| yield emit('piece', piece=piece) | |
| if session.stopped: | |
| break | |
| if not session.stopped: | |
| session.history = history | |
| session.workspace = workspace | |
| session.visible_messages.append(user) | |
| if reply.strip(): | |
| session.visible_messages.append({'role': 'assistant', 'content': reply}) | |
| session.pending_score_ends[turn] = len(session.visible_messages) | |
| session.completed_turn = turn | |
| terminal = emit( | |
| 'end', stopped=session.stopped, files=session.workspace.listing() | |
| ) | |
| except asyncio.CancelledError: | |
| if session.closed: | |
| return | |
| raise | |
| except httpx.HTTPStatusError as exc: | |
| path = exc.request.url.path | |
| if path.endswith(( | |
| '/v1/models', | |
| '/v1/chat/completions', | |
| )) and exc.response.status_code in (502, 503, 504): | |
| message = 'Beam is unavailable and may be starting up. Please try again in a few minutes.' | |
| elif path.endswith('/v1/models'): | |
| message = ( | |
| f'Beam readiness check returned HTTP {exc.response.status_code}.' | |
| ) | |
| else: | |
| message = 'Beam scoring was interrupted. Send your message again.' | |
| terminal = emit('error', message=message) | |
| except ( | |
| httpx.HTTPError, | |
| TimeoutError, | |
| ValueError, | |
| KeyError, | |
| IndexError, | |
| AttributeError, | |
| TypeError, | |
| OSError, | |
| ): | |
| terminal = emit( | |
| 'error', message='Beam scoring was interrupted. Send your message again.' | |
| ) | |
| finally: | |
| session.active_request = None | |
| session.last_used = time.monotonic() | |
| yield terminal | |