Chatbot API Integration Guide 1.0 Introduction to the Chatbot API This document provides a comprehensive, step-by-step walkthrough for developers integrating with the Chatbot API. The API is designed to provide interactive, AI-driven support through a managed chat session, featuring real-time streaming responses that create a dynamic and engaging user experience. The guide is structured to walk you through the entire integration process. We will begin with the foundational concepts of authentication and authorization, then move to a complete workflow that covers starting a chat, asking questions, and retrieving history. Finally, we provide detailed references for implementing the streaming protocol and handling all potential API errors, ensuring you can build a robust and reliable client application. We begin with the foundational topic of authentication, which secures every interaction with the API. 2.0 Core Concepts: Authentication and Authorization The API's authentication model is a critical component that ensures secure and appropriate access to its features. All API endpoints require successful authentication to identify the user. Furthermore, access to core chat functionalities is contingent on the user's support subscription status, ensuring that only eligible users can initiate conversations. 2.1 Authentication Mechanism The primary method of authentication is through an API token. Every request to the API must include the X-Auth-Token HTTP header, which contains the user's unique identifier (GUID). On the backend, this token is validated by the get_authenticated_user dependency, which retrieves the user's information and verifies their subscription status before allowing the request to proceed. 2.2 Support Subscription Validation For all core chat-related endpoints—specifically GET /chat/start-chat, POST /chat/, and GET /chat/—the system validates that the user has an active support subscription. This involves checking two key conditions: 1. The subscription has not expired. 2. The subscription has not been stopped (i.e., actively canceled). An "expired" subscription has passed its natural end date, while a "stopped" subscription indicates an active cancellation by the user or an administrator. If either of these conditions is not met, the API will reject the request with a 401 Unauthorized error. In contrast, the GET /user/support-info endpoint is an exception; it does not perform this validation, allowing even users with inactive or expired subscriptions to check their status. 2.3 Common Authentication Errors (401 Unauthorized) Failures during the authentication or authorization process will result in a 401 Unauthorized response. The following table details the common errors you may encounter. Error Error Code Cause Authentication failed. 10001 The X-Auth-Token header is missing, malformed, or the provided GUID does not correspond to a valid user. Your support has expired. 40001 The user's support subscription has passed its natural expiration date. The response context includes the support_expire_date. Your support has stopped. 40002 The user's support subscription was actively canceled or terminated. The response context includes the support_expire_date. Internal error in get_authenticated_user 50000 An unexpected server-side error occurred during the authentication process. With a clear understanding of authentication, we can now proceed to the practical steps required to build a complete chat client using the API's workflow. 3.0 The API Workflow: Building a Chat Client This section serves as a narrative guide to building a full-featured chat client. The following subsections will walk you through the logical sequence of API calls required to manage a complete user conversation, from initialization and interaction to retrieving the conversation history. 3.1 Step 1: Initiating a Chat Session (GET /chat/start-chat) The first step in any user interaction is to create a new chat session. This endpoint initializes the session on the server and streams back a personalized, word-by-word welcome message. Request Format Make a GET request to the /chat/start-chat endpoint, including the required X-Auth-Token header. Success Response A successful request returns a 200 OK response with a Content-Type of text/event-stream. The response body is a Server-Sent Events (SSE) stream, which delivers the welcome message in real-time. The stream consists of multiple chunk events, each containing a word, followed by a final done event to signal the end of the message. The JSON structure for the SSE events is as follows: The welcome message is personalized using data associated with the user's account. The placeholders %token1 and %token2 in the source message are replaced with the user's salon_name and persian_expire_date, respectively. Error Condition If the user already has an active chat session, the API will return a 400 Bad Request with error code 1007 ("You have an active session"). 3.2 Step 2: Asking a Question (POST /chat/) This endpoint is the core of the user interaction loop. The client sends the user's question, and the API streams back an AI-generated answer. Request Format Make a POST request to the /chat/ endpoint with the X-Auth-Token and Content-Type: application/json headers. The request body must conform to the following schema: - user_question_context (string, required) - The text of the user's question. - Validation: Must be between 2 and 500 characters. Cannot contain the characters !@#$%^\*\_+|<>. - similarity_threshold (float, optional) - A value between 0.0 and 1.0 that determines the relevance of information retrieved from the knowledge base. - Default: 0.35. Success Response A successful request returns a 200 OK response with a text/event-stream content type. Like the start-chat endpoint, the response is an SSE stream containing chunk events for the answer words and a final done event. Streamed Errors A unique feature of this endpoint is how it handles input validation and certain operational errors. Instead of returning a 40x status code, it returns a 200 OK and streams the error message within the SSE stream itself. This allows the client to handle feedback within the same logic used for displaying answers. Error Code Condition Streamed Message 1001 Question contains forbidden characters (`!@#$%^*_+ <>`). 1002 Question is missing required characters (if any). Question context must contain required characters 1003 Question is shorter than 2 characters. Question context must have at least 2 characters 1004 Question is longer than 500 characters. Question context exceeds maximum length of 500 characters 1005 No related answers found.
Note: This error is only raised for the user's first question in a session. سوال شما با هیچ یک از سوالات موجود در پایگاه داده مطابقت ندارد 1006 User's daily token limit has been exceeded. شما بیش از حد تعداد توکن های روزانه خود را استفاده کرده اید لطفا برای راهنمایی بیشتر تماس بگیرید N/A The backend OpenAI API is unavailable or has failed. ببخشید در حال حاضر قادر به پاسخگویی به شما نیستیم 3.3 Step 3: Retrieving Chat History (GET /chat/) This endpoint is used to retrieve the full conversation history for a user's active session. It is ideal for rehydrating a chat interface when a user reloads the page or launches the application, ensuring a seamless conversational context. Request Format Make a GET request to the /chat/ endpoint with the X-Auth-Token header. Success Response A successful request returns a 200 OK with a JSON payload conforming to the ChatSessionHistorySchemaResponse. The structure contains a list of all questions and their corresponding answers for the session. - message (string): A success message, e.g., "Chat session history retrieved successfully". - session_questions (list): A list of question objects. Each object follows the QuestionModelSchema: - id (integer): The unique ID of the question. - context (string): The text of the user's question. - open_ai_answers (list): A list of answer objects. Each object follows the OpenAiAnswerModelSchema: - id (integer): The unique ID of the answer. - context (string): The AI-generated answer text. This endpoint handles multiple scenarios gracefully. The backend uses a lazy initialization pattern within its UserSessionBase class; if a user has no active session, the API transparently creates a new one before returning an empty response. This makes the endpoint's behavior idempotent and simplifies client logic. For performance, relationships are loaded using a selectin strategy to prevent N+1 query problems when fetching answers for multiple questions. 3.4 Optional Step: Checking User Status (GET /user/support-info) Before initiating a chat, it is highly recommended to check the user's status. This endpoint provides a comprehensive summary of a user's support subscription, token usage, and current session state, allowing the client application to make informed decisions. Success Response A successful GET request returns a 200 OK with a JSON payload containing detailed user information. Key fields for a client application include: - has_support (boolean): true if the user's support subscription is currently active (not expired and not stopped). - daily_remaining_token (integer): The number of API tokens the user has left for the day. - has_active_chat_session (boolean): true if the user already has an active chat session. - support_remaining_days_count (integer): The number of days left on the support subscription. - support_expire_date (datetime): The ISO 8601 timestamp for when the support expires. - date_of_not_support (datetime | null): The timestamp for when support was stopped (if applicable). - has_stopped_support_subscription (boolean): true if support was actively canceled. - persian_expire_date (string): The support expiration date in Persian format. - salon_name (string): The user's registered salon name. Crucially, this endpoint returns information even for users with an inactive or expired support subscription, making it a reliable tool for checking status under any condition. Client-Side Logic Guidance The response from this endpoint should drive your application's UI and workflow. For example: - Use the has_support flag to enable or disable the chat functionality in your UI. - Use the has_active_chat_session flag to determine whether your application should next call GET /chat/ (to rehydrate the UI with existing messages) or GET /chat/start-chat (to begin a new conversation). Having walked through the complete API workflow, we will now take a closer look at the streaming technology that powers the core interactions. 4.0 Implementing Streaming with Server-Sent Events (SSE) Two of the core API endpoints—start-chat and POST /chat/—use Server-Sent Events (SSE) to deliver real-time, streaming responses. A solid understanding of how to consume these streams is critical for a successful integration. This section consolidates best practices and provides client-side examples for handling the API's SSE responses. For optimal real-time delivery, the API uses the X-Accel-Buffering: no header to prevent intermediate buffering by proxies like nginx and streams words with a 50ms delay to create a natural reading pace. 4.1 SSE Stream Structure An SSE message from the Chatbot API follows a simple, consistent structure. Each message begins with a data: prefix, followed by a JSON object, and is terminated by two newline characters (\n\n). The API uses two types of events, distinguished by the type field in the JSON payload: 4.2 Client-Side Implementation Examples The following code snippets provide practical templates for handling SSE streams from the Chatbot API in both JavaScript/TypeScript and Python environments. JavaScript/TypeScript Example (using fetch and ReadableStream) /\*\* - NOTE: This is a simplified example. A production-ready implementation - should use a more robust SSE parsing library or custom logic to handle - cases where a single data chunk from the stream contains partial or - multiple SSE messages. The simple `split` approach below may fail in - these edge cases. \*/ async function startChat(authToken) { const response = await fetch('/chat/start-chat', { method: 'GET', headers: { 'X-Auth-Token': authToken, 'Accept': 'text/event-stream' } }); if (!response.ok) { const error = await response.json(); console.error('Error:', error); return; } const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); const lines = chunk.split('\n\n'); for (const line of lines) { if (line.startsWith('data: ')) { try { const data = JSON.parse(line.substring(6)); if (data.type === 'chunk') { // Append data.content to your UI console.log(data.content); } else if (data.type === 'done') { console.log('Stream completed'); } } catch (e) { console.error('Failed to parse SSE data chunk:', line); } } } } } Python Example (using requests) import requests import json def start_chat(auth_token): url = "https://api.example.com/chat/start-chat" headers = { "X-Auth-Token": auth_token, "Accept": "text/event-stream" } response = requests.get(url, headers=headers, stream=True) if response.status_code != 200: error = response.json() print(f"Error: {error}") return for line in response.iter_lines(): if line: line_str = line.decode('utf-8') if line_str.startswith('data: '): data = json.loads(line_str[6:]) if data['type'] == 'chunk': print(data['content'], end='', flush=True) elif data['type'] == 'done': print(f"\n{data['message']}") Understanding how to handle successful streams is key, but it is equally important to manage potential errors gracefully. 5.0 Comprehensive Error Handling Guide Robust error handling is essential for creating a reliable and user-friendly client application. This section provides a centralized reference for all potential error responses from the API, ensuring you can anticipate and manage failures effectively. 5.1 Standard Error Response Format For most non-200 HTTP responses (typically 400 and 401 errors), the API returns a standardized JSON error object with a messages (plural) key. { "messages": "A descriptive error message.", "error_code": 10001, "context": { "support_expire_date": "...", "error": "Additional details..." } } Format Variations Be aware of two important variations for 500 Internal Server Error responses: 1. Most 500 errors use a message (singular) key: 2. The GET /chat/ (chat history) endpoint nests its 500 error object under a detail key: 5.2 Error Code Reference The following table serves as a quick reference for all documented API errors, grouped by HTTP status code. HTTP Status Error Code Message Common Cause / Resolution 400 Bad Request 1007 You have an active session Occurs when calling GET /chat/start-chat while a chat session is already active for the user. 401 Unauthorized 10001 Authentication failed. The X-Auth-Token is missing, invalid, or the user GUID does not exist. 401 Unauthorized 40001 Your support has expired. The user's support subscription has passed its expiration date. Check the support_expire_date in the response context. 401 Unauthorized 40002 Your support has stopped. The user's support subscription was actively canceled. Check the support_expire_date in the response context. 500 Internal Server Error 50000 Internal error... or Error in... An unexpected server-side error occurred, such as a database issue or unhandled exception. The message provides details. Note on Streamed Errors: As detailed in Section 3.2, the POST /chat/ endpoint handles input validation and certain operational errors by streaming them with a 200 OK status, rather than returning a standard HTTP error code. Refer to that section for a complete list of those specific error messages. With the information provided in this guide, you have all the necessary components to build a robust and full-featured integration with the Chatbot API.