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

# Search & AI

> Perform semantic search and get AI-generated answers using the Python SDK

## similarity\_search.query

Performs a semantic search across one or more namespaces.

### Parameters

<ParamField query="namespaces" type="List[str]" required>
  A list of one or more namespace names to search within.
</ParamField>

<ParamField query="query" type="Union[str, List[float]]" required>
  The search query (text or a vector).
</ParamField>

<ParamField query="top_k" type="int" default="10">
  The maximum number of results to return. Defaults to 10.
</ParamField>

<ParamField query="threshold" type="Optional[float]">
  A minimum similarity score (0-1) for results. Defaults to None.
</ParamField>

<ParamField query="kiosk_mode" type="bool" default="False">
  A flag for stricter filtering. Defaults to False.
</ParamField>

**Returns:** `Dict[str, Any]` - A dictionary containing the search results under the results key.

**Raises:** `NamespaceNotFound`, `InvalidInputError`.

Text search across one namespace

```python Search Example theme={null}
results = client.similarity_search.query(
    namespaces=["my-faq-documents"],
    query="How long do I have to return an item?",
    top_k=1
)
print(results['results'])
```

### Advanced Search Examples

Search across multiple namespaces

```python Multi-Namespace Search theme={null}
results = client.similarity_search.query(
    namespaces=["faq-documents", "policy-documents"],
    query="return policy",
    top_k=5,
    threshold=0.7
)

for result in results['results']:
    print(f"ID: {result['id']}")
    print(f"Score: {result['score']:.3f}")
    print(f"Text: {result['text'][:100]}...")
    print("---")
```

## answer.generate

Submits a query to a text namespace to get a conversational answer generated by an LLM.

### Parameters

<ParamField query="namespace" type="str" required>
  The single text namespace to search for context.
</ParamField>

<ParamField query="query" type="str" required>
  The user's question or prompt.
</ParamField>

<ParamField query="top_k" type="int" default="5">
  Number of search results to use as context. Defaults to 5.
</ParamField>

<ParamField query="ai_model" type="str" default="deepseek.r1-v1:0">
  The identifier for the LLM to use. See [Generate AI Answer](/python-sdk/ai/generate#available-models) for the full model list.
</ParamField>

<ParamField query="chat_history" type="Optional[List[Dict]]">
  A list of previous conversation turns to maintain context.
</ParamField>

<ParamField query="temperature" type="float" default="0.7">
  The sampling temperature for the LLM (0-1). Defaults to 0.7.
</ParamField>

**Returns:** `Dict[str, Any]` - A dictionary containing the answer, model, and other metadata.

**Raises:** `NamespaceNotFound`, `InvalidInputError`.

```python Generate Answer Example theme={null}
response = client.answer.generate(
    namespace="my-faq-documents",
    query="What is your return policy?",
    top_k=2
)
```

### Advanced AI Generation

Maintain conversation context

```python Conversational AI with History theme={null}
chat_history = [
    {"role": "user", "content": "What are your business hours?"},
    {"role": "assistant", "content": "Our business hours are Monday to Friday, 9 AM to 5 PM EST."}
]

response = client.answer.generate(
    namespace="customer-support",
    query="What about weekends?",
    chat_history=chat_history,
    temperature=0.5,
    ai_model="anthropic.claude-sonnet-4-6"
)

print(f"AI Answer: {response['answer']}")
print(f"Model Used: {response['model']}")
print(f"Context Count: {response['context_count']}")
```

## Complete Search & AI Workflow

```python Complete Search and AI Workflow theme={null}
from moorcheh_sdk import MoorchehClient
import time

with MoorchehClient() as client:
    namespace = "customer-support"

    # 1. Create namespace and upload support documents
    client.namespace.create(namespace, type="text")

    support_docs = [
        {
            "id": "policy-1",
            "text": "Our return policy allows returns within 30 days of purchase with original receipt.",
            "category": "returns"
        },
        {
            "id": "policy-2",
            "text": "We offer free shipping on orders over $50. Standard shipping takes 3-5 business days.",
            "category": "shipping"
        },
        {
            "id": "hours-1",
            "text": "Our customer service is available Monday-Friday 9AM-5PM EST. We're closed on weekends.",
            "category": "hours"
        }
    ]

    client.documents.upload(namespace, support_docs)
    print("Documents uploaded, waiting for processing...")
    time.sleep(5)

    # 2. Perform searches
    print("\n=== SEARCH RESULTS ===")
    search_results = client.similarity_search.query(
        namespaces=[namespace],
        query="return policy",
        top_k=2
    )

    for result in search_results['results']:
        print(f"Score: {result['score']:.3f} | ID: {result['id']}")
        print(f"Text: {result['text'][:80]}...")
        print()

    # 3. Get AI-generated answers
    print("\n=== AI ANSWERS ===")
    questions = [
        "What is your return policy?",
        "How long does shipping take?",
        "Are you open on weekends?"
    ]

    for question in questions:
        response = client.answer.generate(
            namespace=namespace,
            query=question,
            top_k=1
        )
        print(f"Q: {question}")
        print(f"A: {response['answer']}")
        print()
```

## Search Result Structure

Search results contain the following fields:

```python Search Result Format theme={null}
{
    'results': [
        {
            'id': 'document-id',
            'score': 0.85,  # Similarity score (0-1)
            'label': 'High Relevance',  # Human-readable relevance
            'text': 'Document content...',
            'metadata': {  # Your custom metadata
                'category': 'faq',
                'author': 'support-team'
            }
        }
    ],
    'execution_time': 0.123,
    'timings': {...},  # Detailed timing breakdown
    'optimization_info': {...}  # Search optimization details
}
```

## AI Response Structure

AI generation responses contain:

```python AI Response Format theme={null}
{
    'answer': 'Generated answer text...',
    'model': 'deepseek.r1-v1:0',
    'context_count': 3,  # Number of documents used as context
    'query': 'Original user query'
}
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Search Optimization" icon="magnifying-glass">
    * Use specific, clear queries for better results
    * Set appropriate thresholds to filter low-quality results
    * Use multiple namespaces for comprehensive searches
    * Consider kiosk\_mode for production applications
  </Card>

  <Card title="AI Generation" icon="sparkles">
    * Provide clear, specific questions
    * Use chat history for conversational experiences
    * Adjust temperature based on creativity needs
    * Choose appropriate AI models for your use case
  </Card>
</CardGroup>

## Error Handling

```python Robust Search with Error Handling theme={null}
from moorcheh_sdk import MoorchehClient, NamespaceNotFound, InvalidInputError

try:
    with MoorchehClient() as client:
        results = client.similarity_search.query(
            namespaces=["my-namespace"],
            query="search query",
            top_k=5
        )

        if results['results']:
            print(f"Found {len(results['results'])} results")
        else:
            print("No results found")

except NamespaceNotFound:
    print("One or more namespaces don't exist")
except InvalidInputError as e:
    print(f"Invalid search parameters: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```
