πŸ“Š View Lecture Slides Full-screen presentation with navigation

Session 7: API Integration & Cloud Models

Session Duration: 2 Hours     Block: 2 β€” AI-Assisted Engineering & Integration

Learning Objectives

By the end of this session, students will be able to:

  • Explain the structure of an AI API request and response
  • Authenticate securely using an API key
  • Replace the mock backend from Session 6 with a real cloud AI API call
  • Handle API errors, rate limits, and response parsing in application code

Hour 1: How Cloud AI APIs Work (Instructor-Led β€” 60 minutes)

1.1 The Anatomy of an API Call

An API (Application Programming Interface) call is a structured request from your application to a remote service. For AI APIs, the basic structure is:

Request β†’ Process β†’ Response

Your application sends:

  • Authentication (API key in the request header)
  • Model identifier (which model to use)
  • The message or messages (your prompt)
  • Optional parameters (temperature, max tokens, response format)

The API returns:

  • The model’s response text
  • Usage statistics (tokens consumed)
  • Metadata (model version, finish reason)

1.2 Understanding Temperature

temperature controls the randomness of the model’s output:

Value Behaviour Use Case
0.0 Deterministic (same input β†’ same output) Structured data extraction, classification
0.3–0.7 Balanced (some variety, mostly consistent) General question answering
1.0+ Creative (high variety, may be incoherent) Brainstorming, creative writing

For most AI product applications, start with temperature=0.2 to 0.5 for reliable, consistent outputs.

1.3 API Authentication Security

Your API key grants billing access to your account. Never:

  • Put an API key directly in your code
  • Commit an API key to a git repository
  • Expose an API key in client-side JavaScript

Always:

  • Store keys in environment variables
  • Load them with os.environ.get('API_KEY')
  • Add .env to your .gitignore
import os
api_key = os.environ.get('GEMINI_API_KEY')
if not api_key:
    raise ValueError("GEMINI_API_KEY environment variable not set")

1.4 Making Your First Real API Call (Gemini)

import os
import google.generativeai as genai

# Configure the API key
genai.configure(api_key=os.environ.get('GEMINI_API_KEY'))

# Select the model
model = genai.GenerativeModel('gemini-1.5-flash')

def ask_ai(user_query: str, system_instruction: str = "") -> str:
    """Send a query to the AI and return the response text."""
    try:
        if system_instruction:
            model_with_system = genai.GenerativeModel(
                'gemini-1.5-flash',
                system_instruction=system_instruction
            )
            response = model_with_system.generate_content(user_query)
        else:
            response = model.generate_content(user_query)
        return response.text
    except Exception as e:
        return f"Error: {str(e)}"

1.5 Error Handling

AI APIs fail. Common failures and how to handle them:

Error Type Cause Response
401 Unauthorized Invalid or missing API key Check key, check environment variable
429 Rate Limit Too many requests per minute Implement exponential backoff
500 Server Error API service issue Retry with delay, log the error
Timeout Request too large or network issue Add timeout parameter, reduce input size

Never let an API error crash your application silently. Always catch and log.


Hour 2: Practical β€” Replace the Mock with Real AI (60 minutes)

Lab 7.1 β€” Set Up Your Environment

Create a .env file in your project root:

GEMINI_API_KEY=your_api_key_here

Install the required packages:

pip install google-generativeai python-dotenv flask

Install python-dotenv and load the environment at app startup:

from dotenv import load_dotenv
load_dotenv()

Verify: add .env to .gitignore.

Lab 7.2 β€” Replace the Mock Backend

Update your Flask app.py from Session 6. Replace the mock response with a real AI call:

from flask import Flask, request, jsonify, send_from_directory
import os
from dotenv import load_dotenv
import google.generativeai as genai

load_dotenv()
genai.configure(api_key=os.environ.get('GEMINI_API_KEY'))
model = genai.GenerativeModel('gemini-1.5-flash')

app = Flask(__name__)

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/query', methods=['POST'])
def query():
    data = request.get_json()
    user_input = data.get('query', '').strip()
    if not user_input:
        return jsonify({'error': 'No query provided'}), 400
    try:
        response = model.generate_content(user_input)
        return jsonify({'response': response.text})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)

Lab 7.3 β€” Add Your System Prompt

Add your system prompt from Session 2 to the AI call. Your application now has a configured AI persona:

model = genai.GenerativeModel(
    'gemini-1.5-flash',
    system_instruction="[Your system prompt from Session 2]"
)

Lab 7.4 β€” Test and Observe

Test your application end-to-end. Send five different queries. Observe:

  • Response quality and relevance
  • Response latency (how long each call takes)
  • Token usage (check AI Studio’s usage tab)
  • Any errors or unexpected behaviour

Document your observations in your prompts.md file.


Key Takeaways

  • AI API calls follow a simple Request β†’ Process β†’ Response structure
  • Temperature controls output randomness; use low values for consistent production outputs
  • API keys must never be hardcoded or committed to source control
  • Robust error handling is not optional β€” AI APIs fail in production
  • Your application now has a real AI backend; the mock is replaced

Further Reading

  • Google AI for Developers documentation: ai.google.dev
  • python-dotenv documentation
  • β€œTwelve-Factor App” methodology β€” environment configuration best practices