|
| 1 | +"""Unit tests for the Langfuse-backed PromptBackend (text prompts).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any, cast |
| 6 | + |
| 7 | +import httpx |
| 8 | +import pytest |
| 9 | + |
| 10 | +pytest.importorskip("langfuse") |
| 11 | + |
| 12 | +from langfuse.api import NotFoundError, ServiceUnavailableError # noqa: E402 |
| 13 | +from langfuse.model import ( # noqa: E402 |
| 14 | + ChatPromptClient, |
| 15 | + Prompt_Chat, # pyright: ignore[reportPrivateImportUsage] |
| 16 | + Prompt_Text, # pyright: ignore[reportPrivateImportUsage] |
| 17 | + TextPromptClient, |
| 18 | +) |
| 19 | + |
| 20 | +from openarmature.prompts import PromptManager # noqa: E402 |
| 21 | +from openarmature.prompts.backends.langfuse import LangfusePromptBackend # noqa: E402 |
| 22 | +from openarmature.prompts.errors import ( # noqa: E402 |
| 23 | + PromptNotFound, |
| 24 | + PromptStoreUnavailable, |
| 25 | +) |
| 26 | + |
| 27 | +pytestmark = pytest.mark.asyncio |
| 28 | + |
| 29 | + |
| 30 | +def _text_client( |
| 31 | + *, |
| 32 | + name: str = "greeting", |
| 33 | + version: int = 3, |
| 34 | + prompt: str = "Hello {{ user }}", |
| 35 | + config: dict[str, Any] | None = None, |
| 36 | + labels: list[str] | None = None, |
| 37 | + tags: list[str] | None = None, |
| 38 | +) -> TextPromptClient: |
| 39 | + return TextPromptClient( |
| 40 | + Prompt_Text( |
| 41 | + type="text", |
| 42 | + name=name, |
| 43 | + version=version, |
| 44 | + prompt=prompt, |
| 45 | + config=config or {}, |
| 46 | + labels=["production"] if labels is None else labels, |
| 47 | + tags=tags or [], |
| 48 | + ) |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def _chat_client(*, name: str = "chatty", version: int = 1) -> ChatPromptClient: |
| 53 | + return ChatPromptClient( |
| 54 | + Prompt_Chat( |
| 55 | + type="chat", |
| 56 | + name=name, |
| 57 | + version=version, |
| 58 | + prompt=cast(Any, [{"role": "system", "content": "hi {{ user }}"}]), |
| 59 | + config={}, |
| 60 | + labels=["production"], |
| 61 | + tags=[], |
| 62 | + ) |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +class _FakeClient: |
| 67 | + """Stands in for ``langfuse.Langfuse`` exposing only ``get_prompt``.""" |
| 68 | + |
| 69 | + def __init__(self, *, result: Any = None, exc: BaseException | None = None) -> None: |
| 70 | + self._result = result |
| 71 | + self._exc = exc |
| 72 | + self.calls: list[tuple[str, str]] = [] |
| 73 | + |
| 74 | + def get_prompt(self, name: str, *, label: str = "production", **_: Any) -> Any: |
| 75 | + self.calls.append((name, label)) |
| 76 | + if self._exc is not None: |
| 77 | + raise self._exc |
| 78 | + return self._result |
| 79 | + |
| 80 | + |
| 81 | +async def test_fetch_text_prompt_maps_to_prompt() -> None: |
| 82 | + client = _text_client(prompt="Hello {{ user }}", version=7, tags=["greeting"]) |
| 83 | + backend = LangfusePromptBackend(_FakeClient(result=client)) |
| 84 | + |
| 85 | + prompt = await backend.fetch("greeting", "production") |
| 86 | + |
| 87 | + assert prompt.name == "greeting" |
| 88 | + assert prompt.version == "7" |
| 89 | + assert prompt.label == "production" |
| 90 | + assert prompt.template == "Hello {{ user }}" |
| 91 | + assert prompt.template_hash.startswith("sha256:") |
| 92 | + assert prompt.observability_entities is not None |
| 93 | + assert prompt.observability_entities["langfuse_prompt"] is client |
| 94 | + assert prompt.metadata is not None |
| 95 | + assert prompt.metadata["langfuse_version"] == 7 |
| 96 | + assert prompt.metadata["langfuse_tags"] == ["greeting"] |
| 97 | + |
| 98 | + |
| 99 | +async def test_fetch_passes_label_through() -> None: |
| 100 | + fake = _FakeClient(result=_text_client()) |
| 101 | + backend = LangfusePromptBackend(fake) |
| 102 | + |
| 103 | + await backend.fetch("greeting", "staging") |
| 104 | + |
| 105 | + assert fake.calls == [("greeting", "staging")] |
| 106 | + |
| 107 | + |
| 108 | +async def test_chat_prompt_raises_not_found() -> None: |
| 109 | + backend = LangfusePromptBackend(_FakeClient(result=_chat_client())) |
| 110 | + |
| 111 | + with pytest.raises(PromptNotFound) as excinfo: |
| 112 | + await backend.fetch("chatty", "production") |
| 113 | + |
| 114 | + assert excinfo.value.backend == "langfuse" |
| 115 | + assert "chat prompt" in str(excinfo.value) |
| 116 | + |
| 117 | + |
| 118 | +async def test_not_found_maps_to_prompt_not_found() -> None: |
| 119 | + backend = LangfusePromptBackend(_FakeClient(exc=NotFoundError("nope"))) |
| 120 | + |
| 121 | + with pytest.raises(PromptNotFound): |
| 122 | + await backend.fetch("missing", "production") |
| 123 | + |
| 124 | + |
| 125 | +async def test_service_unavailable_maps_to_store_unavailable() -> None: |
| 126 | + backend = LangfusePromptBackend(_FakeClient(exc=ServiceUnavailableError())) |
| 127 | + |
| 128 | + with pytest.raises(PromptStoreUnavailable): |
| 129 | + await backend.fetch("greeting", "production") |
| 130 | + |
| 131 | + |
| 132 | +async def test_transport_error_maps_to_store_unavailable() -> None: |
| 133 | + # A connect/read/timeout/network failure surfaces as a raw httpx |
| 134 | + # TransportError (no HTTP response to map to a typed SDK error); it |
| 135 | + # must become PromptStoreUnavailable so PromptManager can fall back. |
| 136 | + backend = LangfusePromptBackend(_FakeClient(exc=httpx.ConnectTimeout("timed out"))) |
| 137 | + |
| 138 | + with pytest.raises(PromptStoreUnavailable): |
| 139 | + await backend.fetch("greeting", "production") |
| 140 | + |
| 141 | + |
| 142 | +async def test_sampling_extracted_from_config() -> None: |
| 143 | + client = _text_client(config={"temperature": 0.0, "max_tokens": 256, "model": "gpt-4o"}) |
| 144 | + backend = LangfusePromptBackend(_FakeClient(result=client)) |
| 145 | + |
| 146 | + prompt = await backend.fetch("greeting", "production") |
| 147 | + |
| 148 | + assert prompt.sampling is not None |
| 149 | + assert prompt.sampling.temperature == 0.0 |
| 150 | + assert prompt.sampling.max_tokens == 256 |
| 151 | + # Non-sampling config keys are not lifted into sampling, but the |
| 152 | + # full config is preserved under metadata. |
| 153 | + assert prompt.metadata is not None |
| 154 | + assert prompt.metadata["langfuse_config"]["model"] == "gpt-4o" |
| 155 | + |
| 156 | + |
| 157 | +async def test_no_sampling_config_yields_none() -> None: |
| 158 | + backend = LangfusePromptBackend(_FakeClient(result=_text_client(config={}))) |
| 159 | + |
| 160 | + prompt = await backend.fetch("greeting", "production") |
| 161 | + |
| 162 | + assert prompt.sampling is None |
| 163 | + |
| 164 | + |
| 165 | +async def test_fetched_prompt_renders_through_manager() -> None: |
| 166 | + backend = LangfusePromptBackend(_FakeClient(result=_text_client(prompt="Hi {{ user }}"))) |
| 167 | + manager = PromptManager(backend) |
| 168 | + |
| 169 | + prompt = await manager.fetch("greeting", "production") |
| 170 | + result = manager.render(prompt, {"user": "Alice"}) |
| 171 | + |
| 172 | + assert len(result.messages) == 1 |
| 173 | + assert result.messages[0].content == "Hi Alice" |
0 commit comments