> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kubiya.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshooting

> Common issues and solutions when using the Kubiya SDK

<Info>
  This guide covers common issues you may encounter when using the Kubiya SDK and their solutions.
</Info>

## Authentication Issues

### Invalid API Key

**Problem**: Getting authentication errors even with correct API key.

**Symptoms**:

```
AuthenticationError: Invalid API key
```

**Solutions**:

1. Verify the API key is correct and not expired
2. Check the key hasn't been revoked in the dashboard
3. Ensure no extra whitespace in the key value
4. Verify you're using the correct organization's key

```python theme={null}
# Check your API key
import os
from kubiya import ControlPlaneClient

api_key = os.getenv("KUBIYA_API_KEY")
print(f"API Key length: {len(api_key) if api_key else 0}")
print(f"API Key starts with: {api_key[:10] if api_key else 'None'}...")

# Test connection
try:
    client = ControlPlaneClient(api_key=api_key)
    client.datasets.list_datasets()
    print("✅ Authentication successful")
except Exception as e:
    print(f"❌ Authentication failed: {e}")
```

### Environment Variable Not Set

**Problem**: API key environment variable not being read.

**Solutions**:

1. Verify environment variable name is exactly `KUBIYA_API_KEY`
2. Restart your terminal/IDE after setting the variable
3. Use `.env` file with `python-dotenv`:

```python theme={null}
from dotenv import load_dotenv
load_dotenv()  # Load from .env file

from kubiya import ControlPlaneClient
client = ControlPlaneClient()  # Will use KUBIYA_API_KEY
```

## Connection Issues

### Connection Timeout

**Problem**: Requests timing out.

**Symptoms**:

```
TimeoutError: Request timed out after 300 seconds
```

**Solutions**:

1. Increase timeout for long-running operations:

```python theme={null}
from kubiya import ControlPlaneClient

# Increase timeout to 10 minutes
client = ControlPlaneClient(
    api_key="your-api-key",
    timeout=600
)
```

2. Reduce complexity of operations:

```python theme={null}
# Instead of max_turns=20
result = client.graph.intelligent_search(
    keywords="query",
    max_turns=5  # Reduce complexity
)
```

### Connection Refused

**Problem**: Unable to connect to Control Plane API.

**Solutions**:

1. Check your network connectivity
2. Verify firewall settings allow HTTPS to `control-plane.kubiya.ai`
3. Check if you're behind a proxy:

```python theme={null}
import os
from kubiya import ControlPlaneClient

# Configure proxy if needed
os.environ['HTTPS_PROXY'] = 'http://proxy.company.com:8080'

client = ControlPlaneClient(api_key="your-api-key")
```

## Data Issues

### Empty Results

**Problem**: Search or recall operations return no results.

**Solutions**:

1. Verify data exists in the dataset:

```python theme={null}
# Check dataset status
status = client.datasets.get_dataset_status(dataset_id="your-dataset")
print(f"Status: {status['status']}")
print(f"Progress: {status.get('progress', 0)}%")
```

2. Wait for data processing to complete:

```python theme={null}
import time

while True:
    status = client.datasets.get_dataset_status(dataset_id="dataset-id")
    if status['status'] == 'ready':
        break
    time.sleep(5)
```

3. Broaden your search query:

```python theme={null}
# Too specific - may return nothing
result = client.graph.semantic_search(
    query="exact phrase that might not exist",
    limit=10
)

# Broader query
result = client.graph.semantic_search(
    query="general concept or keywords",
    limit=10
)
```

### Low Relevance Scores

**Problem**: Semantic search returns results with low similarity scores.

**Solutions**:

1. Filter results by minimum score:

```python theme={null}
results = client.graph.semantic_search(query="your query", limit=50)

# Only use high-confidence results
relevant = [r for r in results if r['similarity_score'] > 0.7]
```

2. Use intelligent search instead for complex queries:

```python theme={null}
# Better for complex questions
result = client.graph.intelligent_search(
    keywords="complex multi-part question"
)
```

## Ingestion Issues

### Duplicate Node Errors

**Problem**: Ingestion fails with duplicate node errors.

**Solution**: Use appropriate duplicate handling:

```python theme={null}
# Skip duplicates
client.ingestion.ingest_nodes_batch(
    nodes=nodes,
    duplicate_handling="skip"
)

# Or update existing nodes
client.ingestion.ingest_nodes_batch(
    nodes=nodes,
    duplicate_handling="update"
)
```

### Batch Import Failures

**Problem**: Batch ingestion fails partially.

**Solutions**:

1. Use non-transactional mode:

```python theme={null}
result = client.ingestion.ingest_nodes_batch(
    nodes=nodes,
    transactional=False  # Don't rollback all on single failure
)

# Check results
print(f"Success: {result['summary']['success']}")
print(f"Failed: {result['summary']['failed']}")

if result.get('errors'):
    for error in result['errors']:
        print(f"Error: {error}")
```

2. Reduce batch size:

```python theme={null}
def import_in_chunks(nodes, chunk_size=100):
    """Import large datasets in smaller chunks."""
    for i in range(0, len(nodes), chunk_size):
        chunk = nodes[i:i + chunk_size]
        result = client.ingestion.ingest_nodes_batch(nodes=chunk)
        print(f"Chunk {i//chunk_size + 1}: {result['summary']['success']} succeeded")
```

## Performance Issues

### Slow Responses

**Problem**: API calls taking longer than expected.

**Solutions**:

1. Use batch operations:

```python theme={null}
# ❌ Slow - individual calls
for node in nodes:
    client.ingestion.ingest_node(**node)

# ✅ Fast - batch call
client.ingestion.ingest_nodes_batch(nodes=nodes)
```

2. Use async operations for large data:

```python theme={null}
# Use async for large content
job = client.graph.store_memory_async(
    dataset_id="dataset-id",
    context=large_content
)
# Continue with other work
```

3. Implement caching:

```python theme={null}
from functools import lru_cache

@lru_cache(maxsize=100)
def get_models():
    return client.models.list()

# Subsequent calls use cache
models = get_models()
```

### High Memory Usage

**Problem**: Application using too much memory.

**Solutions**:

1. Process data in chunks:

```python theme={null}
# Instead of loading all at once
skip = 0
while True:
    batch = client.graph.list_memories(skip=skip, limit=100)
    if not batch:
        break

    process_batch(batch)  # Process and discard
    skip += 100
```

2. Clear sensitive data from memory:

```python theme={null}
import gc

secret = client.secrets.get_value(name="api-token")
# Use secret
token = secret['value']
# ... use token ...

# Clear from memory
token = None
secret = None
gc.collect()
```

## Import Errors

### Module Not Found

**Problem**: `ModuleNotFoundError: No module named 'kubiya'`

**Solutions**:

1. Verify SDK is installed:

```bash theme={null}
pip list | grep kubiya
```

2. Install SDK:

```bash theme={null}
pip install kubiya
# or
pip install kubiya-sdk
```

3. Check you're using the correct Python environment:

```bash theme={null}
which python
python --version
```

### Import Errors for Exceptions

**Problem**: Cannot import exception classes.

**Solution**: Use correct import paths:

```python theme={null}
# Core exceptions
from kubiya.core.exceptions import (
    APIError as KubiyaAPIError,
    AuthenticationError as KubiyaAuthenticationError,
    TimeoutError as KubiyaTimeoutError
)

# Resource exceptions
from kubiya.resources.exceptions import (
    GraphError,
    ModelError,
    AgentError
)
```

## SDK Version Issues

### Deprecated Methods

**Problem**: Methods or parameters not working as documented.

**Solutions**:

1. Check SDK version:

```python theme={null}
import kubiya
print(f"Kubiya SDK version: {kubiya.__version__}")
```

2. Upgrade to latest version:

```bash theme={null}
pip install --upgrade kubiya
```

3. Check breaking changes in release notes

## Getting Help

If you're still experiencing issues:

1. **Check SDK Version**: Ensure you're using the latest version
2. **Review Documentation**: Check the specific service documentation
3. **Enable Debug Logging**:

```python theme={null}
import logging
logging.basicConfig(level=logging.DEBUG)
```

4. **Check Status**: Verify Control Plane API status
5. **Contact Support**: Reach out to Kubiya support with:
   * SDK version
   * Error message
   * Minimal code to reproduce
   * Expected vs actual behavior

## Common Error Messages

| Error Message         | Likely Cause                     | Solution                              |
| --------------------- | -------------------------------- | ------------------------------------- |
| "Invalid API key"     | Wrong or expired key             | Verify API key in dashboard           |
| "Dataset not found"   | Dataset doesn't exist            | Create dataset first                  |
| "Session expired"     | Search session timed out         | Create new session                    |
| "Rate limit exceeded" | Too many requests                | Implement backoff and retry           |
| "Validation error"    | Invalid parameters               | Check parameter types and values      |
| "Connection timeout"  | Network issues or slow operation | Increase timeout or reduce complexity |
| "Node not found"      | Referenced node doesn't exist    | Verify node ID or create node first   |

## Next Steps

<CardGroup cols={2}>
  <Card title="Error Handling" icon="triangle-exclamation" href="/sdk/error-handling">
    Learn about exception handling
  </Card>

  <Card title="Best Practices" icon="star" href="/sdk/best-practices">
    SDK best practices guide
  </Card>

  <Card title="Examples" icon="code-branch" href="/sdk/examples">
    Working code examples
  </Card>

  <Card title="API Reference" icon="book" href="/sdk/api-reference">
    Complete API documentation
  </Card>
</CardGroup>
