#!/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()