Python

CGPT SDK Docs Python

Smart Contract Generator SDK Documentation

The ChainGPT Smart Contract Generator allows you to generate Solidity smart contracts based on textual descriptions or prompts. It supports both immediate (buffered) responses and streaming for real-time code generation, along with comprehensive chat history management for maintaining conversation context across sessions.

Table of Contents

  1. Installation

  2. Quick Start

  3. Initialization and Service Access

  4. SmartContractService Methods

    • generate_contract()

    • stream_contract()

    • get_chat_history()

  5. Request and Response Models

    • SmartContractGeneratorRequestModel

    • SmartContractGeneratorResponseModel

    • GetChatHistoryResponseModel

  6. Enums and Types

  7. Error Handling

  8. Complete Examples

  9. Best Practices


Installation

Install the ChainGPT SDK via pip:

Or add to your requirements.txt:


Quick Start


Initialization and Service Access

Basic Setup

Environment Setup (Optional)

For development, you can use a .env file:


SmartContractService Methods

The SmartContractService provides three main methods for smart contract generation and history management.

generate_contract()

Generates a complete smart contract based on your prompt and returns the full response immediately.

Method Signature:

Parameters:

  • request_data (SmartContractGeneratorRequestModel): The request configuration containing the prompt and settings

Returns:

  • SmartContractGeneratorResponseModel: Complete response with generated contract code

Raises:

  • TypeError: If request_data is not a SmartContractGeneratorRequestModel instance

  • ValueError: If the model field is not 'smart_contract_generator'

  • APIError: For API-related errors

  • ValidationError: For request validation errors

Example:

stream_contract()

Generates a smart contract and streams the response in real-time, allowing you to display the generated code as it's being created.

Method Signature:

Parameters:

  • request_data (SmartContractGeneratorRequestModel): The request configuration

Returns:

  • AsyncIterator[StreamChunk]: Async iterator yielding chunks of generated content

Yields:

  • StreamChunk: Raw bytes that need to be decoded (typically UTF-8)

Raises:

  • Same exceptions as generate_contract()

  • StreamingError: For streaming-specific errors

Example:

get_chat_history()

Retrieves the chat history for smart contract generation sessions, including past prompts and generated contracts.

Method Signature:

Parameters:

  • limit (Optional[int]): Maximum number of entries to return (default: 10)

  • offset (Optional[int]): Number of entries to skip for pagination (default: 0)

  • sort_by (Optional[str]): Field to sort by (default: "createdAt")

  • sort_order (Optional[str]): Sort order - "asc" or "desc" (default: "desc")

Returns:

  • GetChatHistoryResponseModel: Response containing history entries and metadata

Example:


Request and Response Models

SmartContractGeneratorRequestModel

The request model for smart contract generation.

Fields:

  • model (Literal["smart_contract_generator"]): Required. Must be "smart_contract_generator"

  • question (str): Required. Your prompt describing the contract (min length: 1)

  • chatHistory (Optional[ChatHistoryMode]): Chat history mode (default: ChatHistoryMode.OFF)

  • sdkUniqueId (Optional[str]): Session identifier for chat history (1-100 characters, required if chatHistory is ON)

Example:

SmartContractGeneratorResponseModel

The response model for contract generation.

Fields:

  • status (bool): Success indicator

  • statusCode (Optional[int]): HTTP status code

  • message (Optional[str]): Response message

  • data (SmartContractDataModel): Generated contract data

    • user (Optional[str]): The processed user prompt

    • bot (Optional[str]): The generated Solidity contract code

GetChatHistoryResponseModel

The response model for chat history retrieval.

Fields:

  • status (Optional[bool]): Success indicator

  • statusCode (Optional[int]): HTTP status code

  • message (str): Response message

  • data (ChatHistoryDataModel): History data

    • count (int): Total available entries

    • rows (List[ChatHistoryEntryModel]): List of history entries

ChatHistoryEntryModel Fields:

  • id (str): Entry identifier

  • question (str): User's prompt

  • answer (str): AI's response (contract code)

  • createdAt (str): Creation timestamp

  • type (str): Entry type

  • chatBot (ChatBotModel): Bot information

  • user (UserModel): User information

  • sdkUniqueId (Optional[str]): Session identifier

  • contractAddress (Optional[str]): Deployed contract address

  • chainId (Optional[str]): Blockchain chain ID

  • auditType (Optional[str]): Audit type if applicable

  • auditMethod (Optional[str]): Audit method if applicable

  • promptId (Optional[str]): Prompt identifier

  • chartData (Optional[Any]): Chart data if applicable

  • chartType (Optional[str]): Chart type if applicable

  • chartInterval (Optional[str]): Chart interval if applicable

  • trend (Optional[str]): Trend information if applicable

  • chatFeedbacks (List[Any]): Feedback entries


Enums and Types

ChatHistoryMode

Controls chat history behavior:

  • ChatHistoryMode.ON ("on"): Enables session-based chat history

  • ChatHistoryMode.OFF ("off"): Disables chat history

StreamChunk

Type for streaming data:

  • StreamChunk = Union[str, bytes]: Raw chunk data from streaming responses

Usage Example


Error Handling

The SDK provides comprehensive error handling with specific exception types:

Exception Hierarchy

  • ChainGPTError: Base exception for all SDK errors

    • APIError: API-related errors with status codes

    • ValidationError: Request validation failures

    • AuthenticationError: Invalid API key (401)

    • InsufficientCreditsError: Account credit issues (402/403)

    • RateLimitError: Rate limiting (429)

    • NotFoundError: Endpoint not found (404)

    • ServerError: Server errors (5xx)

    • TimeoutError: Request timeouts

    • StreamingError: Streaming-specific errors

    • ConfigurationError: SDK configuration issues

Comprehensive Error Handling Example


Complete Examples

Example 1: Session-Based Contract Development

Example 2: Batch Contract Generation


Best Practices

1. Session Management

  • Use meaningful, unique session IDs (UUID format recommended)

  • Enable chat history for iterative development

  • Keep sessions focused on related functionality

2. Prompt Engineering

  • Be specific about contract requirements

  • Include token standards (ERC20, ERC721, etc.)

  • Specify security features needed

  • Mention deployment considerations

3. Error Handling Strategy

  • Always wrap SDK calls in try-except blocks

  • Handle specific exception types appropriately

  • Log errors for debugging

  • Implement retry logic for transient errors

4. Resource Management

  • Always close the client properly

  • Use context managers for automatic cleanup

  • Monitor API usage and credits

5. Code Organization

  • Separate contract generation logic into dedicated functions

  • Use configuration objects for repeated settings

  • Implement proper logging

This comprehensive documentation should provide developers with everything they need to effectively use the ChainGPT Smart Contract Generator SDK, from basic usage to advanced patterns and best practices.

Last updated

Was this helpful?