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

# SDK Quickstart: Chat in 5 Minutes

> Get your first AGO chat working with the JavaScript SDK in under 5 minutes

This tutorial takes you from zero to a working chat page that sends messages to your AGO agent and displays streaming responses. You will start with plain JavaScript, then optionally add a React component.

## What You'll Build

A simple web page where you can:

* Send messages to your AGO agent
* See responses stream in real time, word by word
* Continue past conversations
* (Optional) Drop in a pre-built React chat widget

## Prerequisites

* An AGO instance with at least one published agent
* Your AGO domain (e.g., `acme.useago.com`)
* The domain where you run the SDK added to your allowed domains list (**Settings** > **Widget**)
* [Node.js](https://nodejs.org/) 18 or later installed

***

<Steps>
  <Step title="Install the SDK">
    Create a new project and install the SDK:

    ```bash theme={null}
    mkdir ago-chat-demo && cd ago-chat-demo
    npm init -y
    npm install @useago/sdk
    ```

    This adds `@useago/sdk` (version 0.1.2) to your project. The package includes both vanilla JavaScript helpers and React bindings.
  </Step>

  <Step title="Create the Client">
    Create a file called `index.mjs` and set up the AGO client:

    ```javascript theme={null}
    import { AgoClient } from "@useago/sdk";

    const client = new AgoClient({
      baseUrl: "https://acme.useago.com", // replace with your AGO domain
    });

    console.log("Client ready");
    ```

    Run it to confirm everything is connected:

    ```bash theme={null}
    node index.mjs
    ```

    You should see:

    ```
    Client ready
    ```

    The `baseUrl` points the SDK at your AGO instance. All API calls go through this domain.
  </Step>

  <Step title="Send Your First Message">
    Add a few lines to `index.mjs` to send a message and print the response:

    ```javascript theme={null}
    import { AgoClient } from "@useago/sdk";

    const client = new AgoClient({
      baseUrl: "https://acme.useago.com",
    });

    const response = await client.sendMessage("Hello! What can you help me with?");
    console.log(response.content);

    client.destroy();
    ```

    Run it again:

    ```bash theme={null}
    node index.mjs
    ```

    You should see your agent's reply printed to the terminal — something like:

    ```
    Hi there! I can help you with product questions, troubleshooting,
    and account management. What do you need?
    ```

    `client.destroy()` cleans up open connections when you are done. Always call it before your app exits.
  </Step>

  <Step title="Stream Responses in Real Time">
    Waiting for the full response is fine for scripts, but users expect to see text appear as the agent types. The SDK fires events you can listen to:

    | Event              | When it fires                         |
    | ------------------ | ------------------------------------- |
    | `message:chunk`    | Each time a new piece of text arrives |
    | `message:complete` | The full response is ready            |
    | `message:error`    | Something went wrong                  |

    Create an `index.html` file with a minimal chat UI:

    ```html theme={null}
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <title>AGO Chat Demo</title>
      <style>
        body { font-family: sans-serif; max-width: 600px; margin: 2rem auto; }
        #output { white-space: pre-wrap; background: #f4f4f4; padding: 1rem;
                  min-height: 120px; border-radius: 8px; margin-bottom: 1rem; }
        input { width: 80%; padding: 0.5rem; }
        button { padding: 0.5rem 1rem; }
      </style>
    </head>
    <body>
      <h1>AGO Chat</h1>
      <div id="output">Responses will appear here...</div>
      <input id="msg" type="text" placeholder="Type a message..." />
      <button id="send">Send</button>

      <script type="module">
        import { AgoClient, onMessageChunk, onMessage } from "@useago/sdk";

        const client = new AgoClient({
          baseUrl: "https://acme.useago.com", // replace with your domain
        });

        const output = document.getElementById("output");
        const msgInput = document.getElementById("msg");
        const sendBtn = document.getElementById("send");

        // Append each chunk as it arrives
        onMessageChunk(client, ({ content }) => {
          output.textContent += content;
        });

        // Log the final response when streaming finishes
        onMessage(client, (message) => {
          console.log("Complete response:", message.content);
        });

        sendBtn.addEventListener("click", async () => {
          const text = msgInput.value.trim();
          if (!text) return;

          output.textContent = "";          // clear previous response
          msgInput.value = "";
          await client.sendMessage(text);
        });
      </script>
    </body>
    </html>
    ```

    Open `index.html` in your browser (you can use a local dev server like `npx serve .`). Type a question, click **Send**, and watch the response stream in character by character.
  </Step>

  <Step title="Add Conversation History">
    By default, each `sendMessage` call starts a new conversation. To continue an existing one, pass a `conversationId`:

    ```javascript theme={null}
    // First message — starts a new conversation
    const first = await client.sendMessage("What are your business hours?");
    const conversationId = first.conversationId;

    // Follow-up — same conversation thread
    const followUp = await client.sendMessage("And on weekends?", {
      conversationId,
    });
    console.log(followUp.content);
    ```

    The agent remembers the earlier context, so it knows "And on weekends?" refers to business hours.

    You can also list and retrieve past conversations:

    ```javascript theme={null}
    // Get all conversations for the current visitor
    const conversations = await client.getConversations();
    console.log(`Found ${conversations.length} conversations`);

    // Load a specific conversation by ID
    const conversation = await client.getConversation(conversations[0].id);
    console.log("Messages:", conversation.messages.length);
    ```

    This is useful when you want to show a sidebar with conversation history, or let users pick up where they left off.
  </Step>

  <Step title="Drop-in React Chat Component">
    If you use React, the SDK ships with ready-made components. The fastest option is `ChatWidget`, which gives you a floating chat bubble with no extra code.

    #### Option A: Pre-built widget

    ```jsx theme={null}
    import { AgoProvider, ChatWidget } from "@useago/sdk/react";

    function App() {
      return (
        <AgoProvider baseUrl="https://acme.useago.com">
          <ChatWidget
            title="Support"
            welcomeMessage="Hi! How can I help you today?"
          />
        </AgoProvider>
      );
    }
    ```

    `AgoProvider` creates the client and shares it with every AGO component below it. `ChatWidget` renders the full chat UI — input field, message list, streaming, and conversation management are all built in.

    #### Option B: Custom chat with hooks

    When you need full control over the UI, use the `useMessages` hook instead:

    ```jsx theme={null}
    import { AgoProvider } from "@useago/sdk/react";
    import { useAgo, useMessages } from "@useago/sdk/react";

    function CustomChat() {
      const client = useAgo();
      const { messages, sendMessage, isLoading } = useMessages({ client });

      const handleSubmit = (e) => {
        e.preventDefault();
        const text = e.target.elements.msg.value;
        sendMessage(text);
        e.target.reset();
      };

      return (
        <div>
          <ul>
            {messages.map((m) => (
              <li key={m.id}>
                <strong>{m.role}:</strong> {m.content}
              </li>
            ))}
          </ul>

          {isLoading && <p>Thinking...</p>}

          <form onSubmit={handleSubmit}>
            <input name="msg" placeholder="Ask something..." />
            <button type="submit">Send</button>
          </form>
        </div>
      );
    }

    function App() {
      return (
        <AgoProvider baseUrl="https://acme.useago.com">
          <CustomChat />
        </AgoProvider>
      );
    }
    ```

    `useMessages` returns a `messages` array, a `sendMessage` function, and an `isLoading` flag. Streaming is handled for you — `messages` updates as each chunk arrives.

    Other hooks you can use:

    * `useAgo()` — returns the underlying `AgoClient` instance
    * `useConversation({ client })` — manages the conversation list (load, switch, create)
  </Step>
</Steps>

## Next Steps

You now have a working chat powered by your AGO agent. Here are some directions to explore:

* [SDK Integration](/features/sdk-integration) — full reference for `AgoClient` configuration and auto-detection via `window.AGO`, `<meta>` tags, or `data-ago-*` attributes
* [Client Functions](/api/client-functions) — complete list of SDK methods
* [Widget Deployment](/guides/widget-deployment-howto) — embed the chat widget on your website without writing code
* [API Integration](/api/rest-api) — use the REST API directly for server-side or non-JavaScript integrations
