Retrieval-augmented tool selector for semantic API matching
Project description
Retrieval Tool Selector
A retrieval-augmented tool selector that uses semantic embeddings to dynamically match user queries to relevant API functions and parameters. This library helps reduce LLM hallucination and improve function calling accuracy by:
- Tool Selection: Identifying the most relevant API functions using semantic similarity
- Parameter Filtering: Intelligently filtering enum parameters based on query context
- Zero-shot Retrieval: Working with no prior training using OpenAI's embedding models
Features
- 🔍 Semantic matching between natural language queries and API functions
- 🎯 Context-aware filtering of parameter enums
- ⚡ Precomputed embeddings for fast inference
- 🧠 Support for different embedding models (Ada, Cohere, text-embedding-3, etc.)
- 📊 Built-in debug outputs for similarity analysis
- 🔄 Compatible with OpenAI function calling paradigm
Installation
pip install retrieval-tool-selector
Quick Start
from retrieval_tool_selector import RetrievalAugmentedToolSelector
# Define your tools in OpenAI function-calling format
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather information",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit", "kelvin"]
},
"forecast_type": {
"type": "string",
"enum": ["current", "hourly", "daily", "weekly"]
}
},
"required": ["location"]
}
}
}
]
# Initialize selector
selector = RetrievalAugmentedToolSelector(
tools=tools,
api_key="your_openai_api_key",
base_url="https://api.openai.com/v1", # Can use Azure or other compatible endpoints
embedding_model="text-embedding-3-small"
)
# Select tools based on user query
query = "What's the hourly forecast for Tokyo?"
selected_tools = selector.select_tools(
query,
tool_threshold=0.65,
tool_top_k=1,
enum_threshold=0.5,
enum_top_k=2
)
print(selected_tools)
Key Concepts
Tool Selection Workflow
- Precomputation: During initialization, embeddings are generated for:
- All tool names and descriptions
- All enum parameter values
- Query Processing: For each user query:
- Compute query embedding
- Compare against tool embeddings to find matches
- Filter enum parameters based on semantic relevance
- Output: Returns tool definitions with filtered parameters ready for LLM consumption
Configuration Parameters
| Parameter | Default | Description |
|---|---|---|
tool_threshold |
0.7 | Minimum cosine similarity for tool selection |
tool_top_k |
1 | Maximum number of tools to return |
enum_threshold |
0.6 | Minimum cosine similarity for enum inclusion |
enum_top_k |
3 | Maximum number of enum values to keep per parameter |
Supported Embedding Models
You can use any embedding model supported by your OpenAI-compatible API:
text-embedding-ada-002(default)text-embedding-3-smalltext-embedding-3-large- Or any custom models supported by your endpoint
Advanced Usage
Integrating with OpenAI Chat Completions
from openai import OpenAI
# Initialize tool selector
selector = RetrievalAugmentedToolSelector(tools, api_key, base_url)
# Process user query
query = "Show me the weekly weather forecast for Paris in Celsius"
selected_tools = selector.select_tools(query)
# Call OpenAI with filtered tools
client = OpenAI(api_key=api_key, base_url=base_url)
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": query}],
tools=selected_tools,
tool_choice="auto"
)
Handling Enum Value Mismatches
If your enum values use special formats but need semantic matching:
# During tool definition, add semantic equivalents:
{
"type": "string",
"enum": ["USD", "EUR", "JPY"],
"enum_semantic": ["US Dollar", "Euro", "Japanese Yen"]
}
Then modify the tool preprocessing step to use semantic equivalents for embedding generation.
Debugging Similarity Scores
The library provides debug outputs:
Tool similarity analysis:
Embedding model: text-embedding-3-large
- get_weather: 0.8723
- get_stock: 0.5121
Enum filtering results (threshold=0.5, top_k=2):
Original: ['current', 'hourly', 'daily', 'weekly']
Filtered: ['hourly', 'daily']
Use Cases
- Function Calling: Improve tool selection accuracy for LLMs
- API Gateways: Automatically route requests to appropriate services
- Conversational Interfaces: Parse natural language into precise API calls
- Data APIs: Handle enums with many possible values (e.g. country codes, product types)
- RAG Systems: As a component in larger retrieval-augmented generation pipelines
Best Practices
- Start with
text-embedding-3-smallfor cost efficiency - Adjust thresholds based on your tool diversity
- Use higher top_k for parameters with many possible values
- Include detailed tool descriptions for better matching
- Test with diverse query phrasings
Limitations
- Requires OpenAI API calls for embedding generation
- Primarily designed for text-based tools (though could extend to multimodal)
- Enum filtering works best when values have clear semantic meaning
Contributing
Contributions are welcome! Please submit pull requests or open issues on GitHub.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Developed by SoulJoy(卓寿杰)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file retrieval_tool_selector-0.1.0.tar.gz.
File metadata
- Download URL: retrieval_tool_selector-0.1.0.tar.gz
- Upload date:
- Size: 6.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8e8a9c30b987baec2767162c0c13b80047c0b96019806cf66b2e034115bcff90
|
|
| MD5 |
9d020d0db69b2c2cb5656acfbdd23f17
|
|
| BLAKE2b-256 |
4f042c6ffde0ca2ddad6be31937c8e781fb076a66fbf6013ed23b3ff3e50e5fc
|
File details
Details for the file retrieval_tool_selector-0.1.0-py3-none-any.whl.
File metadata
- Download URL: retrieval_tool_selector-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
40aa33dcb8933051c64faa209a873f9d1370b6e903dda140dccbc448590eebdf
|
|
| MD5 |
76d9426ad3677cb9065509f2ea5ea1ad
|
|
| BLAKE2b-256 |
5d1eb7124b069c5de931e9905f1414e01e919bb8d74e4d5d8ab6b71b98aed3c2
|