Menu

AI & Machine Learning Topic

Connect OpenAI and Gemini APIs with a Simple Python Backend

This guide shows two server-side text calls with the same small task. It uses the OpenAI Python SDK and Google's current google-genai SDK. The older google-generativeai setup and old model IDs from earlier examples are not used here.

You need an account, a valid key and a model available to that account for the provider you choose. Running a request sends your prompt to that provider and may cost money. You can read the code and test your own validation without making a paid request.

Keep secrets on the server

Store keys in an appropriate environment or secret store. Do not put them in a browser page, screenshot, Git commit or application log. A local .env file needs an explicit loader if you use one, and should be excluded from Git. A Python script does not read that file automatically.

For a website, the browser calls your backend. Your backend authenticates the user where needed, checks input size and rate limits, then calls the provider. Never make the browser carry your private provider key.

Set up a separate environment

python3 -m venv .venv
source .venv/bin/activate
python -m pip install openai google-genai

Set AI_PROVIDER to openai or gemini in your terminal environment. For OpenAI, set OPENAI_API_KEY and OPENAI_MODEL. For Gemini, set GEMINI_API_KEY and GEMINI_MODEL. Use a current model ID from the provider's documentation that your account supports. No particular latest model is required for this lesson.

Do not paste your actual key into the tutorial or share the output of commands that print environment variables. Use the settings names above with your local secret-management method.

A complete small client module

Save this as llm_clients.py. It uses the Responses API for OpenAI and the documented Interactions interface for Gemini.

"""Optional paid API examples. Keys and accessible model IDs come from your environment."""
import os

def answer(provider, prompt):
    if provider == "openai":
        from openai import OpenAI
        with OpenAI(timeout=30.0,max_retries=1) as client:
            result = client.responses.create(model=os.environ["OPENAI_MODEL"],
                input=prompt,max_output_tokens=300)
            return result.output_text
    if provider == "gemini":
        from google import genai
        from google.genai import types
        client = genai.Client(api_key=os.environ["GEMINI_API_KEY"],
                              http_options=types.HttpOptions(timeout=30000))
        try:
            result = client.interactions.create(model=os.environ["GEMINI_MODEL"],input=prompt)
            return result.output_text
        finally:
            client.close()
    raise ValueError("Choose openai or gemini")

if __name__ == "__main__":
    # Running this sends data to the selected provider and may incur a charge.
    print(answer(os.environ["AI_PROVIDER"],"Explain a Python list in two easy sentences."))
python llm_clients.py

The result should be a short explanation of a Python list. Exact wording can vary. The model identifier is required through the environment so an obsolete hard-coded name is not silently used.

The wrapper returns text only. Providers differ in streaming, tools, structured output, safety behaviour and usage reporting. A common function does not make all those features interchangeable. Add them deliberately with provider-specific tests.

Handle failure by type

A missing local setting should fail before a request. An invalid key needs credential review, not repeated retries. A rate limit may need backoff or lower request volume. A quota or billing problem can require account action. A temporary connection failure may justify a bounded retry.

The OpenAI example sets a 30-second timeout and one SDK retry. The Gemini HTTP timeout is in milliseconds. Review each SDK's retry behaviour before adding another loop; nested retries can multiply requests. In a web app, return a clear temporary-error response and keep internal details out of the browser.

Check output and spending

Keep prompt size and expected output bounded. The OpenAI example sets an output-token limit; provider settings are not identical. Set appropriate output controls for the exact Gemini model and interface when expanding this example. Add account alerts and application limits rather than assuming a budget alert is a hard cap.

Validate structured results and check important facts. Save prompt versions and non-sensitive operational metrics. A successful HTTP response means the request completed, not that the text is correct.

Practice

Write three invented notes and define the expected answer facts. Compare the selected provider on those cases. Then test a missing model setting and an unsupported provider name locally. Do not test error handling by publishing a real key or sending private production data.

Official references

Reviewed on 25 October 2026. Use documentation for your installed versions.

All AI & Machine Learning tutorials

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?