First AI project

Using Google Gemini API with pydantic-ai

✨ Using Google Gemini API with pydantic-ai

Objective

Use the Google Gemini API with the pydantic-ai Python library to send a question and receive a concise response.

Prerequisites

  • Python 3 installed (pip3 available)
  • Google Gemini API Key (from Google AI Studio or Google Cloud Console)

Step 1: Obtain Gemini API Key

  1. Go to Google AI Studio.
  2. Generate a new API Key for the Gemini API.
  3. Copy and store the API key safely – DO NOT SHARE it.

Step 2: Install pydantic-ai Library

pip3 install pydantic-ai

Step 3: Set Environment Variable

Make sure the key is available in your current terminal session.

Linux/macOS:

export GEMINI_API_KEY="YOUR_API_KEY_HERE"

Windows (Command Prompt):

set GEMINI_API_KEY="YOUR_API_KEY_HERE"

Windows (PowerShell):

$env:GEMINI_API_KEY="YOUR_API_KEY_HERE"
Note: Only valid for the current terminal session. Set it again if you open a new terminal.

Step 4: Create Python Script (hello_world.py)

from pydantic_ai import Agent

# Initialize the Agent
agent = Agent(
    'google-gla:gemini-1.5-flash',
    system_prompt='Be concise, reply with one sentence.',
)

# Ask a question
result = agent.run_sync('Where does "hello world" come from?')

# Print the answer
print(result.data)

▶ Step 5: Run the Script

python3 hello_world.py

Expected Output

A concise answer from the Gemini model, printed in your terminal, for the question:

"Where does 'hello world' come from?"

Comments

Popular posts from this blog

AEM with react.

Sling Servlet