Skip to content

Commit 4e36109

Browse files
authored
feat: added a basic tool to search past conversation logs (#109)
1 parent 1da7d04 commit 4e36109

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

gptme/tools/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from .python import register_function
1515
from .read import tool as tool_read
1616
from .save import execute_save, tool_append, tool_save
17+
from .search_chats import tool as search_chats_tool
1718
from .shell import execute_shell
1819
from .shell import tool as shell_tool
1920
from .subagent import tool as subagent_tool
@@ -44,6 +45,7 @@
4445
tmux_tool,
4546
browser_tool,
4647
gh_tool,
48+
search_chats_tool,
4749
# python tool is loaded last to ensure all functions are registered
4850
get_python_tool,
4951
]

gptme/tools/search_chats.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import logging
2+
from pathlib import Path
3+
4+
from .base import ToolSpec
5+
6+
logger = logging.getLogger(__name__)
7+
8+
9+
def search_chats(query: str, max_results: int = 5) -> None:
10+
"""
11+
Search past conversation logs for the given query and print a summary of the results.
12+
13+
Args:
14+
query (str): The search query.
15+
max_results (int): Maximum number of conversations to display.
16+
"""
17+
# noreorder
18+
from ..logmanager import LogManager, get_conversations # fmt: skip
19+
20+
conversations = list(get_conversations())
21+
results = []
22+
23+
for conv in conversations:
24+
log_path = Path(conv["path"])
25+
log_manager = LogManager.load(log_path)
26+
27+
matching_messages = []
28+
for msg in log_manager.log:
29+
if query.lower() in msg.content.lower():
30+
matching_messages.append(msg)
31+
32+
if matching_messages:
33+
results.append(
34+
{
35+
"conversation": conv["name"],
36+
"messages": matching_messages,
37+
}
38+
)
39+
40+
# Sort results by the number of matching messages, in descending order
41+
results.sort(key=lambda x: len(x["messages"]), reverse=True)
42+
results = results[:max_results]
43+
44+
if not results:
45+
print(f"No results found for query: '{query}'")
46+
return
47+
48+
print(f"Search results for query: '{query}'")
49+
print(f"Found matches in {len(results)} conversation(s):")
50+
51+
for i, result in enumerate(results, 1):
52+
print(f"\n{i}. Conversation: {result['conversation']}")
53+
print(f" Number of matching messages: {len(result['messages'])}")
54+
print(" Sample matches:")
55+
# Show up to 3 sample messages
56+
for j, msg in enumerate(result["messages"][:3], 1):
57+
content = (
58+
msg.content[:100] + "..." if len(msg.content) > 100 else msg.content
59+
)
60+
print(f" {j}. {msg.role.capitalize()}: {content}")
61+
if len(result["messages"]) > 3:
62+
print(
63+
f" ... and {len(result['messages']) - 3} more matching message(s)"
64+
)
65+
66+
67+
instructions = """
68+
To search past conversation logs, you can use the `search_chats` function in Python.
69+
This function allows you to find relevant information from previous conversations.
70+
"""
71+
72+
examples = """
73+
### Search for a specific topic in past conversations
74+
User: Can you find any mentions of "python" in our past conversations?
75+
Assistant: Certainly! I'll search our past conversations for mentions of "python" using the search_chats function.
76+
```python
77+
search_chats("python")
78+
```
79+
"""
80+
81+
tool = ToolSpec(
82+
name="search_chats",
83+
desc="Search past conversation logs",
84+
instructions=instructions,
85+
examples=examples,
86+
functions=[search_chats],
87+
)

0 commit comments

Comments
 (0)