Repository navigation
Expand file tree
/
Copy pathsearch_tools.py
More file actions
154 lines (123 loc) · 5.32 KB
/
Copy pathsearch_tools.py
File metadata and controls
154 lines (123 loc) · 5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
from typing import Dict, Any, Optional, Protocol
from abc import ABC, abstractmethod
from vector_store import VectorStore, SearchResults
class Tool(ABC):
"""Abstract base class for all tools"""
@abstractmethod
def get_tool_definition(self) -> Dict[str, Any]:
"""Return Anthropic tool definition for this tool"""
pass
@abstractmethod
def execute(self, **kwargs) -> str:
"""Execute the tool with given parameters"""
pass
class CourseSearchTool(Tool):
"""Tool for searching course content with semantic course name matching"""
def __init__(self, vector_store: VectorStore):
self.store = vector_store
self.last_sources = [] # Track sources from last search
def get_tool_definition(self) -> Dict[str, Any]:
"""Return Anthropic tool definition for this tool"""
return {
"name": "search_course_content",
"description": "Search course materials with smart course name matching and lesson filtering",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "What to search for in the course content"
},
"course_name": {
"type": "string",
"description": "Course title (partial matches work, e.g. 'MCP', 'Introduction')"
},
"lesson_number": {
"type": "integer",
"description": "Specific lesson number to search within (e.g. 1, 2, 3)"
}
},
"required": ["query"]
}
}
def execute(self, query: str, course_name: Optional[str] = None, lesson_number: Optional[int] = None) -> str:
"""
Execute the search tool with given parameters.
Args:
query: What to search for
course_name: Optional course filter
lesson_number: Optional lesson filter
Returns:
Formatted search results or error message
"""
# Use the vector store's unified search interface
results = self.store.search(
query=query,
course_name=course_name,
lesson_number=lesson_number
)
# Handle errors
if results.error:
return results.error
# Handle empty results
if results.is_empty():
filter_info = ""
if course_name:
filter_info += f" in course '{course_name}'"
if lesson_number:
filter_info += f" in lesson {lesson_number}"
return f"No relevant content found{filter_info}."
# Format and return results
return self._format_results(results)
def _format_results(self, results: SearchResults) -> str:
"""Format search results with course and lesson context"""
formatted = []
sources = [] # Track sources for the UI
for doc, meta in zip(results.documents, results.metadata):
course_title = meta.get('course_title', 'unknown')
lesson_num = meta.get('lesson_number')
# Build context header
header = f"[{course_title}"
if lesson_num is not None:
header += f" - Lesson {lesson_num}"
header += "]"
# Track source for the UI
source = course_title
if lesson_num is not None:
source += f" - Lesson {lesson_num}"
sources.append(source)
formatted.append(f"{header}\n{doc}")
# Store sources for retrieval
self.last_sources = sources
return "\n\n".join(formatted)
class ToolManager:
"""Manages available tools for the AI"""
def __init__(self):
self.tools = {}
def register_tool(self, tool: Tool):
"""Register any tool that implements the Tool interface"""
tool_def = tool.get_tool_definition()
tool_name = tool_def.get("name")
if not tool_name:
raise ValueError("Tool must have a 'name' in its definition")
self.tools[tool_name] = tool
def get_tool_definitions(self) -> list:
"""Get all tool definitions for Anthropic tool calling"""
return [tool.get_tool_definition() for tool in self.tools.values()]
def execute_tool(self, tool_name: str, **kwargs) -> str:
"""Execute a tool by name with given parameters"""
if tool_name not in self.tools:
return f"Tool '{tool_name}' not found"
return self.tools[tool_name].execute(**kwargs)
def get_last_sources(self) -> list:
"""Get sources from the last search operation"""
# Check all tools for last_sources attribute
for tool in self.tools.values():
if hasattr(tool, 'last_sources') and tool.last_sources:
return tool.last_sources
return []
def reset_sources(self):
"""Reset sources from all tools that track sources"""
for tool in self.tools.values():
if hasattr(tool, 'last_sources'):
tool.last_sources = []