Spaces:
Running on Zero
Running on Zero
File size: 6,692 Bytes
baa274b cc92231 baa274b cc92231 baa274b cc92231 baa274b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | """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
@dataclasses.dataclass
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
|