Files
pipewright/tests/test_models.py
T

105 lines
4.5 KiB
Python

import asyncio
import json
import httpx
import pytest
from pipewright.errors import ProviderError
from pipewright.models.base import ModelClient
from pipewright.models.fake import FakeProvider, sample_from_schema
from pipewright.models.openai_compat import OpenAICompatProvider
from pipewright.project import ModelAlias
from pipewright.store import Store
OK = {"id": "x", "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 5, "completion_tokens": 1}}
def provider(handler, **cfg):
return OpenAICompatProvider("p", {"base_url": "http://up/v1", "_transport": httpx.MockTransport(handler), **cfg})
def client(prov, tmp_path=None, **alias):
store = Store(tmp_path) if tmp_path else None
usage = []
c = ModelClient("a", ModelAlias(provider="p", model="m", max_retries=4, **alias), prov, store=store,
on_usage=lambda *a: usage.append(a))
return c, usage
def test_plain_completion_and_usage(tmp_path):
prov = provider(lambda req: httpx.Response(200, json=OK), pricing={"input_per_mtok": 1e6, "output_per_mtok": 0})
c, usage = client(prov, tmp_path)
res = asyncio.run(c.chat([{"role": "user", "content": "x"}]))
assert res.content == "hi" and res.usage.input_tokens == 5 and res.usage.cost_usd == 5.0
again = asyncio.run(c.chat([{"role": "user", "content": "x"}]))
assert again.cached and usage[-1][-1] is True # request cache hit, accounted as cached
def test_429_with_retry_after_is_retried():
calls = []
def handler(req):
calls.append(1)
if len(calls) < 3:
return httpx.Response(429, headers={"retry-after": "0.05"}, json={"error": "slow down"})
return httpx.Response(200, json=OK)
c, _ = client(provider(handler))
assert asyncio.run(c.chat([{"role": "user", "content": "x"}])).content == "hi"
assert len(calls) == 3 and c.provider.limiter.stats["rejected"] == 2
def test_http200_stream_with_error_event_becomes_429():
calls = []
def handler(req):
calls.append(json.loads(req.content))
if len(calls) == 1:
body = b": heartbeat\n\n: heartbeat\n\ndata: {\"error\": {\"code\": \"capacity_saturated\", \"message\": \"busy\"}}\n\n"
return httpx.Response(200, content=body, headers={"content-type": "text/event-stream"})
chunks = [{"choices": [{"index": 0, "delta": {"role": "assistant", "content": "he"}}]},
{"choices": [{"index": 0, "delta": {"content": "llo"}, "finish_reason": "stop"}]},
{"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2}}]
body = b"".join(b"data: " + json.dumps(c).encode() + b"\n\n" for c in chunks) + b"data: [DONE]\n\n"
return httpx.Response(200, content=body, headers={"content-type": "text/event-stream"})
prov = provider(handler, stream=True)
c, _ = client(prov)
res = asyncio.run(c.chat([{"role": "user", "content": "x"}]))
assert res.content == "hello" and res.usage.output_tokens == 2
assert calls[0]["stream"] is True and prov.limiter.stats["rejected"] == 1
def test_http200_body_error_and_4xx():
def handler(req):
return httpx.Response(200, json={"error": {"code": 503, "message": "overloaded"}})
prov = provider(handler)
with pytest.raises(ProviderError) as e:
asyncio.run(prov.complete({"model": "m", "messages": []}))
assert e.value.status == 503 and e.value.retryable
c, _ = client(provider(lambda r: httpx.Response(400, json={"error": "bad"})))
with pytest.raises(ProviderError) as e:
asyncio.run(c.chat([{"role": "user", "content": "x"}]))
assert e.value.status == 400 and not e.value.retryable
def test_literal_api_key_rejected():
prov = provider(lambda r: httpx.Response(200, json=OK), api_key="sk-literal")
with pytest.raises(ProviderError):
asyncio.run(prov.complete({"model": "m", "messages": []}))
def test_fake_provider_schema_and_failures():
schema = {"type": "object", "properties": {"c": {"type": "string", "enum": ["a", "b"]},
"s": {"type": "integer", "minimum": 0, "maximum": 2}}}
v = sample_from_schema(schema, "seed")
assert v["c"] in ("a", "b") and 0 <= v["s"] <= 2
prov = FakeProvider("f", {"fail": {"first": 2, "status": 429, "retry_after": 0.01}})
c, _ = client(prov)
res = asyncio.run(c.chat([{"role": "user", "content": "x"}], response_format={
"type": "json_schema", "json_schema": {"schema": schema}}))
assert set(json.loads(res.content)) == {"c", "s"} and prov.calls == 3