Created At: 2026-11-18T08:58:23Z Completed At: 2026-11-18T08:58:30Z Command exited with code 1. Command output: ============================= test session starts ============================== platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0 -- /root/telegram-saas/.venv/bin/python3 cachedir: .pytest_cache rootdir: /root/telegram-saas configfile: pyproject.toml plugins: anyio-4.16.0, asyncio-1.5.0 asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function collecting ... collected 1 item tests/integration/test_ai_api.py::test_ai_module_full_lifecycle FAILED [100%] =================================== FAILURES =================================== ________________________ test_ai_module_full_lifecycle _________________________ async_client = db_session = @pytest.mark.asyncio async def test_ai_module_full_lifecycle( async_client: AsyncClient, db_session: AsyncSession, ): # 1. Register User and Create Tenant email = f"ai_user_{uuid.uuid4().hex[:6]}@example.com" reg_resp = await async_client.post( "/api/v1/auth/register", json={"email": email, "password": "Password123!", "full_name": "AI Admin"}, ) assert reg_resp.status_code == 201 token = reg_resp.json()["data"]["access_token"] headers = {"Authorization": f"Bearer {token}"} tenant_resp = await async_client.post( "/api/v1/tenants", headers=headers, json={"name": "AI Automation Corp", "slug": f"ai-{uuid.uuid4().hex[:6]}"}, ) assert tenant_resp.status_code == 201 tenant_id = tenant_resp.json()["data"]["id"] headers["X-Tenant-ID"] = tenant_id # 2. Check Models Catalog (OpenAI & OpenRouter) models_openai_resp = await async_client.get("/api/v1/ai/models?provider=openai") assert models_openai_resp.status_code == 200 models_openai = models_openai_resp.json()["data"] assert any(m["id"] == "gpt-4o-mini" for m in models_openai) models_openrouter_resp = await async_client.get("/api/v1/ai/models?provider=openrouter") assert models_openrouter_resp.status_code == 200 models_openrouter = models_openrouter_resp.json()["data"] assert any("anthropic/claude-3.5-sonnet" in m["id"] for m in models_openrouter) # 3. Entitlement Gate: Free Plan Tenant cannot use AI features (HTTP 403) free_key_resp = await async_client.post( "/api/v1/ai/keys", headers=headers, json={ "provider": "openai", "key_name": "Primary OpenAI", "api_key": "sk-proj-testkey123456789012345", }, ) assert free_key_resp.status_code == 403 assert "ai_enabled" in free_key_resp.json()["message"] free_agent_resp = await async_client.post( "/api/v1/ai/agents", headers=headers, json={ "name": "Free Bot", "provider": "openai", "model": "gpt-4o-mini", "system_prompt": "You are a bot.", }, ) assert free_agent_resp.status_code == 403 # 4. Upgrade Tenant Subscription to 'pro' tenant_uuid = uuid.UUID(tenant_id) await db_session.execute( update(Tenant).where(Tenant.id == tenant_uuid).values(plan_id="pro") ) sub_res = await db_session.execute( select(Subscription).where(Subscription.tenant_id == tenant_uuid) ) sub = sub_res.scalar_one_or_none() if sub: sub.plan_id = "pro" else: # Create subscription if not present sub = Subscription( id=uuid.uuid4(), tenant_id=tenant_uuid, plan_id="pro", status="active", gateway_provider="manual", ) db_session.add(sub) await db_session.commit() # 5. Add Custom Encrypted Tenant API Key add_key_resp = await async_client.post( "/api/v1/ai/keys", headers=headers, json={ "provider": "openai", "key_name": "Pro OpenAI Key", "api_key": "sk_test_pro_openai_key_123456789012345", }, ) assert add_key_resp.status_code == 201 key_data = add_key_resp.json()["data"] key_id = key_data["id"] assert key_data["provider"] == "openai" assert key_data["key_name"] == "Pro OpenAI Key" assert "sk_t" in key_data["masked_key"] assert "2345" in key_data["masked_key"] # List keys list_keys_resp = await async_client.get("/api/v1/ai/keys", headers=headers) assert list_keys_resp.status_code == 200 assert len(list_keys_resp.json()["data"]) == 1 # 6. Create AI Assistant Agent create_agent_resp = await async_client.post( "/api/v1/ai/agents", headers=headers, json={ "name": "Customer Support Agent", "provider": "openai", "model": "gpt-4o-mini", "system_prompt": "You are a helpful customer support agent for our SaaS platform.", "temperature": 0.6, "max_tokens": 800, }, ) assert create_agent_resp.status_code == 201 agent_data = create_agent_resp.json()["data"] agent_id = agent_data["id"] assert agent_data["name"] == "Customer Support Agent" assert agent_data["model"] == "gpt-4o-mini" assert agent_data["is_active"] is True # Get agent details get_agent_resp = await async_client.get(f"/api/v1/ai/agents/{agent_id}", headers=headers) assert get_agent_resp.status_code == 200 assert get_agent_resp.json()["data"]["id"] == agent_id # 7. Execute Multi-Turn Chat session_id = f"test_session_{uuid.uuid4().hex[:8]}" chat_resp1 = await async_client.post( f"/api/v1/ai/agents/{agent_id}/chat", headers=headers, json={ "message": "Hello! How do I configure my bot webhook?", "session_id": session_id, }, ) assert chat_resp1.status_code == 200 chat_data1 = chat_resp1.json()["data"] assert chat_data1["role"] == "assistant" assert len(chat_data1["content"]) > 0 assert chat_data1["prompt_tokens"] > 0 assert chat_data1["completion_tokens"] > 0 assert chat_data1["total_tokens"] > 0 assert "conversation_id" in chat_data1 # Follow-up message in same conversation session chat_resp2 = await async_client.post( f"/api/v1/ai/agents/{agent_id}/chat", headers=headers, json={ "message": "Got it, and what are the rate limits for broadcast?", "session_id": session_id, }, ) assert chat_resp2.status_code == 200 chat_data2 = chat_resp2.json()["data"] assert chat_data2["conversation_id"] == chat_data1["conversation_id"] # 8. Check AI Usage Summary & Cost Tracking usage_resp = await async_client.get("/api/v1/ai/usage", headers=headers) assert usage_resp.status_code == 200 usage = usage_resp.json()["data"] assert usage["total_requests"] >= 2 assert usage["total_tokens"] > 0 > assert usage["total_cost_usd"] >= 0 ^^^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'total_cost_usd' tests/integration/test_ai_api.py:179: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 08:58:28 [info ] dispatching_domain_event event_id=ab1055cc-b6a9-4232-ab36-cd27c2c47a95 event_type=UserRegisteredEvent handlers_count=0 2026-11-18 08:58:28 [info ] dispatching_domain_event event_id=1f32cbb9-bc77-4685-8bf3-02f2e8740a24 event_type=TenantCreatedEvent handlers_count=0 2026-11-18 08:58:28 [warning ] app_exception_handled error_code=FORBIDDEN message="Feature 'ai_enabled' is not available on the 'Free Tier' plan. Please upgrade to unlock this feature." method=POST path=/api/v1/ai/keys 2026-11-18 08:58:28 [warning ] app_exception_handled error_code=FORBIDDEN message="Feature 'ai_enabled' is not available on the 'Free Tier' plan. Please upgrade to unlock this feature." method=POST path=/api/v1/ai/agents =========================== short test summary info ============================ FAILED tests/integration/test_ai_api.py::test_ai_module_full_lifecycle - KeyE... ============================== 1 failed in 0.98s ===============================