File size: 12,661 Bytes
83add3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a51d6a
83add3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a51d6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83add3c
 
 
 
 
 
 
 
 
 
 
 
9a51d6a
83add3c
 
 
 
 
 
 
d4017c8
83add3c
d4017c8
 
83add3c
 
9a51d6a
 
83add3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4017c8
 
 
 
 
 
 
 
 
 
 
 
83add3c
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""Speed-oriented orchestration helpers.

Parallel participant turns, compact orchestrator context, and fast-
model routing for lightweight classifier calls. Keeps the same
visible message count while shortening wall-clock time.
"""
from __future__ import annotations

import asyncio
import logging
import re
from dataclasses import dataclass, field
from typing import Any, AsyncIterator, Awaitable, Callable, TYPE_CHECKING

from app.services.resilience import ResilientTurnResult, run_resilient_turn

if TYPE_CHECKING:
    from app.services.models import Participant, Phase, Session

LOG = logging.getLogger(__name__)

# Rough char budget for orchestrator-side prompts that would otherwise
# resend the entire transcript every few turns.
ORCHESTRATOR_TRANSCRIPT_CHAR_BUDGET = 14_000
_RECENT_TAIL_MESSAGES = 24

CallParticipantFn = Callable[..., Awaitable[tuple[str, float, bool, str]]]


@dataclass
class _AiTurnSpec:
    participant: "Participant"
    user_prompt: str
    label: str
    max_tokens: int


@dataclass
class _AiTurnResult:
    participant: "Participant"
    turn: ResilientTurnResult
    pending: list[tuple[str, str, str]] = field(default_factory=list)


def orchestrator_fast_model_id(session: "Session") -> str:
    """Model for lightweight orchestrator classifiers (addressed-to, status)."""
    from app.config import settings
    from app.services.orchestrator import _orchestrator_model_id

    fast = (getattr(settings, "orchestrator_fast_model", None) or "").strip()
    if fast and settings.resolve_model(fast):
        return fast
    return _orchestrator_model_id(session)


def _format_history_for_orchestrator(
    messages: list[dict[str, Any]],
    *,
    include_orchestrator: bool = True,
) -> str:
    from app.services.orchestrator import _format_history

    return _format_history(messages, include_orchestrator=include_orchestrator)


async def compact_transcript_for_orchestrator(
    session: "Session",
    *,
    orchestrator_model_id: str,
) -> str:
    """Return a transcript block sized for orchestrator judge prompts.

    Uses a rolling summary + recent tail when the full history exceeds
    the char budget. Summaries are built lazily (one extra orchestrator
    call) and cached on the session.
    """
    from app.services.json_calls import orchestrator_call
    from app.services.orchestrator import _bump_orchestrator_count

    messages = session.messages
    full = _format_history_for_orchestrator(messages)
    if len(full) <= ORCHESTRATOR_TRANSCRIPT_CHAR_BUDGET:
        return full

    tail = messages[-_RECENT_TAIL_MESSAGES:]
    tail_text = _format_history_for_orchestrator(tail)
    through = len(messages) - len(tail)
    if (
        session.orchestrator_context_summary
        and session.orchestrator_context_through_idx >= through - 2
    ):
        return (
            "[Earlier discussion summary]\n"
            f"{session.orchestrator_context_summary}\n\n"
            "[Recent messages]\n"
            f"{tail_text}"
        )

    prompt = (
        "Summarize the following group discussion for an orchestrator that "
        "will judge consensus and open questions. Preserve names, stances, "
        "and unresolved disagreements. Be concise (under 400 words).\n\n"
        f"{full}"
    )
    raw, _ = await orchestrator_call(
        orchestrator_model_id=orchestrator_model_id,
        user_prompt=prompt,
        label="orchestrator_transcript_summary",
        api_log=session.api_log,
        expect_json=False,
        max_tokens=700,
        temperature=0.2,
    )
    _bump_orchestrator_count(session)
    summary = (raw or "").strip() or full[-ORCHESTRATOR_TRANSCRIPT_CHAR_BUDGET:]
    session.orchestrator_context_summary = summary
    session.orchestrator_context_through_idx = through
    return (
        "[Earlier discussion summary]\n"
        f"{summary}\n\n"
        "[Recent messages]\n"
        f"{tail_text}"
    )


async def _execute_ai_turn(
    session: "Session",
    spec: _AiTurnSpec,
    call_participant: CallParticipantFn,
) -> _AiTurnResult:
    from app.services.orchestrator import _pending_addressed_for

    pending = _pending_addressed_for(session, spec.participant)
    turn = await run_resilient_turn(
        session=session,
        participant=spec.participant,
        user_prompt=spec.user_prompt,
        label=spec.label,
        max_tokens=spec.max_tokens,
        call_participant=call_participant,
    )
    return _AiTurnResult(
        participant=spec.participant,
        turn=turn,
        pending=pending,
    )


PostProcessFn = Callable[
    [_AiTurnResult],
    Awaitable[dict[str, Any] | None],
]


async def run_roster_ai_turns_parallel(
    session: "Session",
    actives: list["Participant"],
    *,
    phase: "Phase",
    build_spec: Callable[["Participant"], _AiTurnSpec | None],
    call_participant: CallParticipantFn,
    on_human_turn: Callable[
        ["Participant"],
        AsyncIterator[str],
    ],
    post_process: PostProcessFn | None = None,
) -> AsyncIterator[str]:
    """Run participant turns: humans sequentially, AI in parallel batches.

    Walks `actives` in roster order. Consecutive AI participants are
    executed with ``asyncio.gather``; results are applied in roster
    order so the message log stays deterministic. Humans are awaited
    one at a time via ``on_human_turn``.

    Yields orchestrator SSE strings (status, message, errors, etc.).
    """
    from app.services.orchestrator import (
        _msg_payload,
        _participant_msg_cap_hit,
        _participant_turn_failure_sse,
        _sse,
        _wait_for_continue,
    )

    ai_batch: list[_AiTurnSpec] = []

    async def flush_ai_batch() -> AsyncIterator[str]:
        nonlocal ai_batch
        if not ai_batch:
            return
        specs = ai_batch
        ai_batch = []
        results = await asyncio.gather(
            *[
                _execute_ai_turn(session, spec, call_participant)
                for spec in specs
            ],
            return_exceptions=True,
        )
        for spec, item in zip(specs, results):
            if isinstance(item, BaseException):
                LOG.exception(
                    "Parallel turn failed for %s: %s",
                    spec.participant.participant_id,
                    item,
                )
                yield _sse("participant_error", {
                    "participant_id": spec.participant.participant_id,
                    "name": spec.participant.name,
                    "phase": phase.value,
                })
                continue
            extra: dict[str, Any] | None = None
            if post_process is not None:
                extra = await post_process(item) or {}
            async for chunk in _emit_ai_turn_result(
                session, item, phase=phase, extra=extra,
            ):
                yield chunk
            if _participant_msg_cap_hit(session):
                async for chunk in _wait_for_continue(session, "messages"):
                    yield chunk

    for p in actives:
        if p.kind == "human":
            async for chunk in flush_ai_batch():
                yield chunk
            async for chunk in on_human_turn(p):
                yield chunk
            continue

        spec = build_spec(p)
        if spec is None:
            continue
        ai_batch.append(spec)

    async for chunk in flush_ai_batch():
        yield chunk


async def run_initial_opinions_roster(
    session: "Session",
    actives: list["Participant"],
    *,
    build_spec: Callable[["Participant"], _AiTurnSpec | None],
    call_participant: CallParticipantFn,
    on_human_turn: Callable[
        ["Participant"],
        AsyncIterator[str],
    ],
    post_process: PostProcessFn | None = None,
) -> AsyncIterator[str]:
    """Phase-1 roster walk with human-aware AI prefetch.

    When a human is in the roster, every AI participant's initial-
    opinion call is fired immediately (in parallel) so answers are ready
    while the human types. SSE ``message`` events are still emitted in
    roster order: any LLMs listed before the human appear as soon as
    their prefetch completes, and LLMs after the human stay hidden until
    the human submits (or skips).
    """
    from app.services.models import Phase
    from app.services.orchestrator import (
        _participant_msg_cap_hit,
        _sse,
        _wait_for_continue,
    )

    phase = Phase.INITIAL_OPINIONS
    has_human = any(p.kind == "human" for p in actives)
    if not has_human:
        async for chunk in run_roster_ai_turns_parallel(
            session,
            actives,
            phase=phase,
            build_spec=build_spec,
            call_participant=call_participant,
            on_human_turn=on_human_turn,
            post_process=post_process,
        ):
            yield chunk
        return

    pending: dict[str, asyncio.Task[_AiTurnResult]] = {}
    for p in actives:
        if p.kind == "human":
            continue
        spec = build_spec(p)
        if spec is None:
            continue
        pending[p.participant_id] = asyncio.create_task(
            _execute_ai_turn(session, spec, call_participant),
            name=f"prefetch_initial:{p.participant_id}",
        )

    for p in actives:
        if p.kind == "human":
            async for chunk in on_human_turn(p):
                yield chunk
            if _participant_msg_cap_hit(session):
                async for chunk in _wait_for_continue(session, "messages"):
                    yield chunk
            continue

        task = pending.pop(p.participant_id, None)
        if task is None:
            continue
        try:
            result = await task
        except BaseException as exc:
            LOG.exception(
                "Prefetched initial opinion failed for %s: %s",
                p.participant_id,
                exc,
            )
            yield _sse("participant_error", {
                "participant_id": p.participant_id,
                "name": p.name,
                "phase": phase.value,
            })
            continue

        extra: dict[str, Any] | None = None
        if post_process is not None:
            extra = await post_process(result) or {}
        async for chunk in _emit_ai_turn_result(
            session, result, phase=phase, extra=extra,
        ):
            yield chunk
        if _participant_msg_cap_hit(session):
            async for chunk in _wait_for_continue(session, "messages"):
                yield chunk

    for pid, task in pending.items():
        if not task.done():
            task.cancel()


async def _emit_ai_turn_result(
    session: "Session",
    result: _AiTurnResult,
    *,
    phase: "Phase",
    extra: dict[str, Any] | None = None,
) -> AsyncIterator[str]:
    """Apply a completed AI turn to the session and yield SSE."""
    from app.services.orchestrator import (
        _add_participant_message,
        _msg_payload,
        _orchestrator_cap_hit,
        _participant_turn_failure_sse,
        _replying_to_ids,
        _sse,
        _wait_for_continue,
    )

    p = result.participant
    turn = result.turn
    substituted = False
    for ev in turn.sse_events:
        if "participant_substituted" in ev:
            substituted = True
        yield ev
    if not turn.ok:
        for chunk in _participant_turn_failure_sse(session, p):
            yield chunk
        return

    speaker = turn.speaker
    meta = extra or {}
    msg = _add_participant_message(
        session,
        speaker,
        turn.text,
        phase=phase,
        elapsed=turn.elapsed,
        addressed_to=meta.get("addressed_to"),
        replying_to=meta.get(
            "replying_to",
            _replying_to_ids(result.pending),
        ),
        message_id=meta.get("message_id"),
    )
    yield _sse("message", _msg_payload(msg))

    if substituted:
        from app.services.orchestrator import (
            _rebuild_participant_credential_on_model_change,
        )
        if await _rebuild_participant_credential_on_model_change(
            session, speaker,
        ):
            yield _sse("credentials_updated", {
                "stage": "model_changed",
                "credentials": session.credential_summary,
            })

    if _orchestrator_cap_hit(session):
        async for chunk in _wait_for_continue(session, "orchestrator"):
            yield chunk


async def run_parallel_coroutines(
    coros: list[Awaitable[Any]],
) -> list[Any]:
    """Gather with exception isolation (failed tasks become exceptions)."""
    return await asyncio.gather(*coros, return_exceptions=True)