Skip to content

Chat API

šŸ’¬ AI Chat Interface

The Chat API provides conversational AI capabilities powered by Google's Agent Development Kit (ADK) and Gemini models. Users can engage in financial discussions with specialized AI agents that provide market analysis, portfolio advice, and real-time financial insights.

Base URL

All chat endpoints are prefixed with:

/api/v1/chat/

Authentication

All chat endpoints require user authentication. Include the Bearer token in the Authorization header:

Authorization: Bearer <your_jwt_token>

Data Models

ChatRequest

Request model for sending messages to the AI chat system.

{
  "message": "What's the current price of Apple stock?",
  "session_id": "session_abc123def456" // Optional - maintains conversation context
}

ChatResponse

Response model containing the AI agent's reply and session information.

{
  "reply": "Apple (AAPL) is currently trading at $185.25, up 2.1% from yesterday's close. The stock has shown strong performance this quarter with a 15% gain.",
  "session_id": "session_abc123def456"
}

SessionListResponse

Response model for listing user chat sessions.

{
  "sessions": [
    {
      "session_id": "session_abc123def456",
      "last_message": "What's the market outlook for tech stocks?",
      "updated_at": "2025-01-15T14:30:00Z",
      "message_count": 12
    }
  ],
  "total_count": 1
}

SessionDetailResponse

Detailed information about a specific chat session.

{
  "session_id": "session_abc123def456",
  "user_id": "user_123",
  "state": {
    "current_agent": "market_analyst",
    "context": "Discussing tech sector analysis",
    "preferences": {
      "detailed_analysis": true,
      "risk_level": "moderate"
    }
  },
  "created_at": "2025-01-15T10:00:00Z",
  "updated_at": "2025-01-15T14:30:00Z"
}

Endpoints

Send Chat Message

Send a message to the AI chat system and receive a response from the appropriate agent.

POST /api/v1/chat/

Request Body

{
  "message": "How is Tesla stock performing today and what factors are driving its price?",
  "session_id": "session_uuid_optional"
}

Response

Status Code: 200 OK

{
  "reply": "Tesla (TSLA) is currently trading at $248.50, up 1.8% today ($4.35 increase). The stock is being driven by several key factors:\n\nšŸ“ˆ **Positive Drivers:**\n• Q4 delivery numbers exceeded analyst expectations (484,507 vehicles vs 483,000 expected)\n• Strong charging network expansion announcements\n• Positive sentiment around FSD (Full Self-Driving) improvements\n\nšŸ“Š **Technical Analysis:**\n• Breaking through resistance at $245\n• Volume is 25% above average, indicating strong interest\n• RSI at 58 suggests room for further upside\n\nWould you like me to analyze any specific aspect of Tesla's performance in more detail?",
  "session_id": "session_abc123def456"
}

Session Management

  • New Session: If no session_id is provided, a new session will be created
  • Existing Session: Provide session_id to continue a previous conversation with maintained context
  • Context Preservation: Sessions maintain conversation history and user preferences

Error Responses

503 Service Unavailable - Google API key not configured

{
  "detail": "AI chat service unavailable - Google API key not configured. Please add your Google API key in settings."
}

500 Internal Server Error - Chat processing failed

{
  "detail": "Chat processing failed"
}


Get Agent Information

Retrieve information about the current AI agent configuration and capabilities.

GET /api/v1/chat/agent-info

Response

Status Code: 200 OK

{
  "agent_name": "Quantbot Manager",
  "description": "AI-powered financial markets assistant with multi-agent orchestration",
  "model": "gemini-2.5-flash",
  "tools": [
    "get_stock_price",
    "get_market_news",
    "analyze_portfolio",
    "get_financial_metrics",
    "search_news",
    "get_market_sentiment"
  ]
}

AI Agent System

Multi-Agent Architecture

Quantbot uses a sophisticated multi-agent system with specialized roles:

Manager Agent (Primary Orchestrator)

  • Model: Gemini 2.5 Flash
  • Role: Routes queries to appropriate specialist agents
  • Capabilities: Query analysis, agent selection, response coordination

Specialist Agents

  1. Portfolio Advisor
  2. Focus: Investment optimization, asset allocation
  3. Tools: Portfolio analysis, risk assessment, optimization algorithms

  4. Market Analyst

  5. Focus: Real-time market data, technical analysis
  6. Tools: Stock prices, market indicators, chart analysis

  7. News Analyst

  8. Focus: Financial news, sentiment analysis
  9. Tools: NewsAPI integration, sentiment scoring, impact analysis

  10. Risk Assessor

  11. Focus: Portfolio risk analysis, stress testing
  12. Tools: VaR calculations, correlation analysis, scenario modeling

  13. General Assistant

  14. Focus: Fallback for general financial questions
  15. Tools: Basic calculations, general financial knowledge

Dynamic Agent Selection

The system automatically routes queries to the most appropriate agent based on:

  • Intent Analysis: Understanding what the user wants to accomplish
  • Domain Expertise: Matching queries to specialist knowledge areas
  • Context Awareness: Considering conversation history and user preferences
  • Tool Requirements: Selecting agents with necessary data access tools

Session Management

Session Lifecycle

  1. Creation: New session created on first interaction or explicit request
  2. Context Maintenance: Session stores conversation history and preferences
  3. Memory Integration: Sessions connect to the memory system for long-term recall
  4. Persistence: Sessions are automatically saved and can be resumed

Session Features

  • Conversation History: Full context of previous interactions
  • User Preferences: Stored preferences for analysis depth, risk tolerance, etc.
  • Agent Context: Remembers which agents were used and their findings
  • Cross-Session Memory: Important insights are stored in long-term memory

Integration Examples

Python Example

import requests
from typing import Optional

class QuantbotChatClient:
    def __init__(self, base_url: str, access_token: str):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json"
        }
        self.current_session_id: Optional[str] = None

    def send_message(self, message: str, session_id: Optional[str] = None) -> dict:
        """Send a message to the chat API"""
        # Use provided session_id or current session
        use_session_id = session_id or self.current_session_id

        response = requests.post(
            f"{self.base_url}/api/v1/chat/",
            headers=self.headers,
            json={
                "message": message,
                "session_id": use_session_id
            }
        )
        response.raise_for_status()

        result = response.json()
        # Store session ID for future messages
        self.current_session_id = result["session_id"]
        return result

    def get_agent_info(self) -> dict:
        """Get information about the AI agent"""
        response = requests.get(
            f"{self.base_url}/api/v1/chat/agent-info",
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()

    def start_new_session(self) -> None:
        """Start a new conversation session"""
        self.current_session_id = None

# Usage
chat_client = QuantbotChatClient("http://localhost:8000", "your_access_token")

# Start conversation
response = chat_client.send_message("What's the latest news on Apple stock?")
print(f"šŸ¤– Quantbot: {response['reply']}")

# Continue conversation with context
follow_up = chat_client.send_message("What about Tesla?")
print(f"šŸ¤– Quantbot: {follow_up['reply']}")

# Get agent information
agent_info = chat_client.get_agent_info()
print(f"šŸ“Š Agent: {agent_info['agent_name']} using {agent_info['model']}")
print(f"šŸ› ļø Available tools: {', '.join(agent_info['tools'])}")

# Start fresh conversation
chat_client.start_new_session()
new_conversation = chat_client.send_message("Help me analyze my portfolio risk")
print(f"šŸ¤– Quantbot: {new_conversation['reply']}")

TypeScript Example

interface ChatMessage {
  message: string;
  session_id?: string;
}

interface ChatResponse {
  reply: string;
  session_id: string;
}

interface AgentInfo {
  agent_name: string;
  description: string;
  model: string;
  tools: string[];
}

class QuantbotChatAPI {
  private currentSessionId?: string;

  constructor(private baseURL: string, private accessToken: string) {}

  private get headers() {
    return {
      'Authorization': `Bearer ${this.accessToken}`,
      'Content-Type': 'application/json'
    };
  }

  async sendMessage(message: string, sessionId?: string): Promise<ChatResponse> {
    const useSessionId = sessionId || this.currentSessionId;

    const response = await fetch(`${this.baseURL}/api/v1/chat/`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({
        message,
        session_id: useSessionId
      })
    });

    if (!response.ok) {
      if (response.status === 503) {
        throw new Error('AI service unavailable - Google API key not configured');
      }
      throw new Error(`Chat request failed: ${response.statusText}`);
    }

    const result: ChatResponse = await response.json();
    this.currentSessionId = result.session_id;
    return result;
  }

  async getAgentInfo(): Promise<AgentInfo> {
    const response = await fetch(`${this.baseURL}/api/v1/chat/agent-info`, {
      method: 'GET',
      headers: this.headers
    });

    if (!response.ok) {
      throw new Error(`Failed to get agent info: ${response.statusText}`);
    }

    return await response.json();
  }

  startNewSession(): void {
    this.currentSessionId = undefined;
  }

  getCurrentSessionId(): string | undefined {
    return this.currentSessionId;
  }
}

// Usage example similar to Python - omitted for brevity

Security Considerations

Data Privacy

  • Session Isolation: User sessions are completely isolated
  • Message Encryption: All messages encrypted in transit and at rest
  • No Cross-User Access: Users cannot access other users' chat history

API Key Management

  • Secure Storage: API keys encrypted and securely stored
  • User-Specific Keys: Users can provide their own Google API keys
  • Fallback Handling: Graceful handling when API keys are missing or invalid

Error Handling

Common Error Responses

401 Unauthorized - Invalid or missing authentication

{
  "detail": "Could not validate credentials"
}

503 Service Unavailable - Google API key not configured

{
  "detail": "AI chat service unavailable - Google API key not configured. Please add your Google API key in settings."
}

500 Internal Server Error - Chat processing failed

{
  "detail": "Chat processing failed"
}

429 Too Many Requests - Rate limit exceeded

{
  "detail": "Rate limit exceeded. Please wait before sending another message."
}