Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions llm_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def extract_json_from_response(response_text: str) -> str:
think_end = response_text.find("</think>")
if think_start != -1 and think_end != -1:
response_text = response_text[:think_start] + response_text[think_end + 8 :]
response_text = response_text.strip()

# Remove leading ```json if present
if response_text.startswith("```json"):
Expand Down
50 changes: 50 additions & 0 deletions tests/llm_utils_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import importlib.util
import json
import sys
import types
import unittest
from pathlib import Path
from unittest.mock import patch


def load_extract_json_from_response():
models = types.ModuleType("models")
models.ModelProvider = types.SimpleNamespace(OLLAMA="ollama")
models.OllamaProvider = object
models.GeminiProvider = object

prompt = types.ModuleType("prompt")
prompt.MODEL_PROVIDER_MAPPING = {}
prompt.GEMINI_API_KEY = None

module_path = Path(__file__).parents[1] / "llm_utils.py"
spec = importlib.util.spec_from_file_location("llm_utils", module_path)
module = importlib.util.module_from_spec(spec)

with patch.dict(sys.modules, {"models": models, "prompt": prompt}):
spec.loader.exec_module(module)

return module.extract_json_from_response


extract_json_from_response = load_extract_json_from_response()


class ExtractJsonFromResponseTests(unittest.TestCase):
def test_supported_response_shapes_are_valid_json(self):
responses = {
"plain JSON": '{"ok": true}',
"fenced JSON": '```json\n{"ok": true}\n```',
"think block then fenced JSON": (
'<think>reasoning</think>\n```json\n{"ok": true}\n```'
),
}

for name, response in responses.items():
with self.subTest(name=name):
cleaned = extract_json_from_response(response)
self.assertEqual(json.loads(cleaned), {"ok": True})


if __name__ == "__main__":
unittest.main()