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

# Overview

> Architecture for the Explore Chat endpoint

## Purpose

Streaming chat endpoint for business research. Uses OpenRouter (Cerebras) for fast inference with competitor context and real-time web search via Exa.

## Architecture

```mermaid theme={null}
flowchart TD
    Request["POST /api/explore/chat"]
    
    subgraph context [Context Building]
        GetBusiness["Get selected businesses"]
        BuildPrompt["build_system_prompt()"]
    end
    
    subgraph streaming [Streaming]
        StreamChat["stream_chat()"]
        SSE["Server-Sent Events"]
    end
    
    subgraph external [External APIs]
        OpenRouter["OpenRouter (Cerebras)"]
        Exa["Exa (web search)"]
    end
    
    Request --> GetBusiness
    GetBusiness --> BuildPrompt
    BuildPrompt --> StreamChat
    StreamChat --> OpenRouter
    StreamChat -->|"Search needed"| Exa
    StreamChat --> SSE
    SSE --> Response
```

## Request Body

```json theme={null}
{
  "message": "How does competitor X compare to us?",
  "selected_competitor_ids": ["uuid-1", "uuid-2"],
  "conversation_history": [...],
  "system_prompt": null,
  "timezone": "America/New_York"
}
```

## Streaming Response

Returns Server-Sent Events (SSE):

```
data: {"type": "content", "text": "Based on..."}
data: {"type": "content", "text": " the analysis..."}
data: {"type": "search", "query": "competitor pricing 2024"}
data: {"type": "done", "system_prompt": "..."}
```

## System Prompt Caching

* First message: Builds system prompt with competitor context
* Subsequent messages: Reuses cached `system_prompt` from response
* Reduces latency and API costs

## Internal Services

| Service                                      | Purpose                          |
| -------------------------------------------- | -------------------------------- |
| [build\_system\_prompt](build-system-prompt) | Creates context-aware prompt     |
| [stream\_chat](stream-chat)                  | Handles streaming and web search |

## Code Location

```
src/app/apis/explore/chat/
├── routes.py
├── prompt_builder.py
└── children/
    └── stream_handler.py
```
