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
Installation
Quick Start
Initialization and Service Access
SmartContractService Methods
generate_contract()
stream_contract()
get_chat_history()
Request and Response Models
SmartContractGeneratorRequestModel
SmartContractGeneratorResponseModel
GetChatHistoryResponseModel
Enums and Types
Error Handling
Complete Examples
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 instanceValueError: If the model field is not 'smart_contract_generator'APIError: For API-related errorsValidationError: 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 indicatorstatusCode(Optional[int]): HTTP status codemessage(Optional[str]): Response messagedata(SmartContractDataModel): Generated contract datauser(Optional[str]): The processed user promptbot(Optional[str]): The generated Solidity contract code
GetChatHistoryResponseModel
The response model for chat history retrieval.
Fields:
status(Optional[bool]): Success indicatorstatusCode(Optional[int]): HTTP status codemessage(str): Response messagedata(ChatHistoryDataModel): History datacount(int): Total available entriesrows(List[ChatHistoryEntryModel]): List of history entries
ChatHistoryEntryModel Fields:
id(str): Entry identifierquestion(str): User's promptanswer(str): AI's response (contract code)createdAt(str): Creation timestamptype(str): Entry typechatBot(ChatBotModel): Bot informationuser(UserModel): User informationsdkUniqueId(Optional[str]): Session identifiercontractAddress(Optional[str]): Deployed contract addresschainId(Optional[str]): Blockchain chain IDauditType(Optional[str]): Audit type if applicableauditMethod(Optional[str]): Audit method if applicablepromptId(Optional[str]): Prompt identifierchartData(Optional[Any]): Chart data if applicablechartType(Optional[str]): Chart type if applicablechartInterval(Optional[str]): Chart interval if applicabletrend(Optional[str]): Trend information if applicablechatFeedbacks(List[Any]): Feedback entries
Enums and Types
ChatHistoryMode
Controls chat history behavior:
ChatHistoryMode.ON("on"): Enables session-based chat historyChatHistoryMode.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 errorsAPIError: API-related errors with status codesValidationError: Request validation failuresAuthenticationError: 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 timeoutsStreamingError: Streaming-specific errorsConfigurationError: 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?