POST POST streaming chat with requests

This method allows users to send messages via Python’s requests library and receive streaming AI responses.

Request

  • Endpoint: https://ai.callaback.workers.dev/api/chat
  • Method: POST
  • Headers: Content-Type: application/json
  • Body:
    {
    "messages": [
      { "role": "user", "content": "Your message here" }
    ]
    }
    

Response

Returns a streaming response with Server-Sent Events (SSE).

Status: 200 OK

Stream format:

data: {"response":"Hello"}
data: {"response":" there"}
data: [DONE]

Python Client Example

import requests
import json
import re

def stream_chat(messages):
    url = "https://ai.callaback.workers.dev/api/chat"
    response = requests.post(url, json={"messages": messages}, stream=True)
    
    for line in response.iter_lines():
        if line:
            line = line.decode('utf-8')
            if line.startswith('data: '):
                data = line[6:]
                if data == '[DONE]':
                    break
                # Parse response chunk
                match = re.search(r'"response":"([^"]*)"', data)
                if match:
                    yield match.group(1)

# Usage
for chunk in stream_chat([{"role": "user", "content": "Hello"}]):
    print(chunk, end='', flush=True)

Multi-turn Conversation

# Continue the conversation
messages = [
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi! How can I help you?"},
    {"role": "user", "content": "What is 2+2?"}
]

for chunk in stream_chat(messages):
    print(chunk, end='', flush=True)
print()  # New line after response

Installation

pip install requests

Usage

python chat_client.py

Response Processing

The client handles streaming by:

  • Setting stream=True in the request
  • Iterating through lines with iter_lines()
  • Parsing SSE format with data: prefix
  • Extracting JSON response fields with regex
  • Yielding chunks for real-time display

For error responses, see the response status codes documentation.

POST POST streaming chat with Bash

This method allows users to send messages via cURL and receive streaming AI responses in the terminal.

Request

  • Endpoint: https://ai.callaback.workers.dev/api/chat
  • Method: POST
  • Headers: Content-Type: application/json
  • Body:
    {
    "messages": [
      { "role": "user", "content": "Your message here" }
    ]
    }
    

Response

Returns a streaming response with Server-Sent Events (SSE).

Status: 200 OK

Stream format:

data: {"response":"Hello"}
data: {"response":" there"}
data: [DONE]

Single Request Example

echo '{"messages":[{"role":"user","content":"Hello"}]}' | \
curl -s -X POST https://ai.callaback.workers.dev/api/chat \
  -H "Content-Type: application/json" \
  -d @- \
  --no-buffer | \
  grep -Eo '"response":"[^"]*"' | \
  sed 's/"response":"//g; s/"//g' | \
  tr -d '\n'

Multiple Questions Test Script

#!/bin/bash

# Test all three questions in one command
for q in "Hello" "What is 2+2?" "Tell me a joke"; do
  echo -e "\nQ: $q → A: "
  echo "{\"messages\":[{\"role\":\"user\",\"content\":\"$q\"}]}" | \
  curl -s -X POST https://ai.callaback.workers.dev/api/chat \
    -H "Content-Type: application/json" \
    -d @- \
    --no-buffer | \
    grep -Eo '"response":"[^"]*"' | \
    sed 's/"response":"//g; s/"//g' | \
    tr -d '\n'
  echo ""
done

Usage

Save as test-chat.sh and run:

chmod +x test-chat.sh
./test-chat.sh

Or run directly:

bash test-chat.sh

Response Parsing

The script extracts responses using:

  • grep -Eo '"response":"[^"]*"' - Extract JSON response fields
  • sed 's/"response":"//g; s/"//g' - Remove JSON formatting
  • tr -d '\n' - Join chunks into continuous output

For error responses, see the response status codes documentation.

POST Fetch streaming chat response

This method allows users to send messages and receive streaming AI responses.

Request

  • Endpoint: https://ai.callaback.workers.dev/api/chat
  • Method: POST
  • Headers: Content-Type: application/json
  • Body:
    {
    "messages": [
      { "role": "user", "content": "Your message here" }
    ]
    }
    

Response

Returns a streaming response with Server-Sent Events (SSE).

Status: 200 OK

Stream format:

data: {"response":"Hello"}
data: {"response":" there"}
data: [DONE]

Node.js Example

#!/usr/bin/env node
const fetch = require('node-fetch');

async function testChat(message) {
  console.log(`Testing: ${message}`);

  try {
    const response = await fetch('https://ai.callaback.workers.dev/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        messages: [{ role: 'user', content: message }]
      })
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let fullResponse = '';

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

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data === '[DONE]') {
            console.log('\n');
            return fullResponse;
          }

          // Try to parse as JSON
          try {
            const parsed = JSON.parse(data);
            if (parsed.response) {
              process.stdout.write(parsed.response);
              fullResponse += parsed.response;
            }
          } catch (e) {
            // If not JSON, try regex extraction
            const match = data.match(/"response":"([^"]*)"/);
            if (match && match[1]) {
              process.stdout.write(match[1]);
              fullResponse += match[1];
            }
          }
        }
      }
    }
  } catch (error) {
    console.error(`Error: ${error.message}`);
  }
}

async function runTests() {
  const tests = [
    "Hello",
    "What is 2+2?",
    "Tell me a joke"
  ];

  for (const test of tests) {
    await testChat(test);
  }
}

runTests();

Usage

node testApi.js

For error responses, see the response status codes documentation.

Response status codes

Success

Successes differ from errors in that their body may not be a simple response object with a code and a message. The headers however are consistent across all calls:

  • GET, PUT, DELETE returns 200 OK on success,
  • POST returns 201 on success,

When retrieving stuff for example:

Status: 200 OK { { id: thing_1, name: 'My first thing' }, { id: thing_2, name: 'My second thing' } }

Error

Error responses are simply returning standard HTTP error codes along with some additional information:

  • The error code is sent back as a status header,
  • The body includes an object describing both the code and message (for debugging and/or display purposes),

For a call with an invalid authentication token for example:

Status: 401 Access denied { code: 401, message: 'Access denied: invalid authentication token.' }

Authenticate

This method allows users to retrieve stuff.

Response

Sends back a collection of things.

Authentication: bearer TOKEN { id: thing_2, name: 'My second thing' }

For errors responses, see the response status codes documentation.

GET /stuff Get stuff

This method allows users to retrieve stuff.

Request

  • The headers must include a valid authentication token.

Response

Sends back a collection of things.

Status: 200 OK { { id: thing_1, name: 'My first thing' }, { id: thing_2, name: 'My second thing' } }

For errors responses, see the response status codes documentation.

POST /stuff Post a thing

This method allows users to create a new thing.

Request

  • The headers must include a valid authentication token.
  • The body can’t be empty and must include at least the name attribute, a string that will be used as the name of the thing.

Authentication: bearer TOKEN { name: 'My new thing' }

Response

If succeeds, returns the created thing.

Status: 201 Created { id: new_thing, name: 'My new thing' }

For errors responses, see the response status codes documentation.

PUT /stuff/:id Update a thing

This method allows the user to retrieve his stuff.

Request

  • :id is the id the thing to update.
  • The headers must include a valid authentication token.
  • The body can’t be empty and must include at least the name attribute, a string that will be used as the name of the thing.

Authentication: bearer f862f658-ad89-4fcb-995b-7a4c50554ff6 { name: 'My new thing' }

Response

Sends back a collection of things.

Status: 200 OK { { id: thing_1, name: 'My first thing' }, { id: thing_2, name: 'My second thing' } }

For errors responses, see the response status codes documentation.

DELETE /stuff/:id Delete a thing

This method allows the user to post a new thing to his stuff.

Request

  • :id is the id the thing to delete.
  • The headers must include a valid authentication token.
  • The body is omitted.

Response

Sends back a collection of things.

Status: 200 Deleted { code: 200, message: 'Your thing (id: 736) was deleted' }

For errors responses, see the response status codes documentation.