> ## 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.

# Generate AI Answer

> Generate AI-powered answers using your data with the Python SDK

## 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, or empty string "" for Direct AI Mode.
</ParamField>

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

<ParamField query="top_k" type="int" default="10">
  Number of top relevant chunks for your query across given namespace. Default is 10.
</ParamField>

<ParamField query="threshold" type="Optional[float]">
  Minimum relevance score threshold (0-1) to filter out chunks below this relevance level. Required when kiosk\_mode is true. Only used in Search Mode.
</ParamField>

<ParamField query="kiosk_mode" type="bool" default="False">
  Enable kiosk mode to filter chunks below certain relevance. When kiosk mode is on, threshold is required. Only used in Search Mode.
</ParamField>

<ParamField query="ai_model" type="str" default="deepseek.r1-v1:0">
  The identifier for the LLM to use. See [Available Models](#available-models).
</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>

<ParamField query="header_prompt" type="Optional[str]">
  Custom instruction for AI behavior.
</ParamField>

<ParamField query="footer_prompt" type="Optional[str]">
  Custom instruction to append.
</ParamField>

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

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

### Search Mode Example (with namespace)

```python Generate Answer Example theme={null}
from moorcheh_sdk import MoorchehClient

with MoorchehClient() as client:
    response = client.answer.generate(
        namespace="my-faq-documents",
        query="What is your return policy?",
        top_k=2
    )
    
    print(f"AI Answer: {response['answer']}")
    print(f"Model Used: {response['model']}")
    print(f"Context Count: {response['context_count']}")
```

### Direct AI Mode Example (empty namespace)

```python Direct AI Mode Example theme={null}
from moorcheh_sdk import MoorchehClient

with MoorchehClient() as client:
    response = client.answer.generate(
        namespace="",  # Empty string for direct AI mode
        query="Explain quantum computing in simple terms",
        ai_model="anthropic.claude-sonnet-4-6",
        temperature=0.7,
        chat_history=[
            {"role": "user", "content": "What is AI?"},
            {"role": "assistant", "content": "AI is artificial intelligence..."}
        ],
        header_prompt="You are a science teacher.",
        footer_prompt="Use simple language and examples."
    )
    
    print(f"Answer: {response['answer']}")
```

### Conversational AI with History

```python Conversational AI with History theme={null}
from moorcheh_sdk import MoorchehClient

with MoorchehClient() as client:
    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 Example

```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.namespaces.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. 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()
```

## 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'
}
```

## API Modes

### Search Mode (with namespace)

When you provide a namespace, the API searches your data for relevant context and uses it to generate contextual answers.

### Direct AI Mode (empty namespace)

When you pass an empty string `""` as namespace, the API makes a direct call to the AI model without searching your data.

<Warning>
  **Field Restrictions** (use snake\_case in JSON; matches the REST API):

  * **Empty Namespace Mode**: Only these fields are allowed: `namespace, query, temperature, chat_history, footer_prompt, header_prompt, ai_model`, and `structured_response` when applicable
  * **Provided Namespace Mode**: All fields are allowed: `namespace, query, top_k, threshold, type, kiosk_mode, ai_model, chat_history, header_prompt, footer_prompt, temperature`, and `structured_response` when applicable
</Warning>

## Available Models

| Model ID                               | Name                 | Provider  | Description                                                                         | Credits |
| -------------------------------------- | -------------------- | --------- | ----------------------------------------------------------------------------------- | ------- |
| anthropic.claude-sonnet-4-6            | Claude Sonnet 4.6    | Anthropic | Fast flagship: coding, tools, long docs and RAG (\~1M context).                     | 3       |
| anthropic.claude-opus-4-6-v1           | Claude Opus 4.6      | Anthropic | Deepest reasoning and hardest tasks; pick when quality matters most (\~1M context). | 3       |
| meta.llama4-maverick-17b-instruct-v1:0 | Llama 4 Maverick 17B | Meta      | Long context, summarization, function calling, fine-tuning friendly.                | 3       |
| amazon.nova-pro-v1:0                   | Amazon Nova Pro      | Amazon    | Chat, math, and structured answers for AWS-style workloads.                         | 2       |
| deepseek.r1-v1:0                       | DeepSeek R1          | DeepSeek  | Step-by-step reasoning; math, logic, and technical explanations.                    | 1       |
| deepseek.v3.2                          | DeepSeek V3.2        | DeepSeek  | Efficient general Q\&A, multilingual, everyday RAG (\~164K context).                | 2       |
| openai.gpt-oss-120b-1:0                | OpenAI GPT OSS 120B  | OpenAI    | Large generalist: research-style answers and long-form writing.                     | 3       |
| qwen.qwen3-32b-v1:0                    | Qwen 3 32B           | Qwen      | Code and bilingual (EN/ZH) tasks in a smaller footprint.                            | 2       |
| qwen.qwen3-next-80b-a3b                | Qwen3 Next 80B A3B   | Qwen      | MoE model for long chats, docs, and code at scale (\~256K context).                 | 1       |

## Temperature Guide

* **0.0-0.5**: Conservative, factual responses - best for technical documentation
* **0.5-1.0**: Balanced creativity - good for general Q\&A
* **1.0-2.0**: More creative and varied responses - use carefully for factual content

## Relevance Score Threshold

Results are scored using Information Theoretic Similarity (ITS), providing nuanced relevance measurements:

| Label               | Score Range            | Description                         |
| ------------------- | ---------------------- | ----------------------------------- |
| Close Match         | score ≥ 0.894          | Near-perfect relevance to the query |
| Very High Relevance | 0.632 ≤ score \< 0.894 | Strongly related content            |
| High Relevance      | 0.447 ≤ score \< 0.632 | Significantly related content       |
| Good Relevance      | 0.316 ≤ score \< 0.447 | Moderately related content          |
| Low Relevance       | 0.224 ≤ score \< 0.316 | Minimally related content           |
| Very Low Relevance  | 0.1 ≤ score \< 0.224   | Barely related content              |
| Irrelevant          | score \< 0.1           | No meaningful relation to the query |

## Best Practices

* Provide clear, specific questions
* Use chat history for conversational experiences
* Adjust temperature based on creativity needs
* Choose appropriate AI models for your use case
* For Search Mode: Higher top\_k values provide more context but may increase response time
* For Search Mode: The threshold parameter can be used to filter low-relevance results

## Use Cases

* **Customer Support**: Answer customer questions using your documentation
* **Internal Q\&A**: Help employees find answers in company knowledge bases
* **Educational Tools**: Create AI tutors using educational content
* **Research Assistance**: Get insights from research papers and publications
* **Technical Support**: Provide technical answers based on documentation
* **Content Creation**: Generate content based on existing materials

## Related Operations

* [Search](/python-sdk/search/query) - Search for relevant context documents
* [Upload Text Data](/python-sdk/data/upload-text) - Add documents for AI context
* [List Namespaces](/python-sdk/namespaces/list) - View available namespaces for generation
