File size: 3,160 Bytes
1f355ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deep mode against a fake model: no GPU needed.   python -m tests.test_deep"""
import argparse
import asyncio
import json

from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer

from deep import server as deep


def fake_upstream(answers, best):
    state = {"i": 0, "reviews": 0}

    async def chat(request):
        body = await request.json()
        text = body["messages"][-1]["content"]
        if "BEST: <number>" in text:                           # a review vote: always prefer the answer holding `best`
            state["reviews"] += 1
            import re
            blocks = re.findall(r'<answer number="(\d+)">\n(.*?)\n</answer>', text, flags=re.S)
            pick = next(n for n, t in blocks if best in t)
            content = f"Looked at them.\nBEST: {pick}"
        else:
            content = answers[state["i"] % len(answers)]
            state["i"] += 1
        return web.json_response({"id": "x", "object": "chat.completion", "model": body["model"],
                                  "choices": [{"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop"}],
                                  "usage": {"prompt_tokens": 5, "completion_tokens": 7}})
    app = web.Application()
    app.router.add_post("/v1/chat/completions", chat)
    return app, state


async def run(answers, best, n):
    up, state = fake_upstream(answers, best)
    us = TestServer(up)
    await us.start_server()
    args = argparse.Namespace(upstream=str(us.make_url("")).rstrip("/"), model="fake", attempts=16)
    client = TestClient(TestServer(await deep.make_app(args)))
    await client.start_server()
    r = await client.post("/v1/chat/completions", json={"model": deep.DEEP_ID, "n_attempts": n, "messages": [{"role": "user", "content": "2+2?"}]})
    out = await r.json()
    p = await client.post("/v1/chat/completions", json={"model": "fake", "messages": [{"role": "user", "content": "hi"}]})
    passed = await p.json()
    m = await (await client.get("/v1/models")).json()
    await client.close()
    await us.close()
    return out, state, passed, m


def main():
    out, state, passed, m = asyncio.run(run(["4", "4", " 4 ", "5"], "4", 4))
    assert out["choices"][0]["message"]["content"].strip() == "4" and out["deep"]["decided_by"] == "agreement", out
    assert out["deep"]["attempts"] == 4 and out["deep"]["distinct_answers"] == 2 and state["reviews"] == 0
    assert out["model"] == deep.DEEP_ID and passed["model"] == "fake" and {x["id"] for x in m["data"]} == {"fake", deep.DEEP_ID}
    print("ok  agreement: 3 of 4 attempts agree, that answer is returned, no review call")
    out, state, _, _ = asyncio.run(run(["a wrong one", "another wrong one", "the right one", "yet another"], "the right one", 4))
    assert out["choices"][0]["message"]["content"] == "the right one" and out["deep"]["decided_by"] == "review", out
    assert state["reviews"] == 3 and sum(out["deep"]["votes"].values()) == 3
    print("ok  review: 4 distinct answers, three votes with rotated order, the voted answer is returned")
    print(json.dumps(out["deep"]))


if __name__ == "__main__":
    main()