Files
pipewright/tests/test_proxy.py
T

60 lines
2.8 KiB
Python

import asyncio
import json
import httpx
from pipewright.models.base import ModelClient
from pipewright.models.fake import FakeProvider
from pipewright.models.proxy import LoggingProxy
from pipewright.project import ModelAlias
def make_client(cfg=None):
prov = FakeProvider("f", cfg or {"rules": [{"match": "hello", "content": "hi there"}]})
return ModelClient("a", ModelAlias(provider="f", model="fake-m", max_retries=1, cache=False), prov)
def test_proxy_records_turns_and_streams():
async def main():
proxy = LoggingProxy()
port = await proxy.listen("127.0.0.1")
s = proxy.open_session(make_client())
base = f"http://127.0.0.1:{port}/v1"
async with httpx.AsyncClient() as http:
h = {"Authorization": f"Bearer {s.token}"}
r1 = await http.post(f"{base}/chat/completions", headers=h,
json={"model": "whatever", "messages": [{"role": "user", "content": "hello"}]})
msgs = [{"role": "user", "content": "hello"}, r1.json()["choices"][0]["message"],
{"role": "user", "content": "hello again"}]
r2 = await http.post(f"{base}/chat/completions", headers=h,
json={"model": "whatever", "messages": msgs, "stream": True})
bad = await http.post(f"{base}/chat/completions", headers={"Authorization": "Bearer nope"}, json={})
models = await http.get(f"{base}/models", headers=h)
await proxy.aclose()
return s, r1, r2, bad, models
s, r1, r2, bad, models = asyncio.run(main())
assert r1.status_code == 200 and r1.json()["choices"][0]["message"]["content"] == "hi there"
assert r2.headers["content-type"] == "text/event-stream"
events = [json.loads(line[6:]) for line in r2.text.splitlines() if line.startswith("data: {")]
assert events[0]["choices"][0]["delta"]["content"] == "hi there"
assert bad.status_code == 401 and models.json()["data"][0]["id"] == "fake-m"
assert len(s.turns) == 2 and {t["conversation"] for t in s.turns} == {"c0"} # continuation detected
assert len(s.messages()) == 4 and not s.failed_last_call
def test_proxy_surfaces_provider_failure():
async def main():
proxy = LoggingProxy()
port = await proxy.listen("127.0.0.1")
s = proxy.open_session(make_client({"fail": {"first": 99, "status": 503}}))
async with httpx.AsyncClient() as http:
r = await http.post(f"http://127.0.0.1:{port}/v1/chat/completions",
headers={"Authorization": f"Bearer {s.token}"},
json={"messages": [{"role": "user", "content": "x"}]})
await proxy.aclose()
return s, r
s, r = asyncio.run(main())
assert r.status_code == 503 and s.failed_last_call and s.turns[-1]["status"] == 503