This tutorial demonstrates how to build interactive chat experiences using Gloo AI APIs. You’ll learn to create chat sessions, send messages, continue conversations, and retrieve chat history. The Chat and Message APIs allow for:
  • Persistent conversations with session management
  • Contextual responses that build on previous interactions
  • Source integration for grounded, authoritative answers
  • Streaming responses for real-time conversation flow

Prerequisites

Before starting, ensure you have:
The Chat and Message APIs require Bearer token authentication. If you haven’t set up authentication yet, follow the Authentication Tutorial to learn how to exchange your credentials for access tokens and manage token expiration.

Step 1: Creating a Chat Session

The Message API can either create a new chat session or continue an existing one. When you don’t provide a chat_id, it automatically creates a new session.
MESSAGE_API_URL = "https://platform.ai.gloo.com/ai/v1/message"

def create_chat_session(initial_message):
    """Create a new chat session with an initial message."""
    token = ensure_valid_token()

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    #- Request body for new chat (no chat_id provided)
    payload = {
        "query": initial_message,
        "character_limit": 1000,
        "sources_limit": 5,
        "stream": False,
        "publishers": [],
        "enable_suggestions": 1  #- Enable suggested follow-up questions
    }

    response = requests.post(MESSAGE_API_URL, headers=headers, json=payload)
    response.raise_for_status()

    return response.json()

#- Example usage
initial_question = "How can I find meaning and purpose when facing life's greatest challenges?"
chat_response = create_chat_session(initial_question)

print("Chat created successfully!")
print(f"Chat ID: {chat_response['chat_id']}")
print(f"Message ID: {chat_response['message_id']}")
print(f"Response: {chat_response['message']}")

#- Show suggested follow-up questions
if chat_response.get('suggestions'):
    print("\nSuggested follow-up questions:")
    for i, suggestion in enumerate(chat_response['suggestions'], 1):
        print(f"{i}. {suggestion}")

Step 2: Continuing the Conversation

Once you have a chat session, you can continue the conversation by including the chat_id from the previous response in your next message request. You don’t need to retrieve chat history to continue the conversation - the API maintains context automatically.
def continue_conversation(chat_id, follow_up_message):
    """Continue an existing chat conversation."""
    token = ensure_valid_token()

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    #- Include chat_id to continue the conversation
    payload = {
        "chat_id": chat_id,
        "query": follow_up_message,
        "character_limit": 1000,
        "sources_limit": 5,
        "stream": False,
        "publishers": [],
        "enable_suggestions": 1  #- Continue getting suggestions
    }

    response = requests.post(MESSAGE_API_URL, headers=headers, json=payload)
    response.raise_for_status()

    return response.json()

#- Example: Continue the conversation using a suggested response
#- Use the first suggestion from the initial response
if chat_response.get('suggestions') and len(chat_response['suggestions']) > 0:
    follow_up = chat_response['suggestions'][0]  #- Use first suggested question
else:
    follow_up = "Can you give me practical steps I can take today to begin this journey?"

follow_up_response = continue_conversation(chat_response['chat_id'], follow_up)

print("\nFollow-up Response:")
print(f"Question: {follow_up}")
print(f"Response: {follow_up_response['message']}")

Step 3: Retrieving Chat History (Optional)

If you want to view the complete conversation history, you can retrieve it using the Chat API. This is useful for displaying conversation logs or analyzing chat patterns.
def get_chat_history(chat_id):
    """Retrieve the complete chat history for a conversation."""
    token = ensure_valid_token()

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    #- Use the chat endpoint to get full conversation history
    params = {"chat_id": chat_id}

    response = requests.get(CHAT_API_URL, headers=headers, params=params)
    response.raise_for_status()

    return response.json()

#- Example: Get chat history after the follow-up conversation
print("\n" + "="*50)
print("COMPLETE CONVERSATION HISTORY")
print("="*50)

chat_history = get_chat_history(chat_response['chat_id'])

#- Display the conversation history
for i, message in enumerate(chat_history.get('messages', []), 1):
    role = message.get('role', 'unknown')
    content = message.get('content', '')
    timestamp = message.get('timestamp', '')

    print(f"\n{i}. {role.upper()}: {content}")
    if timestamp:
        print(f"   Time: {timestamp}")

Complete Working Examples

Here are complete, runnable examples that demonstrate the full chat flow:
#!/usr/bin/env python3
"""
Complete Chat Example - Python
Demonstrates creating a chat session and continuing the conversation.
"""

import requests
import time
import os
from dotenv import load_dotenv

#- Load environment variables
load_dotenv()

#- Configuration
CLIENT_ID = os.getenv("GLOO_CLIENT_ID", "YOUR_CLIENT_ID")
CLIENT_SECRET = os.getenv("GLOO_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
TOKEN_URL = "https://platform.ai.gloo.com/oauth2/token"
MESSAGE_API_URL = "https://platform.ai.gloo.com/ai/v1/message"
CHAT_API_URL = "https://platform.ai.gloo.com/ai/v1/chat"

#- Global token storage
access_token_info = {}

def get_access_token():
    """Retrieve a new access token from the Gloo AI API."""
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    data = {"grant_type": "client_credentials", "scope": "api/access"}

    response = requests.post(TOKEN_URL, headers=headers, data=data, auth=(CLIENT_ID, CLIENT_SECRET))
    response.raise_for_status()

    token_data = response.json()
    token_data['expires_at'] = int(time.time()) + token_data['expires_in']

    return token_data

def is_token_expired(token_info):
    """Check if the token is expired or close to expiring."""
    if not token_info or 'expires_at' not in token_info:
        return True
    return time.time() > (token_info['expires_at'] - 60)

def ensure_valid_token():
    """Ensure we have a valid access token."""
    global access_token_info
    if is_token_expired(access_token_info):
        print("Getting new access token...")
        access_token_info = get_access_token()
    return access_token_info['access_token']

def send_message(message_text, chat_id=None):
    """Send a message to the chat API."""
    token = ensure_valid_token()

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    payload = {
        "query": message_text,
        "character_limit": 1000,
        "sources_limit": 5,
        "stream": False,
        "publishers": []
    }

    if chat_id:
        payload["chat_id"] = chat_id

    response = requests.post(MESSAGE_API_URL, headers=headers, json=payload)
    response.raise_for_status()

    return response.json()

def get_chat_history(chat_id):
    """Retrieve the full chat history for a given chat ID."""
    token = ensure_valid_token()

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    params = {"chat_id": chat_id}

    response = requests.get(CHAT_API_URL, headers=headers, params=params)
    response.raise_for_status()

    return response.json()

def main():
    """Main function demonstrating the complete chat flow."""
    try:
        #- Start with a deep, meaningful question
        initial_question = "How can I find meaning and purpose when facing life's greatest challenges?"

        print("=== Starting New Chat Session ===")
        print(f"Question: {initial_question}")
        print()

        #- Create new chat session
        chat_response = send_message(initial_question)
        chat_id = chat_response['chat_id']

        print("AI Response:")
        print(chat_response['message'])
        print()

        #- Show suggested follow-up questions
        if chat_response['suggestions']:
            print("Suggested follow-up questions:")
            for i, suggestion in enumerate(chat_response['suggestions'], 1):
                print(f"{i}. {suggestion}")
            print()

        #- Use the first suggested question for follow-up, or fallback
        if chat_response['suggestions']:
            follow_up_question = chat_response['suggestions'][0]
        else:
            follow_up_question = "Can you give me practical steps I can take today to begin this journey?"

        print("=== Continuing the Conversation ===")
        print(f"Using suggested question: {follow_up_question}")
        print()

        #- Send follow-up message
        follow_up_response = send_message(follow_up_question, chat_id)

        print("AI Response:")
        print(follow_up_response.message)
        print()

        #- Display final chat history
        print("=== Complete Chat History ===")
        chat_history = get_chat_history(chat_id)

        for message in chat_history['messages']:
            role = message['role'].upper()
            content = message['message']
            print(f"{role}: {content}")
            print()

        print("Chat session completed successfully!")

    except requests.exceptions.RequestException as e:
        print(f"API Error: {e}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

Error Handling Best Practices

When working with the Message API, implement proper error handling for common scenarios:

Authentication Errors

  • 401 Unauthorized: Token expired or invalid
  • 403 Forbidden: Insufficient permissions

Request Errors

  • 400 Bad Request: Invalid request parameters
  • 422 Unprocessable Entity: Validation errors

Rate Limiting

  • 429 Too Many Requests: Implement backoff strategies

Network Issues

  • Connection timeouts: Implement retry logic
  • Network failures: Handle gracefully with user feedback

Advanced Features

Streaming Responses

Set stream: true in your request for real-time response streaming:
{
  "query": "Tell me about hope in difficult times",
  "stream": true,
  "chat_id": "your-chat-id"
}

Publisher Filtering

Restrict responses to specific content publishers:
{
  "query": "What does Scripture say about finding purpose?",
  "publishers": ["Bible", "Christian Literature"],
  "chat_id": "your-chat-id"
}

Response Customization

Control response length and source count:
{
  "query": "How can I grow spiritually?",
  "character_limit": 500,
  "sources_limit": 3,
  "chat_id": "your-chat-id"
}

Next Steps

Now that you understand the Message API, consider exploring:
  1. Authentication Tutorial - For detailed authentication setup
  2. Messages API - For additional API information
  3. Completions Tutorial - For stateless chat interactions
  4. Tool Use - For enhanced AI capabilities
The Message API provides a powerful foundation for building meaningful, contextual conversations that can help users explore deep questions about life, purpose, and human flourishing.