Overview
The AI utilities module provides three main functions for interacting with Google’s Gemini API, each optimized for different use cases in Africa’s Talking applications.Core Functions
ask_gemini()
Generate plain text responses from Gemini.prompt(str) - The question or instruction to send to Geminimodel(str, optional) - The model to use (defaults toDEFAULT_MODEL)
str- Plain text response from Gemini
- SMS auto-replies
- Chatbot responses
- General Q&A
- Content generation
ask_gemini_as_xml()
Generate XML-formatted responses for Voice and USSD APIs.prompt(str) - The question or instruction to send to Geminimodel(str, optional) - The model to use (defaults toDEFAULT_MODEL)root_tag(str, optional) - The XML root element name (defaults to"Response")
str- XML-formatted response with<?xml>declaration
- Voice API callbacks
- IVR responses
- Dynamic call flows
- Text-to-speech content
ask_gemini_structured()
Generate structured responses in JSON, XML, or custom formats.prompt(str) - The question or instruction to send to Geminimodel(str, optional) - The model to use (defaults toDEFAULT_MODEL)output_format(str, optional) - Desired format:"json","xml", or custom (defaults to"json")
str- Structured response in the requested format
- USSD menu generation
- API integrations
- Data extraction
- Structured content creation
Retry Logic & Error Handling
All functions use the internal_call_gemini() helper with built-in retry logic:
utils/ai_utils.py
Features:
- Automatic Retries - Up to 3 attempts by default
- Exponential Backoff - Delays increase with each retry (2s, 4s, 6s)
- Error Logging - Prints warning messages for failed attempts
- Multiple Exception Types - Handles
GoogleAPIError,ValueError, and general exceptions - Empty Response Detection - Validates that response contains text
Error Handling Best Practices
Production Usage
For production applications, consider:Configuration Reference
DEFAULT_MODEL
Configured inutils/ai_utils.py:
- Environment variable:
MODEL_ID=gemini-2.0-pro - Function parameter:
ask_gemini(prompt, model="gemini-2.0-pro")
Next Steps
Gemini Setup
Configure API credentials and environment
Real-World Examples
See AI integration with SMS, Voice, and USSD
