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

# How It Works

> The Aomi request flow end to end, from a user message through tool calls and simulation to a signed transaction, using a worked example.

This page follows one request from start to finish: a user message, the tool calls it triggers, the simulation step, and the wallet signature. **MyCoinDex**, a fictional crypto exchange, is the running example. For the component view of how an App and the Runtime fit together, see [Architecture](/docs/concepts/architecture).

## 1. Your APIs

MyCoinDex exposes standard HTTP endpoints. Aomi does not modify them.

| Endpoint              | Method | Description             |
| --------------------- | ------ | ----------------------- |
| `/prices/{symbol}`    | GET    | Current token price     |
| `/trades`             | POST   | Execute a trade         |
| `/portfolio/{userId}` | GET    | User portfolio and P\&L |
| `/markets`            | GET    | Available trading pairs |
| `/orderbook/{pair}`   | GET    | Order book depth        |

## 2. APIs Become AI Tools

Aomi wraps each endpoint as a **tool**, a typed function the LLM can invoke. Each tool has a name, description, and typed parameters.

When a user asks "What's ETH trading at?", the model calls `GetTokenPrice` with `{ symbol: "ETH" }`. The tool hits `/prices/eth`, returns the result, and the model composes a response. Tools can execute concurrently.

## 3. Configuring the Assistant

### Preamble

The system prompt that shapes personality and rules:

```
You are the MyCoinDex trading assistant. You help users check
prices, manage portfolios, and execute trades.

Always confirm with the user before executing a trade.
Show prices in USD unless the user requests otherwise.
```

### Model Selection

| Provider   | Models                      |
| ---------- | --------------------------- |
| Anthropic  | Claude Sonnet, Claude Haiku |
| OpenAI     | GPT-4o, GPT-4o Mini         |
| OpenRouter | 100+ models                 |

Models can be changed at runtime. No redeployment needed.

### RAG Document Store (Optional)

If MyCoinDex has documentation, FAQs, or knowledge base articles, Aomi ingests them into a vector store for the assistant to search.

## 4. Deployed as an App

```
App:        "mycoindex"
Endpoint:   POST /api/chat?app=mycoindex
Tools:      GetTokenPrice, ExecuteTrade, GetPortfolio, ListMarkets
Preamble:   MyCoinDex trading assistant
Model:      Claude Sonnet (default, switchable)
```

Each app is fully isolated.

## 5. API Key and Authentication

MyCoinDex receives an API key scoped to their app:

```
AOMI-APP-KEY: sk-mcd-a1b2c3d4e5f6
X-Session-Id: 550e8400-e29b-41d4-a716-446655440000
```

## 6. The Request Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend
    participant Aomi as Aomi Backend
    participant LLM
    participant Tool as MyCoinDex API
    User->>Frontend: "What's my ETH position worth?"
    Frontend->>Aomi: POST /api/chat?app=mycoindex\nAOMI-APP-KEY: sk-mcd-...\nX-Session-Id: session-uuid\n{"text": "What's my ETH position worth?"}
    Aomi->>LLM: Messages + available tools
    LLM-->>Aomi: ToolCall: GetPortfolio(userId)
    Aomi->>Tool: GET /portfolio/user123
    Tool-->>Aomi: {"eth": 2.5, "value_usd": 8750}
    Aomi->>LLM: Tool result + continue
    LLM-->>Aomi: ToolCall: GetTokenPrice(ETH)
    Aomi->>Tool: GET /prices/eth
    Tool-->>Aomi: {"price": 3500, "change_24h": "+2.1%"}
    Aomi->>LLM: Tool result + continue
    loop Streaming Response
        LLM-->>Aomi: StreamingText chunk
        Aomi-->>Frontend: SSE: data: {"type":"text","content":"Your..."}
        Frontend-->>User: Text appears incrementally
    end
    LLM-->>Aomi: Complete
    Aomi-->>Frontend: SSE: data: {"type":"complete"}
```

### Step by Step

1. User sends a message via the widget or headless integration.
2. Frontend sends HTTP POST to `/api/chat?app=mycoindex` with the API key.
3. Backend validates the API key and loads the session.
4. Backend sends message + history + tools to the selected LLM.
5. LLM decides to call tools and requests `GetPortfolio` and `GetTokenPrice`.
6. Backend executes tool calls against MyCoinDex's APIs.
7. Tool results go back to the LLM for interpretation.
8. LLM streams its response, and each text chunk forwards as an SSE event.
9. Frontend renders incrementally.
10. Complete event signals the response is finished.

## SSE Stream Format

```
data: {"type":"text","content":"Your ETH "}
data: {"type":"text","content":"position is worth "}
data: {"type":"text","content":"$8,750"}
data: {"type":"tool_call","name":"GetPortfolio","args":{"userId":"user123"}}
data: {"type":"tool_result","name":"GetPortfolio","result":{"eth":2.5,"value_usd":8750}}
data: {"type":"complete"}
```

| Event Type    | Purpose                               |
| ------------- | ------------------------------------- |
| `text`        | Incremental text chunk from the LLM   |
| `tool_call`   | The model is invoking a tool          |
| `tool_result` | Result returned from a tool execution |
| `complete`    | Response finished                     |

## 7. When a Tool Produces a Transaction

The flow above reads data. A write follows the same path until the tool builds a transaction. Then the safety steps take over. A tool never holds a key and never signs. It returns a transaction for the Runtime to simulate and the user's wallet to sign.

```mermaid theme={null}
flowchart LR
    INTENT[User asks to trade] --> TOOL[Tool builds tx params]
    TOOL --> SIM[Simulate on a fork]
    SIM --> REVIEW[User reviews exact outcome]
    REVIEW -->|Approve| SIGN[Wallet signs locally]
    REVIEW -->|Reject| CANCEL[Cancelled]
    SIGN --> SUBMIT[Submitted to chain]
```

1. The model calls a write tool, for example `ExecuteTrade`.
2. The tool builds the transaction parameters and returns them. It does not sign.
3. The Runtime simulates the transaction on a fork of the live network.
4. The user sees the exact token changes, gas, and contract calls. This is the simulate step.
5. If the user approves, the wallet signs locally and the transaction is submitted. If the user rejects, nothing is sent.

For the safety properties of this flow, see [Security](/docs/concepts/security). For the simulation internals, see the [Simulation Reference](/docs/reference/simulation).

## What You Get

| Capability                   | Details                                              | Managed By |
| ---------------------------- | ---------------------------------------------------- | ---------- |
| **AI assistant**             | Understands your product, calls your APIs            | Aomi       |
| **Streaming chat**           | Real time responses via SSE                          | Aomi       |
| **Tool execution**           | LLM calls your APIs as needed during conversations   | Aomi       |
| **Session management**       | Persistent threads, history, and state               | Aomi       |
| **Multi-model support**      | Switch between Claude, GPT-4o, and others at runtime | Aomi       |
| **Wallet integration**       | Optional Web3 wallet connect for onchain actions     | Aomi       |
| **Scaling and availability** | Hosted infrastructure, no GPUs or LLM keys to manage | Aomi       |
| **Your API endpoints**       | Standard HTTP, no modifications required             | You        |
| **Frontend integration**     | Widget, headless, or Telegram                        | You        |
| **API key security**         | Store securely, never expose client-side             | You        |

## Next Steps

* [Reference / Apps & Auth](/docs/reference/apps-auth): how API keys, apps, and sessions fit together.
* [API Reference](/docs/reference/api-reference): full HTTP endpoint documentation.
* [Sessions](/docs/reference/sessions): how chat sessions are created and managed.
