valiantlynxz commited on
Commit
9db78b0
·
unverified ·
1 Parent(s): cfbd01e

Add tool embeddings (800 tools, 3072-dim) + OpenAPI spec + scripts

Browse files
README.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ configs:
4
+ - config_name: embeddings
5
+ data_files: "embeddings.parquet"
6
+ default: true
7
+ - config_name: tools
8
+ data_files: "tools.parquet"
9
+ task_categories:
10
+ - feature-extraction
11
+ - text-classification
12
+ language:
13
+ - "en"
14
+ - "no"
15
+ tags:
16
+ - embeddings
17
+ - openapi
18
+ - tripletex
19
+ - accounting
20
+ - api-tools
21
+ - rag
22
+ - lancedb
23
+ - pydantic
24
+ size_categories:
25
+ - n<1K
26
+ ---
27
+
28
+ # Tripletex API Tool Embeddings
29
+
30
+ Pre-computed embeddings for 800 Tripletex accounting API tools, extracted from the OpenAPI 3.0.1 spec and embedded with Google `gemini-embedding-001` (3072 dimensions).
31
+
32
+ Built for RAG-based tool filtering in the [AI Accounting Agent](https://github.com/kuben-labs/nmai) competition project.
33
+
34
+ ## Quick Start
35
+
36
+ ```python
37
+ from datasets import load_dataset
38
+
39
+ # Full embeddings (800 tools, 3072-dim vectors) — ready for RAG
40
+ ds = load_dataset("valiantlynxz/tripletex-tool-embeddings")
41
+
42
+ # Lightweight: tool metadata only, no embedding vectors
43
+ ds = load_dataset("valiantlynxz/tripletex-tool-embeddings", name="tools")
44
+ ```
45
+
46
+ ## Configurations
47
+
48
+ | Config | Default | Columns | Size | Use case |
49
+ |--------|---------|---------|------|----------|
50
+ | `embeddings` | Yes | name, description, parameters, embedding | ~9 MB | RAG search, vector index |
51
+ | `tools` | | name, description, parameters | ~50 KB | Browsing, filtering, analysis |
52
+
53
+ ## Schema
54
+
55
+ ### `embeddings` config
56
+
57
+ ```python
58
+ ds = load_dataset("valiantlynxz/tripletex-tool-embeddings")
59
+ example = ds["train"][0]
60
+
61
+ example["name"] # "AccountantDashboardNews_get"
62
+ example["description"] # "Get public news articles"
63
+ example["parameters"] # '{"from": "integer", "count": "integer", ...}' (JSON string)
64
+ example["embedding"] # [3072 floats] — gemini-embedding-001 vector
65
+ ```
66
+
67
+ ### `tools` config
68
+
69
+ ```python
70
+ ds = load_dataset("valiantlynxz/tripletex-tool-embeddings", name="tools")
71
+ example = ds["train"][0]
72
+
73
+ example["name"] # "AccountantDashboardNews_get"
74
+ example["description"] # "Get public news articles"
75
+ example["parameters"] # '{"from": "integer", "count": "integer", ...}' (JSON string)
76
+ ```
77
+
78
+ ## Data Summary
79
+
80
+ - **800 API tools** from the Tripletex accounting API (OpenAPI 3.0.1)
81
+ - **3072-dimensional embeddings** via Google `gemini-embedding-001`
82
+ - **Parameters** stored as JSON strings mapping param names to types
83
+ - **Source:** `openapi.json` included in this repo (3.5 MB, 546 paths, 2167 schemas)
84
+
85
+ ## Using with LanceDB
86
+
87
+ ```python
88
+ from datasets import load_dataset
89
+ import lancedb
90
+
91
+ ds = load_dataset("valiantlynxz/tripletex-tool-embeddings")
92
+
93
+ # Convert to LanceDB
94
+ db = lancedb.connect(".tool_embeddings")
95
+ records = [
96
+ {
97
+ "name": row["name"],
98
+ "description": row["description"],
99
+ "parameters": row["parameters"],
100
+ "embedding": row["embedding"],
101
+ }
102
+ for row in ds["train"]
103
+ ]
104
+ table = db.create_table("tools", data=records, mode="overwrite")
105
+
106
+ # Search
107
+ results = table.search(query_embedding).limit(100).to_list()
108
+ ```
109
+
110
+ ## Using with FAISS
111
+
112
+ ```python
113
+ from datasets import load_dataset
114
+ import numpy as np
115
+ import faiss
116
+
117
+ ds = load_dataset("valiantlynxz/tripletex-tool-embeddings")
118
+
119
+ embeddings = np.array(ds["train"]["embedding"], dtype=np.float32)
120
+ index = faiss.IndexFlatIP(3072)
121
+ faiss.normalize_L2(embeddings)
122
+ index.add(embeddings)
123
+
124
+ # Search
125
+ query = np.array([query_embedding], dtype=np.float32)
126
+ faiss.normalize_L2(query)
127
+ distances, indices = index.search(query, k=100)
128
+ tool_names = [ds["train"][int(i)]["name"] for i in indices[0]]
129
+ ```
130
+
131
+ ## Regenerating Embeddings
132
+
133
+ The `scripts/` directory contains the original embedding pipeline:
134
+
135
+ - `scripts/embeddings.py` — Google Gemini embedding provider
136
+ - `scripts/rag_tool_filter.py` — OpenAPI-to-embedding pipeline + LanceDB vector store
137
+
138
+ ```python
139
+ # Requires: google-genai, lancedb
140
+ # Requires: GCP_API_KEY environment variable
141
+
142
+ from scripts.embeddings import get_embedding_provider
143
+ from scripts.rag_tool_filter import ToolEmbedder, ToolVectorStore, index_openapi_tools
144
+ import json, asyncio
145
+
146
+ with open("openapi.json") as f:
147
+ spec = json.load(f)
148
+
149
+ provider = get_embedding_provider()
150
+ embedder = ToolEmbedder(provider)
151
+ store = ToolVectorStore(".tool_embeddings")
152
+ asyncio.run(index_openapi_tools(spec, store, embedder))
153
+ ```
154
+
155
+ ## Repo Structure
156
+
157
+ ```
158
+ tripletex-tool-embeddings/
159
+ ├── README.md
160
+ ├── embeddings.parquet # 800 tools with 3072-dim embeddings
161
+ ├── tools.parquet # 800 tools metadata only (lightweight)
162
+ ├── openapi.json # Source Tripletex OpenAPI 3.0.1 spec (3.5 MB)
163
+ └── scripts/
164
+ ├── embeddings.py # Google Gemini embedding provider
165
+ └── rag_tool_filter.py # OpenAPI extraction + LanceDB indexing
166
+ ```
167
+
168
+ ## Source Project
169
+
170
+ Part of the [nmai](https://github.com/kuben-labs/nmai) project — `ai-accounting-agent/`.
embeddings.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1fab870063479bfd830d8a5ce123de399c5edb0f22ae00c26a9568f44507873
3
+ size 10494645
openapi.json ADDED
The diff for this file is too large to render. See raw diff
 
scripts/embeddings.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google embeddings provider using pydantic-ai.
2
+
3
+ This module provides direct integration with Google Gemini embedding models
4
+ without relying on machine-core or model-providers packages.
5
+ """
6
+
7
+ import os
8
+ from typing import List, Optional
9
+
10
+ from loguru import logger
11
+
12
+
13
+ class GoogleEmbeddingProvider:
14
+ """Wrapper for Google Gemini embedding model.
15
+
16
+ This class provides a simple interface compatible with the existing
17
+ ToolEmbedder class that expects an `embed` method.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ model_name: Optional[str] = None,
23
+ api_key: Optional[str] = None,
24
+ dimensions: Optional[int] = None,
25
+ ):
26
+ """Initialize the Google embedding provider.
27
+
28
+ Args:
29
+ model_name: The embedding model name (defaults to gemini-embedding-001)
30
+ api_key: Google API key (defaults to GCP_API_KEY env var)
31
+ dimensions: Output embedding dimensions (defaults to EMBEDDING_DIMENSIONS env var or 3072)
32
+ """
33
+ self.model_name = model_name or os.getenv(
34
+ "EMBEDDING_MODEL", "gemini-embedding-001"
35
+ )
36
+ self.api_key = api_key or os.getenv("GCP_API_KEY")
37
+ self.dimensions = dimensions or int(os.getenv("EMBEDDING_DIMENSIONS", "3072"))
38
+
39
+ if not self.api_key:
40
+ raise ValueError(
41
+ "Google API key is required for embeddings. "
42
+ "Set GCP_API_KEY environment variable or pass api_key parameter."
43
+ )
44
+
45
+ # Import here to avoid issues if google-genai is not installed
46
+ try:
47
+ from google import genai # type: ignore
48
+
49
+ self._client = genai.Client(api_key=self.api_key)
50
+ self._types = genai.types
51
+ self._initialized = True
52
+ logger.info(f"Initialized Google embedding provider: {self.model_name}")
53
+ except ImportError:
54
+ logger.error("google-genai package not installed")
55
+ self._client = None
56
+ self._types = None
57
+ self._initialized = False
58
+
59
+ def embed(self, texts: List[str]) -> List[List[float]]:
60
+ """Embed a list of texts.
61
+
62
+ Args:
63
+ texts: List of text strings to embed
64
+
65
+ Returns:
66
+ List of embedding vectors
67
+ """
68
+ if not self._initialized or self._client is None:
69
+ logger.warning("Google embedding provider not initialized")
70
+ return [[] for _ in texts]
71
+
72
+ try:
73
+ # Use Google's new genai SDK
74
+ result = self._client.models.embed_content(
75
+ model=self.model_name,
76
+ contents=texts,
77
+ config=self._types.EmbedContentConfig( # type: ignore
78
+ task_type="RETRIEVAL_DOCUMENT",
79
+ output_dimensionality=self.dimensions,
80
+ ),
81
+ )
82
+
83
+ # Extract embeddings
84
+ return [e.values for e in result.embeddings]
85
+
86
+ except Exception as e:
87
+ logger.error(f"Failed to embed texts: {e}")
88
+ return [[] for _ in texts]
89
+
90
+ async def embed_async(self, texts: List[str]) -> List[List[float]]:
91
+ """Async version of embed - delegates to sync for now.
92
+
93
+ Args:
94
+ texts: List of text strings to embed
95
+
96
+ Returns:
97
+ List of embedding vectors
98
+ """
99
+ import asyncio
100
+
101
+ return await asyncio.to_thread(self.embed, texts)
102
+
103
+
104
+ def get_embedding_provider(
105
+ model_name: Optional[str] = None,
106
+ api_key: Optional[str] = None,
107
+ dimensions: Optional[int] = None,
108
+ ) -> GoogleEmbeddingProvider:
109
+ """Factory function to create a Google embedding provider.
110
+
111
+ Args:
112
+ model_name: The embedding model name
113
+ api_key: Google API key
114
+ dimensions: Output embedding dimensions
115
+
116
+ Returns:
117
+ GoogleEmbeddingProvider instance
118
+ """
119
+ return GoogleEmbeddingProvider(
120
+ model_name=model_name,
121
+ api_key=api_key,
122
+ dimensions=dimensions,
123
+ )
scripts/rag_tool_filter.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RAG-based tool filtering system for reducing context size.
2
+
3
+ This module provides functionality to:
4
+ 1. Extract and embed all available MCP tools
5
+ 2. Store embeddings in a vector database (LanceDB)
6
+ 3. Filter tools based on semantic similarity to task prompts
7
+ 4. Return relevant tool names (set[str]) for use with FilteredToolset
8
+
9
+ The actual tool filtering is done by pydantic-ai's native FilteredToolset,
10
+ which preserves full parameter schemas. This module only handles the
11
+ embedding index and semantic search to determine WHICH tools are relevant.
12
+ """
13
+
14
+ import json
15
+ import asyncio
16
+ from pathlib import Path
17
+ from typing import Optional, List, Dict, Any, Set, Tuple
18
+ from dataclasses import dataclass
19
+
20
+ from loguru import logger
21
+
22
+ try:
23
+ import lancedb
24
+ except ImportError:
25
+ lancedb = None
26
+
27
+
28
+ @dataclass
29
+ class ToolMetadata:
30
+ """Metadata for a single tool."""
31
+
32
+ name: str
33
+ description: str
34
+ parameters: Dict[str, Any]
35
+ category: Optional[str] = None
36
+ embedding: Optional[List[float]] = None
37
+
38
+
39
+ class ToolEmbedder:
40
+ """Handles embedding of tool descriptions for semantic search."""
41
+
42
+ def __init__(self, embedding_provider=None):
43
+ """Initialize the tool embedder.
44
+
45
+ Args:
46
+ embedding_provider: Optional embedding provider (GoogleEmbeddingProvider).
47
+ If None, will try to get from environment.
48
+ """
49
+ self.embedding_provider = embedding_provider
50
+ # If embedding_provider has a provider attribute, extract the actual provider
51
+ if embedding_provider and hasattr(embedding_provider, "provider"):
52
+ self.provider = embedding_provider.provider
53
+ else:
54
+ self.provider = embedding_provider
55
+
56
+ async def embed_tools_batch(
57
+ self, tools: List[ToolMetadata], batch_size: int = 32
58
+ ) -> List[ToolMetadata]:
59
+ """Embed multiple tools in batches for efficiency.
60
+
61
+ Args:
62
+ tools: List of tools to embed
63
+ batch_size: Number of tools to embed per batch
64
+
65
+ Returns:
66
+ List of tools with embeddings added
67
+ """
68
+ if self.provider is None:
69
+ logger.warning("No embedding provider configured, skipping embeddings")
70
+ return tools
71
+
72
+ embedded_tools = []
73
+ total = len(tools)
74
+
75
+ for i in range(0, total, batch_size):
76
+ batch = tools[i : i + batch_size]
77
+ logger.debug(f"Embedding batch {i // batch_size + 1} ({len(batch)} tools)")
78
+
79
+ try:
80
+ # Create text representations for embedding
81
+ tool_texts = []
82
+ for tool in batch:
83
+ # Limit parameters JSON to first 2000 chars for embedding
84
+ params_str = json.dumps(tool.parameters, indent=2, default=str)
85
+ if len(params_str) > 2000:
86
+ params_str = params_str[:2000] + "..."
87
+
88
+ tool_text = f"""
89
+ Tool: {tool.name}
90
+ Description: {tool.description}
91
+ Parameters: {params_str}
92
+ """.strip()
93
+ tool_texts.append(tool_text)
94
+
95
+ # Get embeddings for the batch
96
+ embeddings = await asyncio.to_thread(self.provider.embed, tool_texts)
97
+
98
+ # Assign embeddings to tools
99
+ for tool, embedding in zip(batch, embeddings):
100
+ if embedding:
101
+ tool.embedding = embedding
102
+ embedded_tools.append(tool)
103
+
104
+ except Exception as e:
105
+ logger.warning(f"Failed to embed batch: {e}")
106
+ embedded_tools.extend(batch)
107
+
108
+ return embedded_tools
109
+
110
+ async def embed_text(self, text: str) -> List[float]:
111
+ """Embed a text string (e.g., task prompt).
112
+
113
+ Args:
114
+ text: Text to embed
115
+
116
+ Returns:
117
+ Embedding vector
118
+ """
119
+ if self.provider is None:
120
+ logger.warning("No embedding provider configured")
121
+ return []
122
+
123
+ try:
124
+ embeddings = await asyncio.to_thread(self.provider.embed, [text])
125
+ if embeddings and len(embeddings) > 0:
126
+ return embeddings[0]
127
+ return []
128
+ except Exception as e:
129
+ logger.error(f"Failed to embed text: {e}")
130
+ return []
131
+
132
+
133
+ class ToolVectorStore:
134
+ """Manages tool embeddings and vector similarity search using LanceDB."""
135
+
136
+ def __init__(self, db_path: str = ".tool_embeddings"):
137
+ """Initialize the vector store using LanceDB.
138
+
139
+ Args:
140
+ db_path: Path to store the LanceDB database
141
+ """
142
+ self.db_path = Path(db_path)
143
+ self.db_path.mkdir(exist_ok=True)
144
+
145
+ if lancedb is None:
146
+ raise ImportError(
147
+ "lancedb is required for RAG tool filtering. Install with: uv add lancedb"
148
+ )
149
+
150
+ self.db = lancedb.connect(str(self.db_path))
151
+ self.table = None
152
+ self.tools: Dict[str, ToolMetadata] = {}
153
+
154
+ # Load existing tools from database
155
+ self._load_from_disk()
156
+
157
+ def _load_from_disk(self):
158
+ """Load tools from LanceDB if the table exists."""
159
+ try:
160
+ if "tools" in self.db.table_names():
161
+ self.table = self.db.open_table("tools")
162
+ records = self.table.search().limit(10000).to_list()
163
+
164
+ for record in records:
165
+ tool = ToolMetadata(
166
+ name=record["name"],
167
+ description=record["description"],
168
+ parameters=record.get("parameters", {}),
169
+ category=record.get("category"),
170
+ embedding=record.get("embedding"),
171
+ )
172
+ self.tools[record["name"]] = tool
173
+
174
+ logger.info(f"Loaded {len(self.tools)} tools from LanceDB")
175
+ else:
176
+ logger.debug("No existing tools table in LanceDB")
177
+
178
+ except Exception as e:
179
+ logger.warning(f"Failed to load tools from LanceDB: {e}")
180
+
181
+ def _save_to_disk(self):
182
+ """Save tools to LanceDB with embeddings."""
183
+ try:
184
+ records = []
185
+ for tool_name, tool in self.tools.items():
186
+ records.append(
187
+ {
188
+ "name": tool.name,
189
+ "description": tool.description,
190
+ "parameters": json.dumps(tool.parameters, default=str),
191
+ "category": tool.category,
192
+ "embedding": tool.embedding,
193
+ }
194
+ )
195
+
196
+ if not records:
197
+ logger.warning("No tools to save")
198
+ return
199
+
200
+ if self.table is None:
201
+ self.table = self.db.create_table(
202
+ "tools", data=records, mode="overwrite"
203
+ )
204
+ else:
205
+ self.db.drop_table("tools")
206
+ self.table = self.db.create_table(
207
+ "tools", data=records, mode="overwrite"
208
+ )
209
+
210
+ logger.info(f"Saved {len(records)} tools to LanceDB with embeddings")
211
+
212
+ except Exception as e:
213
+ logger.error(f"Failed to save tools to LanceDB: {e}")
214
+ raise
215
+
216
+ def add_tool(self, tool: ToolMetadata) -> None:
217
+ """Add a tool to the vector store."""
218
+ self.tools[tool.name] = tool
219
+
220
+ def find_similar_tools(
221
+ self, query_embedding: List[float], top_k: int = 100
222
+ ) -> List[Tuple[str, float]]:
223
+ """Find similar tools using LanceDB vector search.
224
+
225
+ Args:
226
+ query_embedding: Embedding of the query (task prompt)
227
+ top_k: Number of top results to return
228
+
229
+ Returns:
230
+ List of (tool_name, similarity_score) tuples, sorted by relevance
231
+ """
232
+ if not query_embedding:
233
+ logger.warning("Empty query embedding, returning all tools")
234
+ return [(name, 0.0) for name in list(self.tools.keys())[:top_k]]
235
+
236
+ if self.table is None:
237
+ logger.warning("No tools indexed yet, returning all tools")
238
+ return [(name, 0.0) for name in list(self.tools.keys())[:top_k]]
239
+
240
+ try:
241
+ results = self.table.search(query_embedding).limit(top_k).to_list()
242
+
243
+ tool_scores = []
244
+ for result in results:
245
+ tool_name = result.get("name", "")
246
+ distance = result.get("_distance", 0.0)
247
+ similarity = 1.0 / (1.0 + distance)
248
+ tool_scores.append((tool_name, similarity))
249
+
250
+ logger.debug(f"LanceDB search found {len(tool_scores)} results")
251
+ return tool_scores
252
+
253
+ except Exception as e:
254
+ logger.error(f"LanceDB search failed: {e}")
255
+ return [(name, 0.0) for name in list(self.tools.keys())[:top_k]]
256
+
257
+ def get_all_tool_names(self) -> Set[str]:
258
+ """Get all tool names in the store."""
259
+ return set(self.tools.keys())
260
+
261
+
262
+ async def index_mcp_tools(
263
+ toolsets: List[Any],
264
+ vector_store: ToolVectorStore,
265
+ embedder: ToolEmbedder,
266
+ ) -> None:
267
+ """Index all tools from MCP toolsets into the vector store.
268
+
269
+ Args:
270
+ toolsets: List of MCP toolsets
271
+ vector_store: The vector store to populate
272
+ embedder: The embedder to use for creating embeddings
273
+ """
274
+ logger.info("Starting MCP tool indexing...")
275
+
276
+ total_tools = 0
277
+ for toolset in toolsets:
278
+ try:
279
+ tools_list = await toolset.list_tools() # type: ignore
280
+ logger.info(
281
+ f"Extracted {len(tools_list)} tools from {toolset.__class__.__name__}"
282
+ )
283
+
284
+ # Convert to ToolMetadata objects
285
+ tool_metadata_list = []
286
+ for mcp_tool in tools_list:
287
+ tool_metadata = ToolMetadata(
288
+ name=mcp_tool.name,
289
+ description=mcp_tool.description or "",
290
+ parameters=mcp_tool.inputSchema or {},
291
+ )
292
+ tool_metadata_list.append(tool_metadata)
293
+
294
+ # Embed tools in batches
295
+ embedded_tools = await embedder.embed_tools_batch(
296
+ tool_metadata_list, batch_size=32
297
+ )
298
+
299
+ # Store all tools
300
+ for tool in embedded_tools:
301
+ vector_store.add_tool(tool)
302
+ total_tools += 1
303
+
304
+ # Save to disk
305
+ vector_store._save_to_disk()
306
+
307
+ except Exception as e:
308
+ logger.error(f"Failed to extract tools from toolset: {e}")
309
+ import traceback
310
+
311
+ traceback.print_exc()
312
+
313
+ logger.info(f"Tool indexing complete: {total_tools} tools indexed")
314
+
315
+
316
+ async def index_openapi_tools(
317
+ spec: Dict[str, Any],
318
+ vector_store: ToolVectorStore,
319
+ embedder: ToolEmbedder,
320
+ ) -> None:
321
+ """Index tools from an OpenAPI spec into the vector store.
322
+
323
+ This replaces index_mcp_tools for the direct-API architecture.
324
+ Extracts tool names and descriptions from the OpenAPI spec's
325
+ operation IDs and summaries.
326
+
327
+ Args:
328
+ spec: Parsed OpenAPI spec JSON
329
+ vector_store: The vector store to populate
330
+ embedder: The embedder to use for creating embeddings
331
+ """
332
+ logger.info("Starting OpenAPI tool indexing...")
333
+
334
+ tool_metadata_list = []
335
+ paths = spec.get("paths", {})
336
+
337
+ for path, path_item in paths.items():
338
+ for method in ["get", "post", "put", "delete", "patch"]:
339
+ operation = path_item.get(method)
340
+ if not operation:
341
+ continue
342
+
343
+ operation_id = operation.get("operationId", "")
344
+ if not operation_id:
345
+ continue
346
+
347
+ tool_name = operation_id.strip("[]").replace(" ", "_")
348
+ description = operation.get("summary", "") or operation.get(
349
+ "description", ""
350
+ )
351
+ if not description:
352
+ description = f"{method.upper()} {path}"
353
+
354
+ # Build a simple representation for embedding
355
+ params = {}
356
+ for param in operation.get("parameters", []):
357
+ name = param.get("name", "")
358
+ if name:
359
+ params[name] = param.get("schema", {}).get("type", "string")
360
+
361
+ tool_metadata = ToolMetadata(
362
+ name=tool_name,
363
+ description=description,
364
+ parameters=params,
365
+ )
366
+ tool_metadata_list.append(tool_metadata)
367
+
368
+ logger.info(f"Found {len(tool_metadata_list)} tools in OpenAPI spec")
369
+
370
+ # Embed in batches
371
+ embedded_tools = await embedder.embed_tools_batch(tool_metadata_list, batch_size=32)
372
+
373
+ # Store
374
+ for tool in embedded_tools:
375
+ vector_store.add_tool(tool)
376
+
377
+ vector_store._save_to_disk()
378
+ logger.info(f"OpenAPI tool indexing complete: {len(embedded_tools)} tools indexed")
379
+
380
+
381
+ async def get_relevant_tool_names(
382
+ vector_store: ToolVectorStore,
383
+ embedder: ToolEmbedder,
384
+ task_prompt: str,
385
+ top_k: int = 100,
386
+ ) -> Set[str]:
387
+ """Get the set of relevant tool names for a task using RAG similarity search.
388
+
389
+ This is the main entry point for tool filtering. Returns a set of tool names
390
+ that can be used with pydantic-ai's FilteredToolset to filter the MCP toolset
391
+ while preserving full parameter schemas.
392
+
393
+ Args:
394
+ vector_store: The populated vector store
395
+ embedder: The embedder for embedding the task prompt
396
+ task_prompt: The task prompt to find relevant tools for
397
+ top_k: Number of top relevant tools to return
398
+
399
+ Returns:
400
+ Set of relevant tool names
401
+ """
402
+ try:
403
+ # Embed the task prompt
404
+ query_embedding = await embedder.embed_text(task_prompt)
405
+
406
+ # Find similar tools
407
+ similar_tool_scores = vector_store.find_similar_tools(
408
+ query_embedding, top_k=top_k
409
+ )
410
+
411
+ # Extract just the tool names
412
+ relevant_names = {tool_name for tool_name, score in similar_tool_scores}
413
+
414
+ logger.info(
415
+ f"RAG search: Found {len(relevant_names)} relevant tools "
416
+ f"(from {len(vector_store.tools)} total) for task: {task_prompt[:80]}..."
417
+ )
418
+
419
+ return relevant_names
420
+
421
+ except Exception as e:
422
+ logger.error(f"Error getting relevant tools: {e}")
423
+ # Fallback: return all tools
424
+ return vector_store.get_all_tool_names()
tools.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e2b20ca1d5cb953513be0ef9e8beab655d01d7ec922f8c6062382a245c55033
3
+ size 36390