test_call_orchestration_api.py 19.1 KB
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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
"""LLM 调用编排 API 测试"""
import pytest
import pytest_asyncio
from unittest.mock import patch, AsyncMock, MagicMock
from httpx import AsyncClient

from app.services.adapter import LLMResponse


def _mock_adapter_invoke(*args, **kwargs):
    """Mock 适配器调用,返回成功响应"""
    return LLMResponse(
        success=True,
        content="模拟回复:你好!",
        prompt_tokens=50,
        completion_tokens=20,
        total_tokens=70,
        raw_response={
            "choices": [{"message": {"role": "assistant", "content": "模拟回复:你好!"}}],
            "usage": {"prompt_tokens": 50, "completion_tokens": 20, "total_tokens": 70},
        },
    )


MOCK_PATCH_PATH = "app.services.adapter_service.invoke_model"


class TestCallOrchestrationAPI:
    """LLM 调用编排 API 测试"""

    @pytest.fixture(autouse=True)
    def _mock_celery_and_adapter(self):
        """自动 mock 适配器和 Celery,避免真实 HTTP/Redis 连接"""
        # Mock adapter
        adapter_mock = AsyncMock(return_value=_mock_adapter_invoke())
        adapter_patcher = patch(MOCK_PATCH_PATH, adapter_mock)
        adapter_patcher.start()

        # Mock Celery - 每次调用返回不同的 celery_task_id
        celery_counter = [0]
        celery_has_patcher = patch("app.services.orchestration_service.HAS_CELERY", True)
        celery_has_patcher.start()
        celery_task_patcher = patch("app.services.orchestration_service.process_async_llm_call")
        celery_task_mock = celery_task_patcher.start()
        def delay_side_effect(**kwargs):
            celery_counter[0] += 1
            return MagicMock(id=f"mock-celery-id-{celery_counter[0]}")
        celery_task_mock.delay.side_effect = delay_side_effect

        yield

        adapter_patcher.stop()
        celery_has_patcher.stop()
        celery_task_patcher.stop()

    PROVIDER_DATA = {
        "provider_name": "orch-test-provider",
        "display_name": "编排测试供应商",
        "adapter_type": "openai_compat",
        "supported_models": ["gpt-test"],
    }

    ACCOUNT_DATA = {
        "account_name": "编排测试账号",
        "code": "ACCOUNT-ORCH-001",
        "api_key": "sk-orch-test-key",
        "model_name": "gpt-test",
        "priority": 1,
        "status": "active",
    }

    PROMPT_DATA = {
        "template_type": "general",
        "title": "编排提示词",
        "code": "TEMPLATE-ORCH-001",
        "system_prompt": "你是一个助手。用户说:{{input}}。请用{{lang}}回复。",
        "user_prompt": "以下内容请用{{lang}}回复:{{input}}",
        "variables": [
            {"name": "input", "type": "string"},
            {"name": "lang", "type": "string"},
        ],
    }

    SYNC_REQUEST = {
        "model_name": "gpt-test",
        "biz_type": "general",
        "prompt_template_type": "general",
        "variables": {"input": "你好", "lang": "中文"},
        "request_body": {"messages": [{"role": "user", "content": "Hello"}]},
    }

    ASYNC_REQUEST = {
        "model_name": "gpt-test",
        "biz_type": "general",
        "prompt_template_type": "general",
        "variables": {"input": "你好", "lang": "中文"},
        "request_body": {"messages": [{"role": "user", "content": "Hello"}]},
        "callback_url": "http://example.com/callback",
    }

    @pytest.mark.asyncio
    async def _setup(self, client: AsyncClient) -> tuple:
        """创建测试数据:provider + account + prompt"""
        # 创建供应商
        resp = await client.post("/api/v1/providers", json=self.PROVIDER_DATA)
        provider = resp.json()
        provider_id = provider["id"]

        # 创建账号
        acct_data = self.ACCOUNT_DATA.copy()
        acct_data["provider_id"] = provider_id
        resp = await client.post("/api/v1/accounts", json=acct_data)
        account_id = resp.json()["id"]

        # 创建提示词模板
        resp = await client.post("/api/v1/prompts", json=self.PROMPT_DATA)

        return provider_id, account_id

    @pytest.mark.asyncio
    async def test_sync_call_success(self, client: AsyncClient):
        """测试同步调用成功"""
        await self._setup(client)

        resp = await client.post("/api/v1/calls/orchestrate/sync", json=self.SYNC_REQUEST)
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "success"
        assert result["model_name"] == "gpt-test"
        assert "call_record_id" in result
        assert "response_body" in result or "execution_log" in result

    @pytest.mark.asyncio
    async def test_sync_call_prompt_rendered(self, client: AsyncClient):
        """测试同步调用中 prompt 被正确渲染"""
        await self._setup(client)

        resp = await client.post("/api/v1/calls/orchestrate/sync", json=self.SYNC_REQUEST)
        assert resp.status_code == 200
        result = resp.json()
        # 确保 system_prompt 中的变量被替换
        log = result.get("execution_log", "")
        # execution_log 应包含 prompt 模板加载记录
        assert "加载提示词模板" in log

    @pytest.mark.asyncio
    async def test_sync_call_model_not_found(self, client: AsyncClient):
        """测试模型无可用账号应返回 404"""
        await self._setup(client)

        data = self.SYNC_REQUEST.copy()
        data["model_name"] = "nonexistent-model"
        resp = await client.post("/api/v1/calls/orchestrate/sync", json=data)
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_sync_call_prompt_not_found(self, client: AsyncClient):
        """测试提示词模板类型不存在应返回 404"""
        await self._setup(client)

        data = self.SYNC_REQUEST.copy()
        data["prompt_template_type"] = "nonexistent_type"
        resp = await client.post("/api/v1/calls/orchestrate/sync", json=data)
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_sync_call_missing_model(self, client: AsyncClient):
        """测试缺少 model_name 应返回 422"""
        data = self.SYNC_REQUEST.copy()
        del data["model_name"]
        resp = await client.post("/api/v1/calls/orchestrate/sync", json=data)
        assert resp.status_code == 422

    @pytest.mark.asyncio
    async def test_async_call_success(self, client: AsyncClient):
        """测试异步调用成功"""
        await self._setup(client)

        resp = await client.post("/api/v1/calls/orchestrate/async", json=self.ASYNC_REQUEST)
        assert resp.status_code == 202
        result = resp.json()
        assert result["status"] == "accepted"
        assert "task_id" in result
        assert result["task_status"] in ("processing", "pending")

    @pytest.mark.asyncio
    async def test_async_call_query_result(self, client: AsyncClient):
        """测试查询异步调用结果"""
        await self._setup(client)

        # 创建异步任务
        resp = await client.post("/api/v1/calls/orchestrate/async", json=self.ASYNC_REQUEST)
        assert resp.status_code == 202
        task_id = resp.json()["task_id"]

        # 查询结果
        resp = await client.get(f"/api/v1/calls/orchestrate/async", params={"task_id": task_id})
        assert resp.status_code == 200
        result = resp.json()
        assert result["task_id"] == task_id
        assert result["status"] in ("pending", "processing", "success", "failed")

    @pytest.mark.asyncio
    async def test_async_call_query_not_found(self, client: AsyncClient):
        """测试查询不存在的异步任务应返回 404"""
        resp = await client.get("/api/v1/calls/orchestrate/async", params={"task_id": "nonexistent-task-id"})
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_async_call_batch_query(self, client: AsyncClient):
        """测试批量查询异步结果"""
        await self._setup(client)

        # 创建两个异步任务
        ids = []
        for i in range(2):
            data = self.ASYNC_REQUEST.copy()
            data["request_body"] = {"messages": [{"role": "user", "content": f"Batch {i}"}]}
            resp = await client.post("/api/v1/calls/orchestrate/async", json=data)
            assert resp.status_code == 202
            ids.append(resp.json()["task_id"])

        # 批量查询
        resp = await client.post(
            "/api/v1/calls/orchestrate/async/batch",
            json={"task_ids": ids},
        )
        assert resp.status_code == 200
        result = resp.json()
        assert len(result["results"]) == 2

    @pytest.mark.asyncio
    async def test_sync_with_quality_inspection(self, client: AsyncClient):
        """测试带质检类型的同步调用"""
        provider_id, _ = await self._setup(client)

        # 创建质检类型的 prompt 模板
        qi_prompt = {
            "template_type": "quality_inspection",
            "title": "质检提示词",
            "code": "TEMPLATE-ORCH-QI",
            "system_prompt": "你是质检助手。内容:{{content}}",
            "variables": [{"name": "content", "type": "string"}],
        }
        await client.post("/api/v1/prompts", json=qi_prompt)

        data = self.SYNC_REQUEST.copy()
        data["prompt_template_type"] = "quality_inspection"
        data["variables"] = {"content": "测试质检内容"}

        resp = await client.post("/api/v1/calls/orchestrate/sync", json=data)
        assert resp.status_code == 200

    @pytest.mark.asyncio
    async def test_sync_call_no_biz_type(self, client: AsyncClient):
        """测试不传 biz_type 也正常工作"""
        await self._setup(client)

        data = self.SYNC_REQUEST.copy()
        del data["biz_type"]

        resp = await client.post("/api/v1/calls/orchestrate/sync", json=data)
        assert resp.status_code == 200

    @pytest.mark.asyncio
    async def test_account_priority_matching(self, client: AsyncClient):
        """测试账号优先级匹配"""
        provider_id, first_acct_id = await self._setup(client)

        # 创建第二个优先级更高的账号
        acct2 = self.ACCOUNT_DATA.copy()
        acct2["code"] = "ACCOUNT-ORCH-002"
        acct2["provider_id"] = provider_id
        acct2["account_name"] = "高优账号"
        acct2["priority"] = 0  # 更高优先级
        await client.post("/api/v1/accounts", json=acct2)

        resp = await client.post("/api/v1/calls/orchestrate/sync", json=self.SYNC_REQUEST)
        assert resp.status_code == 200
        result = resp.json()
        assert "matched_account" in result.get("execution_log", "") or result.get("status") == "success"


class TestByTemplateAPI:
    """业务调用(by-template) API 测试"""

    @pytest.fixture(autouse=True)
    def _mock_adapter_only(self):
        """Mock 适配器(不 mock Celery,因为 by-template async 模式内部走 similar path)"""
        adapter_mock = AsyncMock(return_value=_mock_adapter_invoke())
        adapter_patcher = patch(MOCK_PATCH_PATH, adapter_mock)
        adapter_patcher.start()

        celery_has_patcher = patch("app.services.orchestration_service.HAS_CELERY", True)
        celery_has_patcher.start()
        celery_task_patcher = patch("app.services.orchestration_service.process_async_llm_call")
        celery_task_mock = celery_task_patcher.start()
        celery_task_mock.delay.return_value = MagicMock(id="mock-celery-bt")
        yield
        adapter_patcher.stop()
        celery_has_patcher.stop()
        celery_task_patcher.stop()

    @pytest_asyncio.fixture
    async def setup_data(self, client: AsyncClient) -> dict:
        """创建测试数据:provider + account + prompt template"""
        # 创建供应商
        resp = await client.post("/api/v1/providers", json={
            "provider_name": "bt-test-provider",
            "display_name": "业务调用测试供应商",
            "adapter_type": "openai_compat",
            "supported_models": ["gpt-bt"],
        })
        provider = resp.json()
        provider_id = provider["id"]

        # 创建账号
        resp = await client.post("/api/v1/accounts", json={
            "provider_id": provider_id,
            "account_name": "业务调用账号",
            "code": "ACCOUNT-BT-001",
            "api_key": "sk-bt-test",
            "model_name": "gpt-bt",
            "priority": 1,
            "status": "active",
        })
        account_id = resp.json()["id"]

        # 创建提示词模板
        resp = await client.post("/api/v1/prompts", json={
            "template_type": "general",
            "title": "业务调用模板",
            "code": "TEMPLATE-BT-001",
            "system_prompt": "你是智能助手,请回答用户问题。",
            "status": "published",
        })
        template = resp.json()
        template_id = template["id"]

        return {
            "provider_id": provider_id,
            "account_id": account_id,
            "template_id": template_id,
        }

    @pytest.mark.asyncio
    async def test_by_template_sync_success(self, client: AsyncClient, setup_data: dict):
        """测试 by-template 同步调用成功"""
        data = {
            "template_id": setup_data["template_id"],
            "account_id": setup_data["account_id"],
            "variables": {"content": "你好,请介绍一下你自己"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "success"
        assert result["model_name"] == "gpt-bt"
        assert "call_record_id" in result
        assert "response_content" in result

    @pytest.mark.asyncio
    async def test_by_template_sync_biz_type(self, client: AsyncClient, setup_data: dict):
        """测试 by-template 同步调用 — biz_type 自动设为模板业务编码"""
        data = {
            "template_id": "TEMPLATE-BT-001",
            "account_id": "ACCOUNT-BT-001",
            "variables": {"content": "测试 biz_type"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 200
        result = resp.json()
        call_record_id = result["call_record_id"]

        # 查询调用记录详情,验证 biz_type
        detail = await client.get(f"/api/v1/calls/{call_record_id}")
        assert detail.status_code == 200
        assert detail.json()["biz_type"] == "TEMPLATE-BT-001"

    @pytest.mark.asyncio
    async def test_by_template_async_success(self, client: AsyncClient, setup_data: dict):
        """测试 by-template 异步调用成功"""
        data = {
            "template_id": setup_data["template_id"],
            "account_id": setup_data["account_id"],
            "variables": {"content": "异步测试消息"},
            "mode": "async",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 202
        result = resp.json()
        assert result["status"] == "accepted"
        assert "task_id" in result
        assert "call_record_id" in result

    @pytest.mark.asyncio
    async def test_by_template_invalid_mode(self, client: AsyncClient, setup_data: dict):
        """测试传入无效 mode 应返回 422"""
        data = {
            "template_id": setup_data["template_id"],
            "account_id": setup_data["account_id"],
            "variables": {"content": "测试消息"},
            "mode": "invalid_mode",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 422

    @pytest.mark.asyncio
    async def test_by_template_missing_fields(self, client: AsyncClient):
        """测试缺少必填字段应返回 422"""
        resp = await client.post("/api/v1/calls/by-template", json={})
        assert resp.status_code == 422

    @pytest.mark.asyncio
    async def test_by_template_template_not_found(self, client: AsyncClient, setup_data: dict):
        """测试模板不存在应返回 404"""
        data = {
            "template_id": "nonexistent-template-id",
            "account_id": setup_data["account_id"],
            "variables": {"content": "测试消息"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_by_template_account_not_found(self, client: AsyncClient, setup_data: dict):
        """测试账号不存在应返回 404"""
        data = {
            "template_id": setup_data["template_id"],
            "account_id": "nonexistent-account-id",
            "variables": {"content": "测试消息"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_by_template_sync_with_code(self, client: AsyncClient, setup_data: dict):
        """测试 by-template 同步调用 — 使用业务编码查找模板和账号"""
        data = {
            "template_id": "TEMPLATE-BT-001",
            "account_id": "ACCOUNT-BT-001",
            "variables": {"content": "你好,请介绍一下你自己"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "success"
        assert result["model_name"] == "gpt-bt"
        assert "call_record_id" in result
        assert "response_content" in result

    @pytest.mark.asyncio
    async def test_by_template_sync_with_code_and_uuid_mixed(self, client: AsyncClient, setup_data: dict):
        """测试 by-template 同步调用 — 混合使用:template 用业务编码,account 用 UUID"""
        data = {
            "template_id": "TEMPLATE-BT-001",
            "account_id": setup_data["account_id"],
            "variables": {"content": "混合模式测试"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "success"

    @pytest.mark.asyncio
    async def test_by_template_async_with_code(self, client: AsyncClient, setup_data: dict):
        """测试 by-template 异步调用 — 使用业务编码查找模板和账号"""
        data = {
            "template_id": "TEMPLATE-BT-001",
            "account_id": "ACCOUNT-BT-001",
            "variables": {"content": "异步测试消息"},
            "mode": "async",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 202
        result = resp.json()
        assert result["status"] == "accepted"
        assert "task_id" in result
        assert "call_record_id" in result

    @pytest.mark.asyncio
    async def test_by_template_code_not_found(self, client: AsyncClient, setup_data: dict):
        """测试业务编码不存在应返回 404"""
        data = {
            "template_id": "TEMPLATE-NONEXIST",
            "account_id": "ACCOUNT-BT-001",
            "variables": {"content": "测试消息"},
            "mode": "sync",
        }
        resp = await client.post("/api/v1/calls/by-template", json=data)
        assert resp.status_code == 404