API v1

Code examples

Complete working examples in Python, Node.js, and cURL — all include error handling and can be copied directly into your project.

Python

Python
import requests
import json
import os

API_KEY = os.environ.get("CHATMOUNT_API_KEY")
BASE_URL = "https://services.chatmount.co/v1/chat"

def chat(message, stream=False, session_id=None):
    """Send a message and return the response."""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }
    payload = {
        "message": message,
        "stream": stream,
        "include_sources": True,
    }
    if session_id:
        payload["session_id"] = session_id

    response = requests.post(BASE_URL, headers=headers, json=payload, stream=stream)

    # Handle errors
    if response.status_code == 429:
        reset = response.headers.get("X-RateLimit-Reset")
        print(f"Rate limited. Retry after timestamp: {reset}")
        return None
    response.raise_for_status()

    if not stream:
        return response.json()

    # Streaming
    full_response = ""
    for line in response.iter_lines():
        if line:
            line = line.decode("utf-8")
            if line.startswith("data: "):
                event = json.loads(line[6:])
                if event["type"] == "token":
                    full_response += event["content"]
                    print(event["content"], end="", flush=True)
                elif event["type"] == "sources":
                    print("\n\nSources:")
                    for s in event["sources"]:
                        print(f"  - {s['title']}: {s['url']}")
                elif event["type"] == "done":
                    print()
    return full_response

# Usage
reply = chat("What services do you offer?")
print(reply["message"])

# Streaming
chat("Tell me more", stream=True)

# Multi-turn conversation
chat("What services do you offer?", session_id="session-123")
chat("Tell me more about the first one", session_id="session-123")

Node.js

JavaScript
const API_KEY = process.env.CHATMOUNT_API_KEY;
const BASE_URL = "https://services.chatmount.co/v1/chat";

async function chat(message, { stream = false, sessionId } = {}) {
  const response = await fetch(BASE_URL, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      message,
      stream,
      session_id: sessionId,
      include_sources: true,
    }),
  });

  // Handle errors
  if (response.status === 429) {
    const reset = response.headers.get("X-RateLimit-Reset");
    console.error(`Rate limited. Retry after: ${reset}`);
    return null;
  }
  if (!response.ok) {
    const err = await response.json();
    throw new Error(err.error || `HTTP ${response.status}`);
  }

  if (!stream) {
    return response.json();
  }

  // Streaming
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let fullResponse = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    for (const line of chunk.split("\n")) {
      if (line.startsWith("data: ")) {
        const event = JSON.parse(line.slice(6));
        if (event.type === "token") {
          fullResponse += event.content;
          process.stdout.write(event.content);
        } else if (event.type === "sources") {
          console.log("\nSources:", event.sources);
        }
      }
    }
  }
  return fullResponse;
}

// Usage
const reply = await chat("What services do you offer?");
console.log(reply.message);

// Streaming
await chat("Tell me more", { stream: true });

// Multi-turn conversation
await chat("What services do you offer?", { sessionId: "session-123" });
await chat("Tell me more about the first one", { sessionId: "session-123" });

cURL

bash
# Non-streaming request
curl -X POST https://services.chatmount.co/v1/chat \
  -H "Authorization: Bearer $CHATMOUNT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What services do you offer?",
    "include_sources": true
  }'

# Streaming request
curl -X POST https://services.chatmount.co/v1/chat \
  -H "Authorization: Bearer $CHATMOUNT_API_KEY" \
  -H "Content-Type: application/json" \
  --no-buffer \
  -d '{
    "message": "What services do you offer?",
    "stream": true
  }'

# With session ID (multi-turn)
curl -X POST https://services.chatmount.co/v1/chat \
  -H "Authorization: Bearer $CHATMOUNT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Tell me more about the first one",
    "session_id": "session-123"
  }'

Related