This document covers common issues, debugging techniques, and best practices for the SignalWire Agents SDK search system. For an overview of search concepts, see search_overview.md. For indexing configuration, see search_indexing.md.
Symptoms:
The search returns empty results for queries that should match content in the index.
Query: "how to authenticate"
Results: []Diagnosis:
-
Verify the index exists and has content:
ls -lh knowledge.swsearch sw-search validate ./knowledge.swsearch
-
Test the query directly via CLI:
sw-search search ./knowledge.swsearch "how to authenticate" --verboseExamine the similarity scores in verbose output.
-
Check the similarity threshold:
{
"similarity_threshold": 0.7 # Very strict -- may filter out valid results
}Common Causes and Solutions:
-
Similarity threshold too strict: Lower the threshold to allow weaker but valid matches:
# Problem {"similarity_threshold": 0.7} # Only near-perfect matches # Solution {"similarity_threshold": 0.4} # More permissive
-
Content does not exist in the index: Verify and add missing content:
sw-search search ./knowledge.swsearch "authentication" --verbose --count 10 # If no content about authentication exists, rebuild with additional sources sw-search ./auth-docs --output updated.swsearch
-
Query phrasing does not match content semantically: Try synonym variations:
# "how to authenticate" may not match content phrased as "bearer token usage" sw-search search ./knowledge.swsearch "bearer token" --verbose
-
Model mismatch between index build and query: The embedding model used at query time must match the model used when building the index:
# Built with base model # sw-search ./docs --model base --output docs.swsearch # Query must also use base model {"model_name": "base"} # Must match the build model
Fallback strategy: Try progressively lower thresholds:
def search_with_fallback(self, query):
"""Try multiple thresholds"""
for threshold in [0.5, 0.4, 0.3]:
results = self.search(query, threshold=threshold)
if results:
return results
return []Symptoms:
Results are returned but do not match the query intent.
Query: "Python authentication examples"
Results:
1. "Ruby authentication guide" (similarity: 0.65)
2. "General API overview" (similarity: 0.58)
3. "Installation instructions" (similarity: 0.52)Diagnosis:
-
Check similarity scores:
sw-search search ./knowledge.swsearch "Python authentication examples" --verboseScores below 0.5 indicate weak matches.
-
Examine the returned content:
sw-search search ./knowledge.swsearch "Python authentication examples" --verbose --count 10 -
Check chunking quality by reading the index directly. A
.swsearchfile is a SQLite database, so its chunks are queryable withsqlite3:sqlite3 ./knowledge.swsearch "SELECT filename, section, content FROM chunks" # Review chunk boundaries -- are they mixing topics?
Common Causes and Solutions:
-
Threshold too permissive: Raise the threshold to reject weak matches:
# Problem {"similarity_threshold": 0.2} # Accepts weak matches # Solution {"similarity_threshold": 0.4}
-
Poor chunking strategy: Use a strategy that matches your content type:
# Problem: sentence strategy splits code blocks sw-search ./docs --chunking-strategy sentence # Solution: markdown strategy preserves code blocks sw-search ./docs --chunking-strategy markdown
See search_indexing.md for details on chunking strategies.
-
Missing metadata and tags: Add tags during indexing to improve hybrid scoring:
sw-search ./docs --tags python,authentication,examples --output docs.swsearch
-
Content lacks specificity: If generic content dominates, add more specific documents covering the exact topics users ask about.
Tag-based filtering:
self.add_skill("native_vector_search", {
"tool_name": "search_python_examples",
"description": "Search for Python code examples",
"index_file": "./docs.swsearch",
"tags": ["python", "code"],
"similarity_threshold": 0.4
})Symptoms:
The best result appears lower in the list instead of first.
Query: "voice configuration"
Results:
1. "General configuration overview" (similarity: 0.72)
2. "Database configuration" (similarity: 0.68)
3. "Perfect voice config guide" (similarity: 0.85) # Should be #1Diagnosis:
-
Check hybrid scoring via verbose output:
sw-search search ./knowledge.swsearch "voice configuration" --verboseDetermine whether the result with higher vector similarity has a lower hybrid score.
-
Examine metadata on each result:
sqlite3 ./knowledge.swsearch "SELECT filename, section, tags, metadata FROM chunks" # Check if the best result lacks metadata that other results have
Common Causes and Solutions:
-
Missing metadata on the best result: Results with tags receive keyword boosts in hybrid scoring. Re-export the source documents to JSON, add tags, and rebuild:
sw-search ./docs --output-format json --output chunks.json # Edit chunks.json to add metadata: # {"content": "Voice configuration guide...", "metadata": {"tags": ["voice", "configuration", "guide"]}} sw-search ./chunks.json --chunking-strategy json --output fixed.swsearch
-
Keyword matches boosting wrong results: A result containing both query keywords (e.g., "Configuration for voice, database, and API...") may receive a keyword boost even though it is less relevant than a focused document.
-
Increase result count: Returning more results allows the LLM to select the most relevant one:
{"count": 5}- Custom reranking via formatter callback:
def _format_with_reranking(self, response, agent, query, results, **kwargs):
"""Rerank based on custom logic"""
if "example" in query.lower():
results.sort(key=lambda r: r.get('metadata', {}).get('has_code', False), reverse=True)
return self._build_response(results)Symptoms:
Search results appear cut off mid-sentence or are incomplete.
Diagnosis:
- Check the content length budget:
{"max_content_length": 16384} # May be too small for the number of results-
Examine individual chunk sizes:
sqlite3 ./knowledge.swsearch "SELECT filename, LENGTH(content) FROM chunks ORDER BY LENGTH(content) DESC LIMIT 10" # Check for very long chunks
-
Check result count relative to budget:
{
"count": 10,
"max_content_length": 16384 # Only ~1.6KB per result
}Common Causes and Solutions:
- max_content_length too low: Increase the budget:
{"max_content_length": 32768} # 32KB (default)-
Individual chunks too long: Rechunk with a strategy that produces smaller pieces, for example by lowering the sentence count per chunk:
sw-search ./docs \ --chunking-strategy sentence \ --max-sentences-per-chunk 3 \ --output docs_small_chunks.swsearch
-
Too many results for the budget: Reduce the result count so each result gets more space:
{
"count": 3,
"max_content_length": 16384
}Symptoms:
The agent does not invoke the search function even when the user asks questions that should trigger a search.
Diagnosis:
-
Verify the function is registered:
swaig-test agent.py --list-tools # Should list search_docs or the configured tool_name -
Test the function directly:
swaig-test agent.py --exec search_docs --query "test" -
Check the function description. A vague description makes it less likely the LLM will invoke it.
Common Causes and Solutions:
-
Vague function description: Provide a specific, detailed description:
# Problem {"description": "Search docs"} # Solution self.add_skill("native_vector_search", { "tool_name": "search_product_docs", "description": ( "Search comprehensive product documentation. " "Use this for ANY question about: features, configuration, " "API usage, troubleshooting, code examples, or technical details. " "This is your primary source of truth." ), "index_file": "./docs.swsearch" })
-
No prompt instructions telling the agent to search: Add explicit guidance:
self.prompt_add_section(
"Search First Policy",
bullets=[
"Before answering ANY technical question, search the knowledge base",
"Use search_product_docs for product-related questions",
"Never guess or use general knowledge - always search first",
"If search returns no results, tell user you don't have that information"
]
)- LLM believes it already knows the answer: Strengthen the prompt:
"ALWAYS search before answering, even if you think you know the answer"See search_integration.md for full details on agent configuration.
Symptoms:
Error loading model: sentence-transformers/all-MiniLM-L6-v2
Diagnosis:
-
Check that search dependencies are installed:
pip list | grep sentence-transformers -
Check the model cache:
ls ~/.cache/huggingface/hub/ -
Check network access to Hugging Face:
curl -I https://huggingface.co
Common Causes and Solutions:
-
Search dependencies not installed: Install the appropriate search extras:
# Base install does not include search pip install signalwire-sdk[search] -
Network issues preventing model download on first run: Pre-download the model:
python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')" -
Insufficient disk space: Models require approximately 400MB:
df -h ~/.cache # Clean if needed rm -rf ~/.cache/huggingface/hub/
Pre-download in Docker builds:
RUN pip install signalwire-sdk[search] && \
python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"Offline mode: If the model is already cached:
export TRANSFORMERS_OFFLINE=1Query-only mode: If you only need to query existing indexes and do not need the full model:
pip install signalwire-sdk[search-queryonly]Symptoms:
When running sw-search with embedding generation, the process crashes with an "Illegal instruction" error.
Root Cause:
This occurs when PyTorch was compiled with newer CPU instruction sets (such as AVX2 or AVX-512) that are not supported by the host CPU. This is common on older server hardware or certain virtualized environments.
Diagnosis:
-
Check CPU capabilities:
cat /proc/cpuinfo | grep -E "(model name|flags)" | head -5
Look for
avx2andavx512fin the flags. If absent, the CPU does not support these instruction sets. -
Check PyTorch version:
python -c "import torch; print('PyTorch version:', torch.__version__)" -
Test model loading to reproduce the error:
python -c "from sentence_transformers import SentenceTransformer; model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')"
Solution:
PyTorch chooses many of its CPU kernels at runtime, based on what the processor supports. First, force the most basic kernels with ATEN_CPU_CAPABILITY and run the build again:
ATEN_CPU_CAPABILITY=default sw-search ./docs --output index.swsearchIf it still crashes, the installed binary itself uses instructions the CPU lacks. Install a PyTorch build that supports this CPU and operating system, using the options on the PyTorch installation page. The CPU-only wheels are a common choice, but they don't support every older processor:
pip uninstall torch
pip install torch --index-url https://download.pytorch.org/whl/cpuAlternative:
Run sw-search on hardware that supports AVX2 and AVX-512, or inside a container built for the host's actual CPU capabilities.
Symptoms:
Error: could not connect to PostgreSQL server
Or the extension itself may be missing:
vector type not found in the database
Diagnosis:
-
Test the connection directly:
psql "$PGVECTOR_CONNECTION" -
Check the connection string format:
# Required format: postgresql://user:pass@host:port/db echo "$PGVECTOR_CONNECTION"
-
Check whether the pgvector extension is installed:
SELECT * FROM pg_extension WHERE extname = 'vector';
-
Check whether PostgreSQL is running:
sudo systemctl status postgresql sudo systemctl start postgresql # Start if needed
Common Causes and Solutions:
-
Incomplete connection string:
# Problem: missing components "postgresql://localhost/db" # Solution: include all components "postgresql://user:pass@localhost:5432/db"
-
pgvector extension not installed:
# Install the extension package (PostgreSQL 16 example) sudo apt-get install postgresql-16-pgvectorThen enable it inside the target database:
-- Enable in the database (as superuser) CREATE EXTENSION vector; -- Verify \dx
Alternatively, use the Docker image with pgvector pre-installed:
docker run -d \ --name postgres-pgvector \ -e POSTGRES_USER=signalwire \ -e POSTGRES_PASSWORD=signalwire123 \ -e POSTGRES_DB=knowledge \ -p 5432:5432 \ pgvector/pgvector:pg16
-
Database does not exist:
createdb -U postgres knowledge
-
Network or firewall blocking the connection:
telnet postgres-host 5432
-
Authentication failure: Verify credentials and check
pg_hba.conffor allowed connection methods. -
Docker container cannot reach host PostgreSQL:
# Linux: use host networking docker run --network host ... # macOS/Windows: use host.docker.internal # postgresql://user:pass@host.docker.internal:5432/knowledge # Or use a Docker network docker network create myapp docker run -d --name postgres --network myapp pgvector/pgvector:pg16 docker run --network myapp -e DB_HOST=postgres ...
Validate connection string programmatically:
import os
conn = os.getenv("PGVECTOR_CONNECTION")
assert conn.startswith("postgresql://"), "Invalid connection string"
assert "@" in conn, "Missing credentials"
assert ":" in conn.split("@")[1], "Missing port"Test connection:
from sqlalchemy import create_engine
engine = create_engine(os.getenv("PGVECTOR_CONNECTION"))
with engine.connect() as conn:
result = conn.execute("SELECT 1")
print("Connected successfully")See search_deployment.md for full pgvector deployment guidance.
Symptoms:
Search queries take much longer than expected.
Diagnosis:
-
Profile query time:
time sw-search search ./knowledge.swsearch "test query"
-
Check index size:
ls -lh knowledge.swsearch # For pgvector # SELECT count(*) FROM knowledge_chunks;
-
Check which model is being used:
{"model_name": "base"} # base is slower than miniCommon Causes and Solutions:
- Using the base model: Switch to the mini model for faster queries with minimal quality loss:
{"model_name": "mini"}-
No vector index on pgvector: Create an IVFFlat index:
-- For small datasets (< 100k rows) CREATE INDEX ON knowledge_chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); -- For larger datasets CREATE INDEX ON knowledge_chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 1000);
-
Too many results requested: Reduce the result count:
{"count": 3} # Faster than requesting 10+- Remote pgvector with high network latency: For single-agent deployments, consider using a local SQLite index instead:
{"index_file": "./local.swsearch"}-
PostgreSQL not tuned for vector operations:
SET work_mem = '256MB'; -- Or globally: ALTER SYSTEM SET work_mem = '256MB';
-
Analyze query plans to identify bottlenecks:
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM your_collection ORDER BY embedding <=> '[...]'::vector LIMIT 5;
Connection pool exhaustion (multi-agent deployments): use pgbouncer for connection pooling:
# /etc/pgbouncer/pgbouncer.ini
[databases]
knowledge = host=localhost port=5432 dbname=knowledge
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25Point agents at pgbouncer instead of PostgreSQL directly:
# Connect through pgbouncer (default port 6432)
# postgresql://user:pass@localhost:6432/knowledgeEnable verbose logging to see detailed search internals:
import os
os.environ['SIGNALWIRE_LOG_LEVEL'] = 'DEBUG'This exposes similarity scores, hybrid scoring details, and timing information in the agent logs.
A .swsearch file is a SQLite database, so query it directly to inspect what was indexed:
sqlite3 ./knowledge.swsearch "SELECT filename, section, content FROM chunks"Review the output to verify:
- Chunk boundaries are sensible and do not split related content
- Metadata and tags are present on chunks that need them
- Chunk sizes are appropriate (not too large, not too small)
Verify that the embedding model loads correctly and produces vectors:
python -c "from sentence_transformers import SentenceTransformer; m = SentenceTransformer('all-MiniLM-L6-v2'); print(m.encode('test').shape)"If this fails, see the earlier Model Loading Errors and "Illegal Instruction" Error sections.
Use verbose CLI output to analyze similarity scores:
sw-search search ./knowledge.swsearch "your query" --verbose --count 10Interpret the scores:
- 0.7 and above: Strong semantic match
- 0.5 to 0.7: Moderate match, usually relevant
- 0.3 to 0.5: Weak match, may or may not be relevant
- Below 0.3: Poor match, likely irrelevant
A typical --similarity-threshold of 0.4 provides a good balance between recall and precision.
The --verbose flag on sw-search search provides:
- Similarity scores for each result
- The NLP backend and embedding model used for the query
- How many chunks and files the loaded index contains
For example:
sw-search search ./knowledge.swsearch "query" --verboseWhen troubleshooting search issues, work through this checklist in order:
- Verify the index file exists and passes validation (
sw-search validate) - Test the query with the CLI tool (
sw-search search --verbose) - Check the distance threshold (0.4 is a typical starting value)
- Verify the model matches between build and query time
- Examine chunk quality by exporting and reviewing the index
- Check that the function description is specific and clear
- Verify prompt instructions tell the agent when to use search
- Monitor search latency
- Check for missing Python dependencies
- Test pgvector connection if using that backend
- Review verbose output for similarity scores
- Verify metadata and tags are present on indexed chunks
Follow these practices when building an index:
- Choose the right chunking strategy for your content type:
- Technical docs with code:
markdown - FAQ/support content:
qa - General articles/blogs:
paragraph - Academic papers:
semantic - Mixed content: start with
markdown - Custom needs: JSON workflow for manual curation
- Technical docs with code:
- Add tags during indexing to improve hybrid search scoring:
sw-search ./docs --tags documentation,api,code --output docs.swsearch
- Use the mini model for most use cases. Only upgrade to base or large if quality is insufficient.
- Validate indexes after building to catch issues early:
sw-search validate ./knowledge.swsearch
- Test with representative queries before deploying:
sw-search search ./knowledge.swsearch "expected user question" --verbose
Follow these practices when configuring the skill on an agent:
- Write specific, detailed function descriptions: The LLM uses the description to decide when to call the search function. Generic descriptions like "Search docs" lead to the function not being invoked.
- Add explicit prompt instructions telling the agent to search before answering:
self.prompt_add_section("Instructions", bullets=[
"Always search before answering technical questions",
"Base answers on search results, not general knowledge",
"If no results, say you don't have that information"
])- Match the model name between the index build and the agent configuration.
- Set a balanced distance threshold: Start with 0.4 and adjust based on testing.
- Tune result count and content length together to avoid truncation:
{
"count": 3,
"max_content_length": 32768
}Follow these practices when deploying to production:
- Use
search-queryonlyin production to save approximately 400MB of dependencies:pip install signalwire-sdk[search-queryonly]
- Use
search-fullfor building indexes in your CI/CD pipeline or development environment. - Switch to pgvector for multi-agent deployments: SQLite is appropriate for single-agent setups; pgvector handles concurrent access and shared knowledge bases.
- Pre-download models in Docker builds to avoid first-run delays:
RUN pip install signalwire-sdk[search] && \ python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"
- Create pgvector indexes on the embedding column for large datasets:
CREATE INDEX ON knowledge_chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
- Use connection pooling (pgbouncer) for multi-agent deployments sharing a pgvector database.
- Monitor search performance: Track query latency, result counts, and no-result queries to identify content gaps and performance regressions.
-
Not telling the agent to search: Adding the search skill without prompt instructions means the LLM may never invoke it. Always pair
add_skill()with prompt instructions. -
Using the wrong chunking strategy: Sentence-based chunking splits code blocks and destroys their meaning. Use the markdown strategy for technical documentation.
-
Setting the distance threshold too strictly or too loosely:
- Too strict (0.7): returns no results for valid queries
- Too permissive (0.2): returns irrelevant results
- Recommended starting point: 0.4
-
Mismatched models: Building the index with one model and querying with a different model produces meaningless similarity scores. Always match the model.
-
Ignoring metadata: Indexes built without tags lose the keyword boosting benefits of hybrid search. Add relevant tags during indexing.
-
Deploying without testing: Always test with the CLI and
swaig-testbefore deploying:sw-search search ./knowledge.swsearch "test queries" swaig-test agent.py --exec search_docs --query "test"
CLI reference:
sw-search --help
sw-search search --help
sw-search validate --helpEnable debug logging:
import os
os.environ['SIGNALWIRE_LOG_LEVEL'] = 'DEBUG'Test with CLI:
sw-search search ./knowledge.swsearch "query" --verboseInspect index contents directly:
sqlite3 ./knowledge.swsearch "SELECT filename, section, content FROM chunks"GitHub Issues: https://github.com/signalwire/signalwire-python/issues
GitHub Discussions: https://github.com/signalwire/signalwire-python/discussions