Repository navigation
Expand file tree
/
Copy pathvector_store.py
More file actions
283 lines (228 loc) · 10.1 KB
/
Copy pathvector_store.py
File metadata and controls
283 lines (228 loc) · 10.1 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""
In-memory tool repository implementation with embedding support.
"""
import json
from typing import List, Dict, Any, Optional, Tuple
import numpy as np
from embedding_model import EmbeddingModel
from utcp.shared.tool import Tool
from utcp.shared.provider import ProviderUnion, Provider
from utcp.client.tool_repository import ToolRepository
class EmbeddingInMemRepo(ToolRepository):
"""
In-memory tool repository with embedding support for tool search.
"""
def __init__(self, embedding_model: EmbeddingModel):
"""
Initialize the in-memory tool repository.
Args:
embedding_model: The embedding model for generating embeddings
"""
self.tools: List[Tool] = []
self.tool_per_provider: Dict[str, Tuple[Provider, List[Tool]]] = {}
self.embedding_model = embedding_model
self._tool_embeddings: Dict[str, List[float]] = {} # tool_name -> embedding
self._all_tags: set = set() # Cache of all unique tags
async def save_provider_with_tools(self, provider: Provider, tools: List[Tool]) -> None:
"""
Save a provider and its tools in the repository.
Args:
provider: The provider to save.
tools: The tools associated with the provider.
"""
# Remove existing tools for this provider if any
if provider.name in self.tool_per_provider:
await self.remove_provider(provider.name)
# Add tools to main list and generate embeddings
# Try batch embedding first for better performance
try:
embed_texts = [f"{tool.name} {tool.description} {' '.join(tool.tags)}" for tool in tools]
embeddings = await self.embedding_model.embed_batch(embed_texts)
# Store embeddings and update tags (skip empty embeddings from failed batch items)
for tool, embedding in zip(tools, embeddings):
if embedding: # Only store non-empty embeddings
self._tool_embeddings[tool.name] = embedding
self._all_tags.update(tool.tags)
except Exception as e:
print(f"Batch embedding failed, falling back to individual embeddings: {e}")
# Fallback to individual embedding generation
for tool in tools:
try:
embed_text = f"{tool.name} {tool.description} {' '.join(tool.tags)}"
embedding = await self.embedding_model.embed(embed_text)
self._tool_embeddings[tool.name] = embedding
self._all_tags.update(tool.tags)
except Exception as embed_error:
print(f"Failed to generate embedding for tool {tool.name}: {embed_error}")
# Continue with other tools even if one fails
self.tools.extend(tools)
self.tool_per_provider[provider.name] = (provider, tools)
async def remove_provider(self, provider_name: str) -> None:
"""
Remove a provider and its tools from the repository.
Args:
provider_name: The name of the provider to remove.
Raises:
ValueError: If the provider is not found.
"""
if provider_name not in self.tool_per_provider:
raise ValueError(f"Provider '{provider_name}' not found")
tools_to_remove = self.tool_per_provider[provider_name][1]
# Remove tools from main list
self.tools = [tool for tool in self.tools if tool not in tools_to_remove]
# Remove embeddings for these tools
for tool in tools_to_remove:
self._tool_embeddings.pop(tool.name, None)
# Remove provider
self.tool_per_provider.pop(provider_name, None)
# Rebuild tags cache
self._all_tags = set()
for tool in self.tools:
self._all_tags.update(tool.tags)
async def remove_tool(self, tool_name: str) -> None:
"""
Remove a tool from the repository.
Args:
tool_name: The name of the tool to remove.
Raises:
ValueError: If the tool is not found.
"""
provider_name = tool_name.split(".")[0]
if provider_name not in self.tool_per_provider:
raise ValueError(f"Provider '{provider_name}' not found")
# Find and remove tool from main list
new_tools = [tool for tool in self.tools if tool.name != tool_name]
if len(new_tools) == len(self.tools):
raise ValueError(f"Tool '{tool_name}' not found")
self.tools = new_tools
# Remove embedding
self._tool_embeddings.pop(tool_name, None)
# Update provider's tool list
provider, provider_tools = self.tool_per_provider[provider_name]
new_provider_tools = [tool for tool in provider_tools if tool.name != tool_name]
self.tool_per_provider[provider_name] = (provider, new_provider_tools)
# Rebuild tags cache
self._all_tags = set()
for tool in self.tools:
self._all_tags.update(tool.tags)
async def get_tool(self, tool_name: str) -> Optional[Tool]:
"""
Get a tool from the repository.
Args:
tool_name: The name of the tool to retrieve.
Returns:
The tool if found, otherwise None.
"""
for tool in self.tools:
if tool.name == tool_name:
return tool
return None
async def get_tools(self) -> List[Tool]:
"""
Get all tools from the repository.
Returns:
List of all tools
"""
return self.tools
async def get_tools_by_provider(self, provider_name: str) -> Optional[List[Tool]]:
"""
Get tools associated with a specific provider.
Args:
provider_name: The name of the provider.
Returns:
A list of tools associated with the provider, or None if the provider is not found.
"""
if provider_name not in self.tool_per_provider:
return None
return self.tool_per_provider[provider_name][1]
async def get_provider(self, provider_name: str) -> Optional[Provider]:
"""
Get a provider from the repository.
Args:
provider_name: The name of the provider to retrieve.
Returns:
The provider if found, otherwise None.
"""
if provider_name not in self.tool_per_provider:
return None
return self.tool_per_provider[provider_name][0]
async def get_providers(self) -> List[Provider]:
"""
Get all providers from the repository.
Returns:
A list of providers.
"""
return [provider for provider, _ in self.tool_per_provider.values()]
def get_all_tags(self) -> List[str]:
"""
Get all unique tags from the repository.
Returns:
List of all unique tags
"""
return list(self._all_tags)
def _cosine_similarity(self, v1: List[float], v2: List[float]) -> float:
"""Calculate cosine similarity between two vectors"""
vec1 = np.array(v1)
vec2 = np.array(v2)
dot_product = np.dot(vec1, vec2)
norm_v1 = np.linalg.norm(vec1)
norm_v2 = np.linalg.norm(vec2)
return dot_product / (norm_v1 * norm_v2)
async def search_by_embedding(self, query_embedding: List[float], top_k: int = 5) -> List[Tuple[Tool, float]]:
"""
Search tools by embedding similarity.
Args:
query_embedding: The query embedding
top_k: Maximum number of results to return
Returns:
List of (Tool, similarity_score) tuples
"""
results = []
for tool in self.tools:
if tool.name in self._tool_embeddings:
embedding = self._tool_embeddings[tool.name]
similarity = self._cosine_similarity(query_embedding, embedding)
results.append((tool, similarity))
# Sort by similarity score in descending order
results.sort(key=lambda x: x[1], reverse=True)
return results[:top_k]
# Legacy method for backward compatibility
def remove_tool_legacy(self, name: str) -> bool:
"""
Remove a tool from the store (legacy method).
Args:
name: Name of the tool to remove
Returns:
True if the tool was removed, False if not found
"""
try:
import asyncio
asyncio.create_task(self.remove_tool(name))
return True
except ValueError:
return False
except Exception:
return False
async def search_by_tags(self, tags: List[str], top_k: int = 5) -> List[Tuple[Tool, float]]:
"""
Search tools by tag overlap (Jaccard similarity).
Args:
tags: List of tags to search for
top_k: Maximum number of results to return
Returns:
List of (tool, score) tuples, where score is the Jaccard similarity
"""
tools = await self.get_tools()
results = []
for tool in tools:
# Calculate tag overlap score (proportion of searched tags that exist in this tool)
matching_tags = set(tags) & set(tool.tags)
if matching_tags:
# Score is a combination of tag match ratio and the number of matching tags
match_ratio = len(matching_tags) / len(tags)
tag_weight = len(matching_tags) / (len(tool.tags) + 1) # +1 to avoid division by zero
score = (match_ratio + tag_weight) / 2
results.append((tool, score))
# Sort by tag overlap score in descending order
results.sort(key=lambda x: x[1], reverse=True)
return results[:top_k]