File size: 7,679 Bytes
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
220
221
222
223
224
225
226
227
228
229
"""Gradio server for the compiled frontend and its same-origin streaming API."""

import asyncio
import ipaddress
import json
import pathlib
import secrets
import time
from typing import cast

import fastapi
import gradio
import httpx
from backend import (
  beam_client,
  beam_status,
  iris_content_guard,
  turns,
  workspace,
)
from starlette import responses, staticfiles


def _endpoint(value: str, setting: str) -> httpx.URL:
  url = httpx.URL(value)
  if (
    url.scheme not in {'http', 'https'}
    or not url.host
    or url.userinfo
    or url.query
    or url.fragment
  ):
    raise ValueError(
      f'{setting} must be an HTTP(S) base URL without credentials, query or fragment'
    )
  if url.scheme == 'http' and not _loopback(url.host):
    raise ValueError(f'{setting} requires HTTPS for a remote endpoint.')
  path = url.raw_path.rstrip(b'/').removesuffix(b'/v1')
  return url.copy_with(raw_path=path + b'/')


def _loopback(host: str) -> bool:
  if host == 'localhost':
    return True
  try:
    return ipaddress.ip_address(host).is_loopback
  except ValueError:
    return False


def create_app(
  dist: pathlib.Path,
  beam_url: str,
  beam_token: str | None,
  score_url: str | None = None,
) -> gradio.Server:
  """Create one Space process; each browser receives its own session capability."""
  url = _endpoint(beam_url, 'BEAM_URL')
  monitor = beam_status.BeamStatus(url, beam_token)
  app = gradio.Server()
  sessions: dict[str, turns.Session] = {}
  monitor_url = (
    _endpoint(score_url, 'IRIS_BEAM_SCORE_URL') if score_url else None
  )

  @app.api(  # pyright: ignore[reportUnknownMemberType]
    name='score_turn', api_visibility='undocumented', concurrency_limit=2
  )
  async def score_turn(
    turn: int, request: gradio.Request
  ) -> iris_content_guard.TurnScores:
    session = sessions.get(request.headers.get('x-iris-session', ''))
    if session is None or session.expired(time.monotonic()):
      raise ValueError('Session expired')
    end = session.pending_score_ends.pop(turn, None)
    if end is None:
      raise ValueError('No pending Iris Content Guard score for this turn')
    return await asyncio.to_thread(
      iris_content_guard.score_conversation, session.visible_messages[:end]
    )

  def home() -> responses.FileResponse:
    return responses.FileResponse(dist / 'index.html')

  def license_file() -> responses.FileResponse:
    return responses.FileResponse(dist / 'plex-ofl.txt')

  app.mount(
    '/assets',
    staticfiles.StaticFiles(directory=dist / 'assets'),
    name='iris_assets',
  )

  initial_files = workspace.Workspace().listing()

  async def status() -> dict[str, str]:
    return {'state': await monitor.read()}

  def config() -> dict[str, object]:
    return {'cutoff': turns.CUTOFF, 'files': initial_files}

  def error(code: int, message: str) -> responses.JSONResponse:
    return responses.JSONResponse(
      {'error': message},
      status_code=code,
      headers={'Cache-Control': 'no-store'},
    )

  def lookup(request: fastapi.Request) -> tuple[str, turns.Session | None]:
    now = time.monotonic()
    for key, session in list(sessions.items()):
      if session.expired(now):
        del sessions[key]
    # Hugging Face uses Authorization for the visitor's ZeroGPU identity.
    key = request.headers.get('x-iris-session', '')
    return key, sessions.get(key)

  def starter_workspace(request: fastapi.Request) -> workspace.Workspace:
    seed = request.headers.get('x-iris-workspace-seed', '')
    return workspace.Workspace(entries=workspace.initial_files(seed))

  async def read_file(
    request: fastapi.Request, name: str = fastapi.Body(embed=True)
  ) -> responses.Response:
    """Read starter files statelessly. Live file reads refresh the chat timeout."""
    if name == 'api-key.txt':
      return error(403, 'Permission denied.')
    session = None
    if 'x-iris-session' in request.headers:
      _, session = lookup(request)
      if session is None:
        return error(401, 'Session expired. Start a new session.')
    guest = session.workspace if session else starter_workspace(request)
    text = guest.read_file(name)
    if text is None:
      return error(404, 'This file no longer exists in your workspace.')
    if session:
      session.last_used = time.monotonic()
    return responses.JSONResponse(text, headers={'Cache-Control': 'no-store'})

  async def session_state(request: fastapi.Request) -> responses.Response:
    _, session = lookup(request)
    if session is None:
      return error(401, 'Session expired. Start a new session.')
    if session.active_request is not None:
      return error(
        409, 'Beam is still processing the previous turn. Try again shortly.'
      )
    return responses.JSONResponse(
      {
        'turn': session.turns,
        'completed': session.completed_turn,
        'stopped': session.stopped,
        'files': session.workspace.listing(),
      },
      headers={'Cache-Control': 'no-store'},
    )

  async def reset(request: fastapi.Request) -> responses.Response:
    key, session = lookup(request)
    if session is None:
      return error(401, 'Session expired. Start a new session.')
    del sessions[key]
    session.close()
    return responses.JSONResponse({})

  async def turn(request: fastapi.Request) -> responses.Response:
    if (
      request.headers.get('content-type', '').partition(';')[0]
      != 'application/json'
    ):
      return error(415, 'Expected a JSON request.')
    body = bytearray()
    async for chunk in request.stream():
      if len(body) + len(chunk) > 16384:
        return error(413, 'Request is too large.')
      body.extend(chunk)
    try:
      payload = json.loads(body)
    except (ValueError, UnicodeDecodeError, RecursionError):
      return error(400, 'Invalid JSON.')
    prompt = (
      cast(dict[str, object], payload).get('prompt')
      if isinstance(payload, dict)
      else None
    )
    if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 1600:
      return error(400, 'Enter a prompt of 1 to 1600 characters.')
    key, session = lookup(request)
    if session is None:
      if 'x-iris-session' in request.headers:
        return error(401, 'Session expired. Start a new session.')
      if len(sessions) >= 1000:
        return error(503, 'Session capacity reached. Try again later.')
      key = secrets.token_urlsafe(32)
      sessions[key] = session = turns.Session(
        workspace=starter_workspace(request)
      )
    if (
      session.active_request is not None
      or session.stopped
      or session.turns >= 64
    ):
      return error(409, 'Session busy, stopped or full. Start a new session.')
    # Reserve this session before StreamingResponse starts its iterator.
    session.active_request = asyncio.current_task()
    session.turns += 1
    stream = turns.events(
      session,
      key,
      prompt.strip(),
      beam_client.connect(url, beam_token, monitor_url),
    )
    return responses.StreamingResponse(
      stream,
      media_type='application/x-ndjson',
      headers={'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no'},
    )

  app.add_api_route('/', home, methods=['GET', 'HEAD'])
  app.add_api_route('/plex-ofl.txt', license_file, methods=['GET', 'HEAD'])
  app.add_api_route('/api/beam-status', status, methods=['GET'])
  app.add_api_route('/api/config', config, methods=['GET'])
  app.add_api_route('/api/workspace/file', read_file, methods=['POST'])
  app.add_api_route('/api/session', session_state, methods=['GET'])
  app.add_api_route('/api/session', reset, methods=['DELETE'])
  app.add_api_route('/api/turns', turn, methods=['POST'])
  return app