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

# Troubleshooting

> Common issues and solutions when using the Noxus Client SDK

## Common Issues

### Authentication Problems

<AccordionGroup>
  <Accordion title="401 Unauthorized Error" icon="key">
    **Problem**: Getting `401 Unauthorized` when making API calls.

    **Causes**:

    * Invalid API key
    * Expired API key
    * API key not properly set

    **Solutions**:

    ```python theme={null}
    # Check if API key is set
    import os
    api_key = os.getenv("NOXUS_API_KEY")
    if not api_key:
        print("API key not found in environment variables")

    # Verify API key format
    if api_key and not api_key.startswith("noxus_"):
        print("API key format appears incorrect")

    # Test authentication
    try:
        client = Client(api_key=api_key)
        models = client.get_models()  # Simple test call
        print("✅ Authentication successful")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 401:
            print("❌ Invalid API key")
    ```
  </Accordion>

  <Accordion title="403 Forbidden Error" icon="shield">
    **Problem**: Getting `403 Forbidden` when accessing certain resources.

    **Causes**:

    * Insufficient permissions for your workspace role
    * Trying to access resources from another workspace
    * API key doesn't have required permissions

    **Solutions**:

    * Contact your workspace administrator
    * Verify you're using the correct workspace API key
    * Check your role permissions in the Noxus dashboard

    ```python theme={null}
    # Check your user permissions
    try:
        client = Client(api_key="your_key")
        if client.admin.enabled:
            print("✅ You have admin permissions")
        else:
            print("ℹ️ Limited permissions - some features may not be available")
    except Exception as e:
        print(f"❌ Error checking permissions: {e}")
    ```
  </Accordion>
</AccordionGroup>

### Connection Issues

<AccordionGroup>
  <Accordion title="Network Timeouts" icon="clock-4">
    **Problem**: Requests timing out or taking too long.

    **Solutions**:

    ```python theme={null}
    import httpx
    from noxus_sdk.client import Client

    # For long-running operations, increase timeout
    try:
        client = Client(api_key="your_key")
        # Use async for better timeout handling
        import asyncio
        
        async def with_timeout():
            try:
                result = await asyncio.wait_for(
                    client.workflows.alist(),
                    timeout=60.0  # 60 second timeout
                )
                return result
            except asyncio.TimeoutError:
                print("Operation timed out")
                return None
        
        workflows = asyncio.run(with_timeout())
    except httpx.RequestError as e:
        print(f"Network error: {e}")
    ```
  </Accordion>

  <Accordion title="Connection Refused" icon="wifi-off">
    **Problem**: Cannot connect to the Noxus backend.

    **Causes**:

    * Network connectivity issues
    * Firewall blocking requests
    * Incorrect backend URL

    **Solutions**:

    ```python theme={null}
    import requests

    # Test basic connectivity
    def test_connectivity():
        try:
            response = requests.get("https://backend.noxus.ai/health", timeout=10)
            if response.status_code == 200:
                print("✅ Backend is reachable")
            else:
                print(f"⚠️ Backend returned status: {response.status_code}")
        except requests.exceptions.ConnectionError:
            print("❌ Cannot connect to backend")
        except requests.exceptions.Timeout:
            print("❌ Connection timed out")

    test_connectivity()

    # Check if using custom backend URL
    backend_url = os.getenv("NOXUS_BACKEND_URL")
    if backend_url:
        print(f"Using custom backend: {backend_url}")
    ```
  </Accordion>
</AccordionGroup>

### Workflow Issues

<AccordionGroup>
  <Accordion title="Workflow Creation Fails" icon="triangle-alert">
    **Problem**: Cannot create or save workflows.

    **Common Issues**:

    ```python theme={null}
    from noxus_sdk.workflows import WorkflowDefinition

    # Issue 1: Missing required node configurations
    def check_node_config(workflow_def):
        for node in workflow_def.nodes:
            if node.type == "TextGenerationNode":
                if not hasattr(node.config, 'template') or not node.config.template:
                    print(f"❌ Node '{node.label}' missing template")
                if not hasattr(node.config, 'model') or not node.config.model:
                    print(f"❌ Node '{node.label}' missing model")

    # Issue 2: Invalid connections
    def check_connections(workflow_def):
        node_ids = {node.id for node in workflow_def.nodes}
        for edge in workflow_def.edges:
            if edge.source_node_id not in node_ids:
                print(f"❌ Invalid source node: {edge.source_node_id}")
            if edge.target_node_id not in node_ids:
                print(f"❌ Invalid target node: {edge.target_node_id}")

    # Issue 3: Orphaned nodes
    def check_orphaned_nodes(workflow_def):
        connected_nodes = set()
        for edge in workflow_def.edges:
            connected_nodes.add(edge.source_node_id)
            connected_nodes.add(edge.target_node_id)
        
        orphaned = [node for node in workflow_def.nodes if node.id not in connected_nodes]
        if orphaned:
            print(f"⚠️ Orphaned nodes: {[n.label for n in orphaned]}")
    ```
  </Accordion>

  <Accordion title="Workflow Execution Fails" icon="play-circle">
    **Problem**: Workflows fail during execution.

    **Debugging Steps**:

    ```python theme={null}
    def debug_workflow_execution(workflow, input_data):
        try:
            # Start workflow
            run = workflow.run(body=input_data)
            print(f"Started run: {run.id}")
            
            # Monitor execution
            while run.status not in ["completed", "failed", "cancelled"]:
                print(f"Status: {run.status}")
                time.sleep(2)
                run = run.refresh()
            
            if run.status == "completed":
                print(f"✅ Success: {run.output}")
            else:
                print(f"❌ Failed: {run.error_message}")
                if hasattr(run, 'error_details'):
                    print(f"Details: {run.error_details}")
                    
        except Exception as e:
            print(f"❌ Execution error: {e}")

    # Test with minimal input
    debug_workflow_execution(workflow, {"test_input": "hello world"})
    ```
  </Accordion>
</AccordionGroup>

### Conversation Issues

<AccordionGroup>
  <Accordion title="Messages Not Working" icon="message-circle">
    **Problem**: Cannot send messages or get responses.

    **Solutions**:

    ```python theme={null}
    from noxus_sdk.resources.conversations import MessageRequest

    def debug_conversation(conversation):
        try:
            # Test basic message
            test_message = MessageRequest(content="Hello, can you hear me?")
            response = conversation.add_message(test_message)
            
            if response and response.message_parts:
                print("✅ Conversation working")
                print(f"Response: {response.message_parts}")
            else:
                print("❌ Empty response received")
                
        except Exception as e:
            print(f"❌ Message error: {e}")
            
            # Check conversation settings
            print(f"Model: {conversation.settings.model}")
            print(f"Max tokens: {conversation.settings.max_tokens}")
            print(f"Tools: {len(conversation.settings.tools)}")

    debug_conversation(conversation)
    ```
  </Accordion>

  <Accordion title="Tool Usage Issues" icon="wrench">
    **Problem**: Conversation tools not working as expected.

    **Debugging**:

    ```python theme={null}
    def debug_tools(conversation):
        print("Enabled tools:")
        for tool in conversation.settings.tools:
            print(f"- {tool.__class__.__name__}: {tool.enabled}")
            
            # Check tool-specific configuration
            if hasattr(tool, 'kb_id'):
                print(f"  KB ID: {tool.kb_id}")
            if hasattr(tool, 'workflow'):
                print(f"  Workflow: {tool.workflow}")

    # Test tool usage explicitly
    def test_tool_usage(conversation, tool_name):
        try:
            message = MessageRequest(
                content="Test message for tool",
                tool=tool_name
            )
            response = conversation.add_message(message)
            print(f"✅ Tool '{tool_name}' working")
        except Exception as e:
            print(f"❌ Tool '{tool_name}' error: {e}")

    debug_tools(conversation)
    test_tool_usage(conversation, "web_research")
    ```
  </Accordion>
</AccordionGroup>

### Knowledge Base Issues

<AccordionGroup>
  <Accordion title="Document Upload Fails" icon="cloud-upload">
    **Problem**: Cannot upload documents to knowledge base.

    **Solutions**:

    ```python theme={null}
    def debug_kb_upload(kb, file_path):
        import os
        
        # Check file exists and size
        if not os.path.exists(file_path):
            print(f"❌ File not found: {file_path}")
            return
        
        file_size = os.path.getsize(file_path) / (1024 * 1024)  # MB
        print(f"File size: {file_size:.2f} MB")
        
        if file_size > 50:  # Assuming 50MB limit
            print("⚠️ File may be too large")
        
        # Check file type
        file_ext = os.path.splitext(file_path)[1].lower()
        supported_types = kb.document_types or []
        if file_ext.lstrip('.') not in supported_types:
            print(f"❌ Unsupported file type: {file_ext}")
            print(f"Supported types: {supported_types}")
            return
        
        try:
            run_ids = kb.upload_document(files=[file_path])
            print(f"✅ Upload started: {run_ids}")
            
            # Monitor upload progress
            import time
            for _ in range(30):  # Wait up to 5 minutes
                kb.refresh()
                print(f"KB status: {kb.status}")
                if kb.status == "ready":
                    break
                time.sleep(10)
                
        except Exception as e:
            print(f"❌ Upload error: {e}")

    debug_kb_upload(kb, "document.pdf")
    ```
  </Accordion>

  <Accordion title="Knowledge Base Not Ready" icon="clock">
    **Problem**: Knowledge base stuck in processing state.

    **Solutions**:

    ```python theme={null}
    def check_kb_status(kb):
        kb.refresh()
        print(f"Status: {kb.status}")
        print(f"Total documents: {kb.total_documents}")
        print(f"Trained documents: {kb.trained_documents}")
        print(f"Error documents: {kb.error_documents}")
        
        if kb.error_documents > 0:
            print("⚠️ Some documents failed to process")
            
            # Check individual document status
            documents = kb.list_documents()
            for doc in documents:
                if doc.status == "error":
                    print(f"❌ Failed document: {doc.name}")
        
        if kb.status == "processing":
            print("ℹ️ Knowledge base still processing...")
            
            # Check processing runs
            runs = kb.get_runs(status="running")
            print(f"Active runs: {len(runs)}")

    check_kb_status(kb)
    ```
  </Accordion>
</AccordionGroup>

## Performance Issues

### Slow Response Times

```python theme={null}
import time
from contextlib import contextmanager

@contextmanager
def timer():
    start = time.time()
    yield
    end = time.time()
    print(f"Operation took {end - start:.2f} seconds")

# Measure operation times
with timer():
    workflows = client.workflows.list()

# Use async for better performance
import asyncio

async def fast_operations():
    # Run multiple operations concurrently
    tasks = [
        client.workflows.alist(),
        client.conversations.alist(),
        client.knowledge_bases.alist()
    ]

    results = await asyncio.gather(*tasks)
    return results

with timer():
    results = asyncio.run(fast_operations())
```

### Memory Usage

```python theme={null}
import psutil
import os

def check_memory_usage():
    process = psutil.Process(os.getpid())
    memory_mb = process.memory_info().rss / 1024 / 1024
    print(f"Memory usage: {memory_mb:.2f} MB")

# Monitor memory during operations
check_memory_usage()

# Process large datasets in batches
def process_large_dataset(items, batch_size=10):
    for i in range(0, len(items), batch_size):
        batch = items[i:i + batch_size]
        # Process batch
        yield batch
        check_memory_usage()

# Use generators for large results
def get_all_workflows_generator(client):
    page = 1
    while True:
        workflows = client.workflows.list(page=page, page_size=50)
        if not workflows:
            break
        for workflow in workflows:
            yield workflow
        page += 1
```

## Debugging Tools

### Enable Debug Logging

```python theme={null}
import logging

# Configure detailed logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Enable HTTP request logging
import httpx
httpx_logger = logging.getLogger("httpx")
httpx_logger.setLevel(logging.DEBUG)

# Now all HTTP requests will be logged
client = Client(api_key="your_key")
workflows = client.workflows.list()
```

### Request/Response Inspection

```python theme={null}
import httpx

class DebugClient(Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def request(self, method, url, **kwargs):
        print(f"🔄 {method} {url}")
        if 'json' in kwargs:
            print(f"📤 Request body: {kwargs['json']}")

        try:
            response = super().request(method, url, **kwargs)
            print(f"✅ Response: {response.status_code}")
            return response
        except Exception as e:
            print(f"❌ Error: {e}")
            raise

# Use debug client
debug_client = DebugClient(api_key="your_key")
workflows = debug_client.workflows.list()
```

## Getting Help

### Collect Diagnostic Information

```python theme={null}
def collect_diagnostics():
    import sys
    import platform

    print("=== Noxus SDK Diagnostics ===")
    print(f"Python version: {sys.version}")
    print(f"Platform: {platform.platform()}")

    try:
        import noxus_sdk
        print(f"Noxus SDK version: {noxus_sdk.__version__}")
    except:
        print("Noxus SDK version: unknown")

    # Test basic connectivity
    try:
        client = Client(api_key=os.getenv("NOXUS_API_KEY"))
        models = client.get_models()
        print(f"✅ API connection working ({len(models)} models available)")
    except Exception as e:
        print(f"❌ API connection failed: {e}")

    # Check environment
    print(f"API key set: {'Yes' if os.getenv('NOXUS_API_KEY') else 'No'}")
    print(f"Backend URL: {os.getenv('NOXUS_BACKEND_URL', 'default')}")

collect_diagnostics()
```

### Contact Support

When contacting support, include:

1. **Error message** - Full error text and stack trace
2. **Code snippet** - Minimal code that reproduces the issue
3. **Environment** - Python version, OS, SDK version
4. **Expected behavior** - What you expected to happen
5. **Actual behavior** - What actually happened

```python theme={null}
# Template for bug reports
bug_report_template = """
## Bug Report

**Error Message:**
```

\[Paste full error message here]

````

**Code to Reproduce:**
```python
[Minimal code that reproduces the issue]
````

**Environment:**

* Python version:
* OS:
* Noxus SDK version:
* Backend URL:

**Expected Behavior:**
\[What you expected to happen]

**Actual Behavior:**
\[What actually happened]

**Additional Context:**
\[Any other relevant information]
"""

print(bug\_report\_template)

```

## Next Steps

<CardGroup cols={2}>
  <Card
    title="Best Practices"
    icon="sparkles"
    href="/sdk/workflows/examples"
  >
    Learn best practices for using the SDK effectively
  </Card>
  <Card
    title="API Reference"
    icon="book"
    href="/sdk/api-reference/introduction"
  >
    Detailed API documentation for all SDK features
  </Card>
  <Card
    title="Examples"
    icon="code"
    href="/sdk/workflows/examples"
  >
    Working examples for common use cases
  </Card>
  <Card
    title="Community Support"
    icon="users"
    href="https://noxus.ai/community"
  >
    Get help from the Noxus community
  </Card>
</CardGroup>
```
