File size: 7,287 Bytes
741ca6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deep mode as one model id: `rightnow-mini-deep`.

An OpenAI-compatible server in front of a RightNow Mini endpoint. A request for `rightnow-mini-deep` is fanned out to
N sampled attempts in parallel (default 16), a verifier picks one, and that one answer is returned. Any other model
id is passed through unchanged.

    python deep/server.py --upstream http://127.0.0.1:9000 --model inkling-2-mini --port 9100

The verifier uses only what the caller sent:
  1. agreement: if more than half of the attempts give the same answer (white space ignored), that answer wins;
  2. review: otherwise the model reads the request and the distinct answers and votes three times with the answers
     in a different order each time; the most voted answer wins, then the one more attempts agreed on.
Per-request fields (optional): "n_attempts" (1 to 64), "attempt_temperature" (default 0.8).
The reply carries a "deep" object: attempts, distinct answers, how it was decided, seconds, tokens used.
"""
import argparse
import asyncio
import collections
import json
import re
import time

import aiohttp
from aiohttp import web

DEEP_ID = "rightnow-mini-deep"
REVIEW = """Several answers were written for the same request. Pick the one that is most correct and complete.

<request>
{req}
</request>

{cands}

Think it through, then end with a line of the form: BEST: <number>"""


def norm(text):
    return re.sub(r"\s+", " ", text or "").strip()


def last_user(messages):
    for m in reversed(messages):
        if m.get("role") == "user":
            c = m.get("content")
            return c if isinstance(c, str) else json.dumps(c)
    return ""


async def call(session, url, body):
    async with session.post(url + "/v1/chat/completions", json=body) as r:
        d = await r.json()
        if r.status != 200:
            raise web.HTTPBadGateway(text=json.dumps(d)[:500])
        return d


async def deep(app, body):
    a, s = app["args"], app["session"]
    n = max(1, min(64, int(body.pop("n_attempts", a.attempts))))
    temp = float(body.pop("attempt_temperature", 0.8))
    base = {k: v for k, v in body.items() if k not in ("stream", "n", "stream_options")}
    base.update(model=a.model, temperature=temp)
    t0 = time.perf_counter()
    done = await asyncio.gather(*[call(s, a.upstream, dict(base)) for _ in range(n)], return_exceptions=True)
    ok = [d for d in done if isinstance(d, dict) and d.get("choices")]
    if not ok:
        raise web.HTTPBadGateway(text="no attempt returned an answer")
    tokens = sum((d.get("usage") or {}).get("completion_tokens", 0) for d in ok)
    groups = collections.defaultdict(list)
    for d in ok:
        groups[norm(d["choices"][0]["message"].get("content"))].append(d)
    ranked = sorted(groups.values(), key=len, reverse=True)
    how, votes = "agreement", {}
    best = 0
    if len(ranked) > 1 and len(ranked[0]) * 2 <= len(ok):
        how = "review"
        cands = list(range(min(len(ranked), 8)))
        tally = collections.Counter()

        async def vote(rot):
            order = cands[rot % len(cands):] + cands[:rot % len(cands)]
            text = "\n\n".join(f"<answer number=\"{i + 1}\">\n{(ranked[g][0]['choices'][0]['message'].get('content') or '')[:12000]}\n</answer>"
                               for i, g in enumerate(order))
            # reasoning effort 0.3 and a large budget: at the model's default effort (0.9) and 4,096 tokens most reviews
            # ended while still reasoning, with no answer (results/deep.md)
            d = await call(s, a.upstream, {"model": a.model, "temperature": 0, "max_tokens": 16384,
                                           "chat_template_kwargs": {"reasoning_effort": 0.3}, "messages": [
                {"role": "user", "content": REVIEW.format(req=last_user(body.get("messages", []))[:16000], cands=text)}]})
            msg = d["choices"][0]["message"]
            said = msg.get("content") or ""
            if "BEST:" not in said:
                said += "\n" + (msg.get("reasoning") or msg.get("reasoning_content") or "")
            m = re.findall(r"BEST:\s*(\d+)", said)
            return (order[int(m[-1]) - 1] if m and 1 <= int(m[-1]) <= len(order) else None), (d.get("usage") or {}).get("completion_tokens", 0)
        for r in await asyncio.gather(*[vote(i) for i in range(3)], return_exceptions=True):
            if isinstance(r, tuple):
                tokens += r[1]
                if r[0] is not None:
                    tally[r[0]] += 1
        votes = dict(tally)
        best = max(cands, key=lambda g: (tally.get(g, 0), len(ranked[g])))
    out = dict(ranked[best][0])
    out["model"] = DEEP_ID
    out["deep"] = {"attempts": n, "answered": len(ok), "distinct_answers": len(ranked), "decided_by": how, "votes": votes,
                   "agreeing_attempts": len(ranked[best]), "seconds": round(time.perf_counter() - t0, 3), "completion_tokens_all": tokens}
    return out


async def chat(request):
    app = request.app
    body = await request.json()
    stream = bool(body.get("stream"))
    if body.get("model") != DEEP_ID:
        async with app["session"].post(app["args"].upstream + "/v1/chat/completions", json=body) as r:
            if not stream:
                return web.Response(status=r.status, body=await r.read(), content_type="application/json")
            resp = web.StreamResponse(status=r.status, headers={"Content-Type": "text/event-stream"})
            await resp.prepare(request)
            async for chunk in r.content.iter_any():
                await resp.write(chunk)
            return resp
    out = await deep(app, body)
    if not stream:
        return web.json_response(out)
    resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
    await resp.prepare(request)
    msg = out["choices"][0]["message"]
    chunk = {"id": out.get("id"), "object": "chat.completion.chunk", "model": DEEP_ID, "deep": out["deep"],
             "choices": [{"index": 0, "delta": {"role": "assistant", "content": msg.get("content") or ""}, "finish_reason": out["choices"][0].get("finish_reason")}]}
    await resp.write(f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n".encode())
    return resp


async def models(request):
    a = request.app["args"]
    return web.json_response({"object": "list", "data": [{"id": a.model, "object": "model"}, {"id": DEEP_ID, "object": "model"}]})


async def make_app(args):
    app = web.Application(client_max_size=64 * 2**20)
    app["args"] = args
    app["session"] = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3600), connector=aiohttp.TCPConnector(limit=0))
    app.router.add_post("/v1/chat/completions", chat)
    app.router.add_get("/v1/models", models)

    async def close(app):
        await app["session"].close()
    app.on_cleanup.append(close)
    return app


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--upstream", default="http://127.0.0.1:9000")
    ap.add_argument("--model", default="rightnow-mini")
    ap.add_argument("--attempts", type=int, default=16)
    ap.add_argument("--host", default="127.0.0.1")
    ap.add_argument("--port", type=int, default=9100)
    args = ap.parse_args()
    web.run_app(make_app(args), host=args.host, port=args.port, print=None)


if __name__ == "__main__":
    main()