CG

Python

Updated May 29, 2026, 12:30 PM


description: CGPT SDK Docs

Python

AI Chatbot & LLM SDK Documentation

The ChainGPT AI Chatbot & LLM feature allows you to integrate powerful conversational AI capabilities into your applications. You can send prompts, manage chat history, and customize the AI's responses using context injection.

Table of Contents

  1. Installation
  2. Quick Start
  3. ChainGPTClient Parameters
  4. LLM Service
    • LLMChatRequestModel Parameters
    • Basic LLM Usage
      • Buffered Chat (Complete Response)
      • Streaming Chat (Real-time Response)
  5. Context Injection
    • ContextInjectionModel Parameters
    • TokenInformationModel Parameters
    • SocialMediaUrlModel Parameters
    • Context Injection Example
  6. Enums and Constants
    • ChatHistoryMode
    • AITone Options
    • PresetTone Options
    • Supported Blockchain Networks
  7. Error Handling
    • Exception Types
    • Error Handling Example
  8. Complete Example
  9. Best Practices

Installation

Install via pip:

pip install chaingpt

Or add to your requirements.txt:

chaingpt>=1.1.3

Quick Start

Basic Client Initialization

client = ChainGPTClient(api_key=API_KEY)

# Always remember to close the client
await client.close()

# Or use as context manager (recommended)
async with ChainGPTClient(api_key=API_KEY) as client:
    # Your code here
    pass

ChainGPTClient Parameters

ParameterTypeDefaultDescription
api_keystrRequiredYour ChainGPT API key
base_urlstr"https://api.chaingpt.org"The base URL for the ChainGPT API
timeoutHTTPTimeoutDEFAULT_TIMEOUTDefault timeout for regular requests (seconds)
stream_timeoutHTTPTimeoutDEFAULT_STREAM_TIMEOUTDefault timeout for streaming requests (seconds)

LLM Service

The LLM service provides both buffered (complete response) and streaming chat capabilities.

LLMChatRequestModel Parameters

ParameterTypeDefaultDescription
modelstr"general_assistant"Model ID to use (currently only "general_assistant" supported)
questionstrRequiredUser's question or prompt (1-10,000 characters)
chat_historyChatHistoryModeChatHistoryMode.OFFEnable/disable chat history (ON or OFF)
sdk_unique_idstrNoneUnique session identifier (1-100 characters)
use_custom_contextboolFalseWhether to use custom context injection
context_injectionContextInjectionModelNoneCustom context data (required if use_custom_context=True)

Basic LLM Usage

Buffered Chat (Complete Response)

from chaingpt.models import LLMChatRequestModel
from chaingpt.types import ChatHistoryMode

async def buffered_chat_example():
    client = ChainGPTClient(api_key=API_KEY)
    try:
        request = LLMChatRequestModel(
            question="What is blockchain technology?",
            chatHistory=ChatHistoryMode.OFF
        )
        response = await client.llm.chat(request)
        print(response.data.bot)
    finally:
        await client.close()

Streaming Chat (Real-time Response)

async def streaming_chat_example():
    client = ChainGPTClient(api_key=API_KEY)
    try:
        request = LLMChatRequestModel(
            question="Explain smart contracts in detail",
            chatHistory=ChatHistoryMode.ON,
            sdkUniqueId="unique-session-123"
        )

        print("AI Response:")
        async for chunk in client.llm.stream_chat(request):
            print(chunk.decode("utf-8"), end="", flush=True)
        print("\n--- Stream ended ---")
    finally:
        await client.close()

Context Injection

Context injection allows you to customize the AI's responses with specific company, project, or token information.

ContextInjectionModel Parameters

ParameterTypeDefaultDescription
company_namestrNoneCompany or project name
company_descriptionstrNoneBrief description of the company/project
company_website_urlHttpUrlNoneCompany website URL
white_paper_urlHttpUrlNoneWhitepaper URL
purposestrNonePurpose or role of the AI chatbot
crypto_tokenboolNoneWhether the project has a crypto token
token_informationTokenInformationModelNoneToken details (required if crypto_token=True)
social_media_urlsList[SocialMediaUrlModel]NoneSocial media URLs
limitationboolNoneContent limitation flag
ai_toneAIToneNoneAI tone setting
selected_tonePresetToneNoneSelected preset tone (required if ai_tone=PRE_SET_TONE)
custom_tonestrNoneCustom tone description (required if ai_tone=CUSTOM_TONE)

TokenInformationModel Parameters

ParameterTypeDefaultDescription
token_namestrNoneName of the token
token_symbolstrNoneToken symbol/ticker
token_addressstrNoneToken contract address
token_source_codestrNoneToken source code or repository URL
token_audit_urlHttpUrlNoneURL to token audit report
explorer_urlHttpUrlNoneBlock explorer URL for the token
cmc_urlHttpUrlNoneCoinMarketCap URL
coingecko_urlHttpUrlNoneCoinGecko URL
blockchainList[BlockchainNetwork]NoneList of supported blockchain networks

SocialMediaUrlModel Parameters

ParameterTypeDefaultDescription
namestrRequiredName of the social media platform
urlHttpUrlRequiredURL to the social media profile

Context Injection Example

from chaingpt.models import (
    LLMChatRequestModel,
    ContextInjectionModel,
    TokenInformationModel,
    SocialMediaUrlModel
)
from chaingpt.types import AITone, PresetTone, BlockchainNetwork

async def context_injection_example():
    client = ChainGPTClient(api_key=API_KEY)
    try:
        # Define token information
        token_info = TokenInformationModel(
            tokenName="MyAwesomeToken",
            tokenSymbol="MAT",
            blockchain=[BlockchainNetwork.ETHEREUM, BlockchainNetwork.POLYGON]
        )

        # Define social media
        social_media = [
            SocialMediaUrlModel(
                name="twitter",
                url="https://twitter.com/myawesometoken"
            ),
            SocialMediaUrlModel(
                name="telegram",
                url="https://t.me/myawesometoken"
            )
        ]

        # Create context injection
        context = ContextInjectionModel(
            companyName="Awesome Crypto Inc.",
            companyDescription="Leading DeFi protocol for yield farming",
            cryptoToken=True,
            tokenInformation=token_info,
            socialMediaUrls=social_media,
            aiTone=AITone.PRE_SET_TONE,
            selectedTone=PresetTone.PROFESSIONAL
        )

        # Make request with context
        request = LLMChatRequestModel(
            question="Tell me about our token and its utilities",
            useCustomContext=True,
            contextInjection=context,
            sdkUniqueId="context-session-456"
        )

        response = await client.llm.chat(request)
        print(response.data.bot)
    finally:
        await client.close()

Enums and Constants

ChatHistoryMode

  • ChatHistoryMode.ON: Enable chat history
  • ChatHistoryMode.OFF: Disable chat history

AITone Options

  • AITone.DEFAULT_TONE: Use default AI tone
  • AITone.CUSTOM_TONE: Use custom tone (requires custom_tone parameter)
  • AITone.PRE_SET_TONE: Use preset tone (requires selected_tone parameter)

PresetTone Options

ToneDescription
PROFESSIONALProfessional business tone
FRIENDLYCasual and friendly tone
INFORMATIVEEducational and detailed tone
FORMALFormal and structured tone
CONVERSATIONALNatural conversation tone
AUTHORITATIVEExpert and confident tone
PLAYFULLight and entertaining tone
INSPIRATIONALMotivational and uplifting tone
CONCISEBrief and to-the-point tone
EMPATHETICUnderstanding and caring tone
ACADEMICScholarly and research-focused tone
NEUTRALBalanced and objective tone
SARCASTIC_MEME_STYLEHumorous and meme-like tone

Supported Blockchain Networks

NetworkValue
EthereumETHEREUM
Binance Smart ChainBSC
ArbitrumARBITRUM
BaseBASE
BlastBLAST
AvalancheAVALANCHE
PolygonPOLYGON
ScrollSCROLL
OptimismOPTIMISM
LineaLINEA
zkSyncZKSYNC
Polygon zkEVMPOLYGON_ZKEVM
GnosisGNOSIS
FantomFANTOM
MoonriverMOONRIVER
MoonbeamMOONBEAM
BobaBOBA
MetisMETIS
LiskLISK
AuroraAURORA
SeiSEI
Immutable zkEVMIMMUTABLE_ZK
GravityGRAVITY
TaikoTAIKO
CronosCRONOS
FraxtalFRAXTAL
AbstractABSTRACT
World ChainWORLD_CHAIN
MantleMANTLE
ModeMODE
CeloCELO
BerachainBERACHAIN

Error Handling

The SDK provides comprehensive error handling with specific exception types:

Exception Types

ExceptionDescriptionWhen Raised
ChainGPTErrorBase exception for all SDK errorsGeneral SDK errors
APIErrorAPI returned an error responseAPI-specific errors
AuthenticationErrorAuthentication failed (401)Invalid API key
ValidationErrorRequest validation failed (400)Invalid request parameters
InsufficientCreditsErrorAccount has insufficient credits (402/403)No credits remaining
RateLimitErrorRate limit exceeded (429)Too many requests
NotFoundErrorEndpoint not found (404)Invalid endpoint
ServerErrorServer error (5xx)API server issues
TimeoutErrorRequest timed outNetwork timeout
StreamingErrorStreaming encountered an errorStreaming-specific issues
ConfigurationErrorSDK configuration is invalidInvalid configuration

Error Handling Example

from chaingpt.exceptions import (
    ChainGPTError,
    AuthenticationError,
    ValidationError,
    RateLimitError
)

async def error_handling_example():
    client = ChainGPTClient(api_key=API_KEY)
    try:
        request = LLMChatRequestModel(
            question="What is DeFi?",
            chatHistory=ChatHistoryMode.OFF
        )
        response = await client.llm.chat(request)
        print(response.data.bot)

    except AuthenticationError:
        print("Authentication failed. Please check your API key.")
    except ValidationError as e:
        print(f"Validation error: {e.message}")
        if e.field:
            print(f"Field: {e.field}")
    except RateLimitError as e:
        print(f"Rate limit exceeded: {e.message}")
        if e.retry_after:
            print(f"Retry after: {e.retry_after} seconds")
    except ChainGPTError as e:
        print(f"ChainGPT error: {e.message}")
        if e.details:
            print(f"Details: {e.details}")
    except Exception as e:
        print(f"Unexpected error: {e}")
    finally:
        await client.close()

Complete Example

Here's a comprehensive example demonstrating various features:

import asyncio
import os
from chaingpt.client import ChainGPTClient
from chaingpt.models import (
    LLMChatRequestModel,
    ContextInjectionModel,
    TokenInformationModel,
    SocialMediaUrlModel,
)
from chaingpt.types import AITone, PresetTone, ChatHistoryMode, BlockchainNetwork
from chaingpt.exceptions import ChainGPTError

async def comprehensive_example():
    API_KEY = os.getenv("CHAINGPT_API_KEY")

    if not API_KEY:
        print("Please set your CHAINGPT_API_KEY environment variable")
        return

    async with ChainGPTClient(api_key=API_KEY) as client:
        try:
            # Example 1: Simple chat
            print("=== Simple Chat ===")
            simple_request = LLMChatRequestModel(
                question="Explain blockchain in simple terms"
            )
            response = await client.llm.chat(simple_request)
            print(response.data.bot)

            # Example 2: Chat with context injection
            print("\n=== Chat with Context ===")
            token_info = TokenInformationModel(
                tokenName="DemoToken",
                tokenSymbol="DEMO",
                blockchain=[BlockchainNetwork.ETHEREUM]
            )

            context = ContextInjectionModel(
                companyName="Demo Company",
                companyDescription="Blockchain innovation company",
                cryptoToken=True,
                tokenInformation=token_info,
                aiTone=AITone.PRE_SET_TONE,
                selectedTone=PresetTone.PROFESSIONAL
            )

            context_request = LLMChatRequestModel(
                question="What can you tell me about our company?",
                useCustomContext=True,
                contextInjection=context,
                chatHistory=ChatHistoryMode.ON,
                sdkUniqueId="demo-session-123"
            )

            response = await client.llm.chat(context_request)
            print(response.data.bot)

            # Example 3: Streaming chat
            print("\n=== Streaming Chat ===")
            stream_request = LLMChatRequestModel(
                question="Tell me about DeFi protocols",
                chatHistory=ChatHistoryMode.ON,
                sdkUniqueId="demo-session-123"  # Continue same session
            )

            print("Streaming response:")
            async for chunk in client.llm.stream_chat(stream_request):
                print(chunk.decode("utf-8"), end="", flush=True)
            print("\n--- Stream complete ---")

        except ChainGPTError as e:
            print(f"Error: {e}")

if __name__ == "__main__":
    asyncio.run(comprehensive_example())

Best Practices

  1. Always use context managers or remember to call close() to properly clean up resources
  2. Handle exceptions appropriately - use specific exception types for better error handling
  3. Use unique session IDs when maintaining chat history across multiple requests
  4. Validate context injection - ensure required fields are provided when using custom context
  5. Consider rate limits - implement retry logic with exponential backoff for production use
  6. Use streaming for long responses - better user experience for lengthy AI responses
  7. Store API keys securely - use environment variables, not hardcoded values

This concludes the documentation for the AI Chatbot & LLM feature!

View original source