Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Add prompt summary utility

Abi Raja5d2e7fe8c6f8
diff --git a/backend/README.md b/backend/README.md
index 155bf460..e3ea8830 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -5,3 +5,12 @@ poetry run pyright
# Run tests
poetry run pytest
+
+## Prompt Summary
+
+Use `print_prompt_summary` from `utils.py` to quickly visualize prompts:
+
+```python
+from utils import print_prompt_summary
+print_prompt_summary(prompt_messages)
+```
diff --git a/backend/tests/test_prompt_summary.py b/backend/tests/test_prompt_summary.py
new file mode 100644
index 00000000..dc71a8f3
--- /dev/null
+++ b/backend/tests/test_prompt_summary.py
@@ -0,0 +1,20 @@
+import pytest
+from utils import format_prompt_summary
+
+
+def test_format_prompt_summary():
+ messages = [
+ {"role": "system", "content": "lorem ipsum dolor sit amet"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "hello world"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAA"}},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,BBB"}},
+ ],
+ },
+ ]
+
+ summary = format_prompt_summary(messages)
+ assert "system: lorem ipsum" in summary
+ assert "[2 images]" in summary
diff --git a/backend/utils.py b/backend/utils.py
index 6c28e141..63949a41 100644
--- a/backend/utils.py
+++ b/backend/utils.py
@@ -8,6 +8,37 @@ def pprint_prompt(prompt_messages: List[ChatCompletionMessageParam]):
print(json.dumps(truncate_data_strings(prompt_messages), indent=4))
+def format_prompt_summary(prompt_messages: List[ChatCompletionMessageParam]) -> str:
+ parts: list[str] = []
+ for message in prompt_messages:
+ role = message["role"]
+ content = message["content"]
+ text = ""
+ image_count = 0
+
+ if isinstance(content, list):
+ for item in content:
+ if item["type"] == "text":
+ text += item["text"] + " "
+ elif item["type"] == "image_url":
+ image_count += 1
+ else:
+ text = str(content)
+
+ text = text.strip()
+ if len(text) > 40:
+ text = text[:40] + "..."
+
+ img_part = f" + [{image_count} images]" if image_count else ""
+ parts.append(f"{role}: {text}{img_part}")
+
+ return " / ".join(parts)
+
+
+def print_prompt_summary(prompt_messages: List[ChatCompletionMessageParam]):
+ print(format_prompt_summary(prompt_messages))
+
+
def truncate_data_strings(data: List[ChatCompletionMessageParam]): # type: ignore
# Deep clone the data to avoid modifying the original object
cloned_data = copy.deepcopy(data)