Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

fix(utils): render inspect history tool calls (#9835)

Isaac Miller571171227a48
diff --git a/dspy/utils/inspect_history.py b/dspy/utils/inspect_history.py
index 46aebad1c..e52161ff2 100644
--- a/dspy/utils/inspect_history.py
+++ b/dspy/utils/inspect_history.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import json
import sys
+from contextlib import suppress
from typing import Any, TextIO
@@ -35,6 +37,16 @@ def pretty_print_history(history: list[dict[str, Any]], n: int = 1, file: TextIO
out = file or sys.stdout
use_colors = file is None
+ def print_tool_calls(tool_calls):
+ if tool_calls:
+ print(_red("Tool calls:", use_colors=use_colors), file=out)
+ for tool_call in tool_calls or []:
+ function = tool_call.get("function") or {}
+ arguments = function.get("arguments")
+ arguments = tool_call.get("args", tool_call.get("arguments", {})) if arguments is None else arguments
+ with suppress(json.JSONDecodeError):
+ arguments = json.loads(arguments) if isinstance(arguments, str) else arguments
+ print(_green(f"{function.get('name') or tool_call.get('name', '<unknown>')}: {json.dumps(arguments, ensure_ascii=False) if isinstance(arguments, (dict, list)) else str(arguments)}", use_colors=use_colors), file=out)
for item in history[-n:]:
messages = item["messages"] or [{"role": "user", "content": item["prompt"]}]
outputs = item["outputs"]
@@ -75,17 +87,15 @@ def pretty_print_history(history: list[dict[str, Any]], n: int = 1, file: TextIO
file_data = file_info.get("file_data", "")
file_str = f"<file: name:{filename}, id:{file_id}, data_length:{len(file_data)}>"
print(_blue(file_str.strip(), use_colors=use_colors), file=out)
+ print_tool_calls(msg.get("tool_calls"))
print("\n", file=out)
if isinstance(outputs[0], dict):
- if outputs[0]["text"]:
+ if outputs[0].get("text"):
print(_red("Response:", use_colors=use_colors), file=out)
print(_green(outputs[0]["text"].strip(), use_colors=use_colors), file=out)
- if outputs[0].get("tool_calls"):
- print(_red("Tool calls:", use_colors=use_colors), file=out)
- for tool_call in outputs[0]["tool_calls"]:
- print(_green(f"{tool_call['function']['name']}: {tool_call['function']['arguments']}", use_colors=use_colors), file=out)
+ print_tool_calls(outputs[0].get("tool_calls"))
else:
print(_red("Response:", use_colors=use_colors), file=out)
print(_green(outputs[0].strip(), use_colors=use_colors), file=out)
diff --git a/tests/clients/test_inspect_global_history.py b/tests/clients/test_inspect_global_history.py
index cd9a42b70..f2f63975c 100644
--- a/tests/clients/test_inspect_global_history.py
+++ b/tests/clients/test_inspect_global_history.py
@@ -1,8 +1,11 @@
+from io import StringIO
+
import pytest
import dspy
from dspy.clients.base_lm import GLOBAL_HISTORY
from dspy.utils.dummies import DummyLM
+from dspy.utils.inspect_history import pretty_print_history
@pytest.fixture(autouse=True)
@@ -30,6 +33,65 @@ def test_inspect_history_basic(capsys):
assert all("messages" in entry for entry in history)
+def test_inspect_history_renders_message_tool_calls():
+ out = StringIO()
+ history = [
+ {
+ "messages": [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "search", "arguments": '{"query":"cats"}'},
+ }
+ ],
+ },
+ {"role": "tool", "content": "cat result", "tool_call_id": "call_1", "name": "search"},
+ ],
+ "outputs": [{"text": "done"}],
+ "timestamp": "now",
+ }
+ ]
+
+ pretty_print_history(history, n=1, file=out)
+
+ text = out.getvalue()
+ assert "Assistant message:" in text
+ assert "Tool calls:" in text
+ assert 'search: {"query": "cats"}' in text
+ assert "Tool message:" in text
+ assert "cat result" in text
+
+
+def test_inspect_history_renders_output_tool_calls_without_text():
+ out = StringIO()
+ history = [
+ {
+ "messages": [{"role": "user", "content": "Find cats"}],
+ "outputs": [
+ {
+ "tool_calls": [
+ {"name": "lookup", "arguments": {"query": "cats"}},
+ {"name": "search", "args": {"query": "dogs"}},
+ ]
+ }
+ ],
+ "timestamp": "now",
+ }
+ ]
+
+ pretty_print_history(history, n=1, file=out)
+
+ text = out.getvalue()
+ assert "Response:" not in text
+ assert "Tool calls:" in text
+ assert 'lookup: {"query": "cats"}' in text
+ assert 'search: {"query": "dogs"}' in text
+
+
def test_inspect_history_with_n(capsys):
"""Test that inspect_history works with n
Random failures in this test most likely mean you are printing messages somewhere
@@ -45,7 +107,7 @@ def test_inspect_history_with_n(capsys):
dspy.inspect_history(n=2)
# Test getting last 2 entries
- out, err = capsys.readouterr()
+ out, _err = capsys.readouterr()
assert "First" not in out
assert "Second" in out
assert "Third" in out