Проверка среды отвергает пустой DB_PATH и DATA_DIR-файл; в проверке шлюза конец потока определяется телом data, а не подстрокой в тексте. Co-Authored-By: Claude Code <noreply@anthropic.com>
289 lines
14 KiB
Python
289 lines
14 KiB
Python
"""R-06: инструменты модели в шлюзе — запрос, вызовы и ответы в обе стороны.
|
|
|
|
Форма клиента — OpenAI-совместимая (tools/tool_calls/tool-сообщения), провайдер —
|
|
Anthropic Messages. Проверяем перевод запроса, разбор потока провайдера и поток клиенту.
|
|
"""
|
|
import importlib
|
|
import os
|
|
import sys
|
|
|
|
import pytest
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
if ROOT not in sys.path:
|
|
sys.path.insert(0, ROOT)
|
|
|
|
|
|
@pytest.fixture()
|
|
def env(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
|
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
|
monkeypatch.setenv("AI_BACKEND", "claude")
|
|
monkeypatch.setenv("DEVICE_MIN_VERSION", "1.0.0")
|
|
monkeypatch.setenv("REVIEWS_ENABLED", "on")
|
|
monkeypatch.chdir(ROOT)
|
|
import auth, db, device_auth, gateway, main
|
|
for m in (db, auth, device_auth, gateway, main):
|
|
importlib.reload(m)
|
|
db.init_db()
|
|
db.create_user("u@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("u@x")
|
|
db.save_message("u@x", "tab-own", "user", "привет")
|
|
from fastapi.testclient import TestClient
|
|
client = TestClient(main.app)
|
|
site = {"Authorization": "Bearer " + auth._make_token("u@x", "user")}
|
|
resp = client.post("/api/device/codes", json={"tab_id": "tab-own"}, headers=site)
|
|
assert resp.status_code == 200, resp.text
|
|
code = resp.json()
|
|
resp = client.post("/api/device/token", json={
|
|
"code": code["code"], "device_name": "ПК", "app_version": "1.4.0"})
|
|
assert resp.status_code == 200, resp.text
|
|
dev = resp.json()
|
|
device = {"Authorization": "Bearer " + dev["access"], "X-App-Version": "1.4.0"}
|
|
return {"client": client, "device": device, "gateway": gateway, "db": db}
|
|
|
|
|
|
def _provider_body():
|
|
return {
|
|
"model": "любой",
|
|
"tools": [
|
|
{"type": "function", "function": {
|
|
"name": "find_base_price", "description": "цена по ФСНБ",
|
|
"parameters": {"type": "object", "properties": {"code": {"type": "string"}},
|
|
"required": ["code"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "read_document", "description": "кусок документа",
|
|
"parameters": {"type": "object", "properties": {}}}},
|
|
],
|
|
"messages": [
|
|
{"role": "system", "content": "Ты сметчик."},
|
|
{"role": "user", "content": "Проверь замечание 3"},
|
|
{"role": "assistant", "content": "Смотрю цену.",
|
|
"tool_calls": [{"id": "call_1", "type": "function",
|
|
"function": {"name": "find_base_price",
|
|
"arguments": "{\"code\": \"01.7.10.07\"}"}}]},
|
|
{"role": "tool", "tool_call_id": "call_1", "content": "{\"price\": 123.45}"},
|
|
],
|
|
"max_tokens": 900,
|
|
}
|
|
|
|
|
|
def test_request_is_translated_to_provider_shape(env):
|
|
payload = env["gateway"]._to_provider(_provider_body(), "model-x", 4096)
|
|
assert payload["model"] == "model-x" and payload["stream"] is True
|
|
assert payload["max_tokens"] == 900
|
|
assert payload["system"] == "Ты сметчик."
|
|
tools = payload["tools"]
|
|
assert [t["name"] for t in tools] == ["find_base_price", "read_document"]
|
|
assert tools[0]["input_schema"]["properties"]["code"]["type"] == "string"
|
|
msgs = payload["messages"]
|
|
assert [m["role"] for m in msgs] == ["user", "assistant", "user"]
|
|
assistant = msgs[1]["content"]
|
|
assert any(b.get("type") == "tool_use" and b["name"] == "find_base_price"
|
|
and b["input"] == {"code": "01.7.10.07"} for b in assistant)
|
|
result = msgs[2]["content"]
|
|
assert any(b.get("type") == "tool_result" and b["tool_use_id"] == "call_1"
|
|
and "123.45" in str(b["content"]) for b in result)
|
|
|
|
|
|
def test_provider_tool_events_become_client_events(env):
|
|
state = env["gateway"]._stream_state()
|
|
evs = env["gateway"]._event_to_events(
|
|
{"type": "content_block_start", "index": 1,
|
|
"content_block": {"type": "tool_use", "id": "toolu_1", "name": "read_document",
|
|
"input": {}}}, state)
|
|
assert evs and evs[0]["tool_call"]["name"] == "read_document"
|
|
assert evs[0]["tool_call"]["id"] == "toolu_1"
|
|
evs = env["gateway"]._event_to_events(
|
|
{"type": "content_block_delta", "index": 1,
|
|
"delta": {"type": "input_json_delta", "partial_json": "{\"path\":"}}, state)
|
|
assert evs[0]["tool_call"]["arguments"] == "{\"path\":"
|
|
evs = env["gateway"]._event_to_events(
|
|
{"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {}}, state)
|
|
assert {"finish": "tool_calls"} in evs
|
|
state2 = env["gateway"]._stream_state()
|
|
evs = env["gateway"]._event_to_events(
|
|
{"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {}}, state2)
|
|
assert {"finish": "stop"} in evs
|
|
|
|
|
|
def test_client_stream_carries_tool_calls(env, monkeypatch):
|
|
async def fake_stream(profile, body):
|
|
yield {"tool_call": {"index": 0, "id": "toolu_9", "name": "find_base_price",
|
|
"arguments": ""}}
|
|
yield {"tool_call": {"index": 0, "arguments": "{\"code\":\"1-14-1\"}"}}
|
|
yield {"delta": "Готово."}
|
|
yield {"finish": "tool_calls"}
|
|
yield {"usage": {"input_tokens": 5, "output_tokens": 7, "price_rub": 0.1}}
|
|
|
|
monkeypatch.setattr(env["gateway"], "_provider_stream", fake_stream)
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [{"role": "user", "content": "x"}],
|
|
"tools": [{"type": "function", "function": {
|
|
"name": "find_base_price", "description": "d",
|
|
"parameters": {"type": "object"}}}]},
|
|
headers=dict(env["device"], **{"X-Tab-Id": "tab-own"}))
|
|
assert r.status_code == 200, r.text
|
|
body = r.text
|
|
assert "[DONE]" in body
|
|
import json as _json
|
|
chunks = [_json.loads(l[5:]) for l in body.splitlines()
|
|
if l.startswith("data:") and l[5:].strip() != "[DONE]"]
|
|
calls = [c["choices"][0]["delta"]["tool_calls"] for c in chunks
|
|
if (c["choices"][0].get("delta") or {}).get("tool_calls")]
|
|
first, fragments = calls[0][0], [call[0] for call in calls[1:]]
|
|
assert first["id"] == "toolu_9" and first["function"]["name"] == "find_base_price"
|
|
assert fragments and all("id" not in f and "name" not in f["function"] for f in fragments)
|
|
args = first["function"]["arguments"] + "".join(f["function"]["arguments"] for f in fragments)
|
|
assert args == '{"code":"1-14-1"}'
|
|
finishes = [c["choices"][0]["finish_reason"] for c in chunks
|
|
if c["choices"][0].get("finish_reason")]
|
|
assert finishes == ["tool_calls"]
|
|
con = env["db"]._conn()
|
|
row = con.execute("SELECT input_tokens, cache_tokens, output_tokens, price_rub"
|
|
" FROM llm_usage WHERE tab_id='tab-own'").fetchone()
|
|
con.close()
|
|
assert row[0] == 5 and row[1] is None and row[2] == 7 and row[3] == 0.1
|
|
|
|
|
|
def test_tool_index_starts_at_zero_after_text(env):
|
|
"""Индекс вызова в форме OpenAI считается по вызовам, а не по блокам провайдера."""
|
|
state = env["gateway"]._stream_state()
|
|
env["gateway"]._event_to_events({"type": "content_block_delta", "index": 0,
|
|
"delta": {"type": "text_delta", "text": "Смотрю."}}, state)
|
|
env["gateway"]._event_to_events({"type": "content_block_start", "index": 1,
|
|
"content_block": {"type": "tool_use", "id": "t1",
|
|
"name": "read_document", "input": {}}}, state)
|
|
second = env["gateway"]._event_to_events(
|
|
{"type": "content_block_start", "index": 3,
|
|
"content_block": {"type": "tool_use", "id": "t2", "name": "find_base_price",
|
|
"input": {}}}, state)
|
|
assert second[0]["tool_call"]["index"] == 1
|
|
frag = env["gateway"]._event_to_events(
|
|
{"type": "content_block_delta", "index": 3,
|
|
"delta": {"type": "input_json_delta", "partial_json": "{}"}}, state)
|
|
assert frag[0]["tool_call"]["index"] == 1
|
|
|
|
|
|
def test_max_tokens_finish_is_length(env):
|
|
state = env["gateway"]._stream_state()
|
|
evs = env["gateway"]._event_to_events(
|
|
{"type": "message_delta", "delta": {"stop_reason": "max_tokens"}, "usage": {}}, state)
|
|
assert {"finish": "length"} in evs
|
|
|
|
|
|
def test_tool_choice_is_translated(env):
|
|
body = _provider_body()
|
|
body["tool_choice"] = "required"
|
|
assert env["gateway"]._to_provider(body, "m", 100)["tool_choice"] == {"type": "any"}
|
|
body["tool_choice"] = "none"
|
|
assert env["gateway"]._to_provider(body, "m", 100)["tool_choice"] == {"type": "none"}
|
|
body["tool_choice"] = {"type": "function", "function": {"name": "read_document"}}
|
|
assert env["gateway"]._to_provider(body, "m", 100)["tool_choice"] == {
|
|
"type": "tool", "name": "read_document"}
|
|
|
|
|
|
def test_developer_role_becomes_system(env):
|
|
body = {"messages": [{"role": "developer", "content": "правила"},
|
|
{"role": "user", "content": "вопрос"}]}
|
|
payload = env["gateway"]._to_provider(body, "m", 100)
|
|
assert payload["system"] == "правила"
|
|
assert [m["role"] for m in payload["messages"]] == ["user"]
|
|
|
|
|
|
def test_unknown_role_refused(env):
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [{"role": "robot", "content": "x"}]},
|
|
headers=dict(env["device"], **{"X-Tab-Id": "tab-own"}))
|
|
assert r.status_code == 400
|
|
assert r.json()["code"] == "bad_request"
|
|
|
|
|
|
def test_sse_lines_are_parsed(env):
|
|
"""Настоящие строки провайдера: текст, затем вызов — общий путь разбора."""
|
|
state = env["gateway"]._stream_state()
|
|
lines = [
|
|
'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Да"}}',
|
|
'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use",'
|
|
'"id":"toolu_1","name":"read_document","input":{}}}',
|
|
'data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta",'
|
|
'"partial_json":"{\\"path\\":\\"a.xlsx\\"}"}}',
|
|
'data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":4}}',
|
|
': keep-alive',
|
|
]
|
|
out = []
|
|
for line in lines:
|
|
out.extend(env["gateway"]._line_to_events(line, state))
|
|
assert {"delta": "Да"} in out
|
|
call = [e["tool_call"] for e in out if "tool_call" in e]
|
|
assert call[0]["index"] == 0 and call[0]["name"] == "read_document"
|
|
assert call[1]["arguments"] == '{"path":"a.xlsx"}'
|
|
assert {"finish": "tool_calls"} in out
|
|
assert state["usage"]["output_tokens"] == 4
|
|
|
|
|
|
def test_cache_tokens_are_recorded(env, monkeypatch):
|
|
async def fake_stream(profile, body):
|
|
yield {"delta": "ок"}
|
|
yield {"usage": {"input_tokens": 10, "cache_read_input_tokens": 3,
|
|
"cache_creation_input_tokens": 2, "output_tokens": 5,
|
|
"price_rub": 0.2}}
|
|
|
|
monkeypatch.setattr(env["gateway"], "_provider_stream", fake_stream)
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [{"role": "user", "content": "x"}]},
|
|
headers=dict(env["device"], **{"X-Tab-Id": "tab-own"}))
|
|
assert r.status_code == 200, r.text
|
|
con = env["db"]._conn()
|
|
row = con.execute("SELECT input_tokens, cache_tokens, output_tokens FROM llm_usage"
|
|
" ORDER BY id DESC LIMIT 1").fetchone()
|
|
con.close()
|
|
assert row[0] == 12 # вход + промах кэша
|
|
assert row[1] == 3 # попадание кэша
|
|
assert row[2] == 5
|
|
|
|
|
|
def test_garbage_tools_do_not_break_translation(env):
|
|
body = _provider_body()
|
|
body["tools"] = [None, "строка", 42, body["tools"][0]]
|
|
payload = env["gateway"]._to_provider(body, "m", 100)
|
|
assert [t["name"] for t in payload.get("tools", [])] == ["find_base_price"]
|
|
|
|
|
|
def test_zero_max_tokens_refused(env):
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "max_tokens": 0,
|
|
"messages": [{"role": "user", "content": "x"}]},
|
|
headers=dict(env["device"], **{"X-Tab-Id": "tab-own"}))
|
|
assert r.status_code == 400
|
|
assert r.json()["code"] == "bad_request"
|
|
|
|
|
|
def test_tool_message_without_call_id_refused(env):
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [
|
|
{"role": "user", "content": "x"},
|
|
{"role": "tool", "content": "результат"}]},
|
|
headers=dict(env["device"], **{"X-Tab-Id": "tab-own"}))
|
|
assert r.status_code == 400
|
|
assert r.json()["code"] == "bad_request"
|
|
|
|
|
|
def test_assistant_tool_call_without_id_refused(env):
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [
|
|
{"role": "user", "content": "x"},
|
|
{"role": "assistant", "content": "",
|
|
"tool_calls": [{"type": "function",
|
|
"function": {"name": "f", "arguments": "{}"}}]}]},
|
|
headers=dict(env["device"], **{"X-Tab-Id": "tab-own"}))
|
|
assert r.status_code == 400
|
|
|
|
|
|
def test_system_content_blocks_joined(env):
|
|
payload = env["gateway"]._to_provider({"messages": [
|
|
{"role": "system", "content": [{"type": "text", "text": "раз"},
|
|
{"type": "text", "text": "два"}]},
|
|
{"role": "user", "content": "вопрос"}]}, "m", 100)
|
|
assert payload["system"] == "раз\n\nдва"
|