PyGai Connector API Technical Documentation

The PyGai Connector API is designed to act as a bridge between AI generation services and the Gai application, providing data interaction capabilities. Core API interfaces include fetching AI generation tasks (T1) and submitting AI generation results (T2). Auxiliary function APIs include resetting prompt instruction status (T4) and obtaining JWT (T5). T3 describes the post-processing flow after result submission, which is closely related to the PyGaiCustomize mechanism, detailing the system's extensibility methods.

All API responses adhere to the JSend standard. For users with programming experience, HTTP-related terminology (e.g., URL, Header, Params, Body, Status) is kept in English throughout the document.

Core Data Entity Overview

To deeply understand the PyGai Connector API, it's essential to grasp its underlying data model. Below are brief definitions of the main data tables (for detailed fields, refer to docs\pygai.sql):

  • Website Directory Table (gaiDirectory): Records the page storage directory for each static website.
  • Time Expression Table (gaiInterval): Stores commonly used Cron format time expressions.
  • Configuration Parameter Table (gaiConfig): Records common AI model and parameter settings.
  • System Instruction Table (gaiInstruction): Stores custom system instructions or prompt prefixes.
  • Topic Category Table (gaiTopic): Used to organize and manage related matters or content topics.
  • Prompt Instruction Table (gaiPrompt): Predefined prompt instructions used in PyGai. For easier management, it is recommended to associate with the following data: intervalId (gaiInterval.id), configId (gaiConfig.id), topicId (gaiTopic.id), instId (gaiInstruction.id), dirId (gaiDirectory.id).
  • Generated Content Table (gaiContent): Records AI-generated submitted content.
  • Publish Record Table (gaiPublish): Records the publishing history of gaiContent converted into static files.

This connector natively supports website building functionality, i.e., generating rich-media static web content through AI.

T1-Retrieve AI Generation Task

This interface is used to retrieve a prompt instruction and associated configuration from the PyGai Connector, which can be used by an AI model to generate content.

  • Method: GET
  • Url: {{host}}/aiprompt/output/
  • Header:
    • Authorization: Bearer {{token}}
  • Query Parameters: (for filtering prompt instructions)
    • id: int, optional, corresponds to gaiPrompt.id.
    • intervalId: int, optional, corresponds to gaiPrompt.intervalId.
    • topicId: int, optional, corresponds to gaiPrompt.topicId.
    • dirId: int, optional, corresponds to gaiPrompt.dirId.
Response Data data Field Structure (AI Generation Task Payload)
Name Type Required Description
id int Y Unique ID of the prompt instruction (gaiPrompt.id).
type string Y Generation type: gentxt (generate text), genimg (generate image).
text string Y Prompt text.
files list<string> Y Array of attached file URLs; an empty array if none.
instId int N System instruction ID (gaiInstruction.id).
instName string N System instruction name.
instText string N System instruction text.
config dict N AI model generation parameters.
Response Example (Successfully fetched text generation task, no system instruction, no parameter setting [uses application-side parameters if none])
  • Status: 200 OK
  • Body:

    json { "status": "success", "data": { "id": 1, "type": "gentxt", "text": "Essay Prompt: Live for Today, Let Tomorrow's Troubles Wait. Write an essay of any style (minimum 500 words) on this theme.", "files": [] } }

T2-Submit AI Generation Result

This interface is used to submit AI-generated rich-media content back to the PyGai Connector for storage and potential post-processing.

  • Method: POST
  • Url: {{host}}/aicontent/input/
  • Header:
    • Authorization: Bearer {{token}}
    • Content-Type: application/json
  • Query Parameters:
    • writetofile: bool, optional. If set to true (which includes 1 or any non-empty/non-zero string in the URL for boolean interpretation), then after recording the content to the gaiContent table, the system will further record publishing information in the gaiPublish table and generate static files.
Request Data data Field Structure (Submission Content Payload)
Name Type Required Description
id string Y External unique identifier, defaults to an empty string.
text string Y AI-generated text content.
files list<string> Y Array of URLs for AI-generated files; an empty array if none.
cronId string Y Application-side scheduled task ID.
histId string Y Application-side log ID.
promptId string Y Corresponding prompt instruction ID (gaiPrompt.id), associated with the id returned by the T1 interface.
Request Example
{
    "status": "success",
    "data": {
        "id": "",
        "text": "Rain streaked diagonally outside, tapping a soft patter against the windowpane. I gazed out, my thoughts drifting as aimlessly as the drops...",
        "cronId": "_CRON-Daily_Writing_Prompt-Live_for_Today",
        "histId": "L-GTXT-1731317840133187",
        "promptId": "2",
        "files": [
            "http://localhost:8080/genimgs/139473250698292130.png"
        ]
    }
}
Response Example (Successfully submitted, no content requires client-side processing)
  • Status: 200 OK
  • Body:

    json { "status": "success", "data": { } }

T3-Content Post-processing and PyGai Extension Mechanism

Upon successful submission of AI generation results, the system triggers content post-processing logic. PyGai provides a flexible extension mechanism (PyGaiCustomize), allowing developers to override or enhance default system functionalities through custom logic, achieving clean code separation and feature expansion.

Content Post-processing Flow Example

The following code snippet illustrates the system's default content publishing (publish) flow:

# ~/Projects/pygai/gai/content.py

from gai.publish import publish

contentId: int = 1 # Example content ID
publishId = publish(contentId) # Calls the publish function to trigger post-processing

PyGai Extension Mechanism (PyGaiCustomize)

The PyGai extension mechanism is implemented by searching for same-named functions within a specific path. For instance, when the system calls the gai.publish.publish method, it first attempts to load the publishHandler method from the corresponding gai/publish.py file within the extension path (~/Projects/pygaiext/). If found and enabled, the extension logic will be executed instead of the system's default logic.

Project Structure Example:

  • Application Path: ~/Projects/pygai/
  • Extension Path: ~/Projects/pygaiext/

System Default Logic (~/Projects/pygai/gai/publish.py):

# ~/Projects/pygai/gai/publish.py

# Imports the extension method utility
from pygai.ext import extMethod

def publish(contentId: int, reWrite: bool = False) -> None | int:
    """
    Main publish function that can be extended.
    It checks for a custom handler in the extension path.
    """
    extPublishHandler = extMethod('gai/publish', 'publishHandler')
    # If a custom handler exists in the extension path, use it; otherwise, use the default publishHandler.
    return extPublishHandler(contentId, reWrite) if extPublishHandler else publishHandler(contentId, reWrite)

def publishHandler(contentId: int, reWrite: bool = False) -> None | int:
    """
    Default content publish logic.
    This function handles the default actions like recording to gaiPublish and generating static files.
    """
    # Default implementation, e.g., generating static files based on contentId
    pass

Custom Extension Logic (~/Projects/pygaiext/gai/publish.py):

By creating a file and function with the same name in the extension path, default behavior can be overridden:

# ~/Projects/pygaiext/gai/publish.py

def publishHandler(contentId: int, reWrite: bool = False) -> None | int:
    """
    Custom content publish logic.
    This function will be executed instead of the default one if the extension is enabled.
    """
    # print(f'pygaiext/gai/publish.py, publishHandler, contendId:{contentId}, reWrite:{reWrite}')
    # Add your custom publishing logic here, e.g., integrating with a CMS,
    # triggering webhooks, or advanced static site generation.
    pass

List of Extensible System Methods

Below are the key methods in PyGai that can be extended:

  • promptHandler: located in pygai\gai\prompt.py.
  • resetHandler: located in pygai\gai\prompt.py.
  • contentHandler: located in pygai\gai\content.py.
  • publishHandler: located in pygai\gai\publish.py.

Brief Description of Extension Use Cases

Through the extension capabilities provided by PyGai, developers can easily achieve various customized integrations and feature enhancements based on specific business requirements. For example:

  • Content Management System (CMS) Integration: Add logic to publishHandler to automatically synchronize AI-generated static web content to an existing CMS platform.
  • Social Interaction Features: Through extension capabilities, features like adding comments to products or articles, or replying to comments, can be implemented.
  • Multilingual Support: Extend promptHandler or contentHandler to add language detection and translation processing logic when fetching or submitting content.
  • Third-Party Service Integration: After content generation or publication, trigger Webhooks to notify other systems (e.g., email marketing, message push services).
  • Advanced Data Analytics: Embed data analytics code within contentHandler for real-time monitoring and statistics of generated content.

T4-Reset Prompt Instruction Status

This interface is used to reset the status of used prompt instructions, making them available again. When a prompt instruction is used for content generation and successfully submitted back, its available count typically decreases (disabled if 0), and the return data ID and time are recorded. This API clears these markers and restores its available status, allowing scheduled tasks to poll and use the prompt instruction again.

  • Method: GET
  • Url: {{host}}/aiprompt/reset/
  • Header:
    • Authorization: Bearer {{token}}
Response Example (Successfully Reset)
  • Status: 200 OK
  • Body:

    json { "status": "success", "data": { } }


T5-Obtain JSON Web Token (JWT)

This interface is used for user authentication. Upon successful authentication, it returns a JWT, which can then be used to access all protected PyGai API interfaces.

  • Method: POST
  • Url: {{host}}/signin
  • Header:
    • Content-Type: application/x-www-form-urlencoded
  • Request Body (Form Data):
    • username: {{email}} (User email)
    • password: {{passwd}} (User password)
Response Example (Successfully Obtained JWT)
  • Status: 200 OK
  • Body:

    json { "status": "success", "data": { "jwt": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9..." } }