Try Chat Free Docs Pricing AI Analysis Repo Insights Free Tools About Blog
Sign in Get started free
< Back to blog
Tutorial Velona Team ·9 September 2026 ·4 min read

How to Use an AI API with Python

The easiest way to use an AI API from Python is the official OpenAI Python SDK. It works with OpenAI and with any OpenAI-compatible gateway, so with Velona the same few lines can call GPT, Claude, Gemini, DeepSeek and 300+ other models. You change only the model value.

This guide goes from your first request to a small reusable helper with system prompts, chat history, streaming, error handling and cost tracking.

1. Install the SDK and set your key

pip install openai python-dotenv

Create a .env file next to your script and add it to .gitignore:

VELONA_API_KEY=your_key_here

No key yet? Follow the 5-minute setup guide. You can start with ₹10 via UPI.

2. Your first request

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(
    api_key=os.environ["VELONA_API_KEY"],
    base_url="https://velona.in/v1",
)

response = client.chat.completions.create(
    model="deepseek/deepseek-v4-flash",
    messages=[{"role": "user", "content": "Explain APIs in simple words."}],
)

print(response.choices[0].message.content)

Three things make this work: your API key, the base_url, and a model ID in the form provider/model.

3. Give the model instructions with a system prompt

A system message sets the model's role and rules for the whole conversation.

response = client.chat.completions.create(
    model="deepseek/deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "You are a patient Python tutor. Answer in under 100 words with one code example."},
        {"role": "user", "content": "What is a list comprehension?"},
    ],
    max_tokens=300,
)

max_tokens limits the length of the reply, which also limits the cost.

4. Keep a conversation going

The API doesn't remember previous messages. You send the history each time.

history = [{"role": "system", "content": "You are a helpful assistant."}]

def chat(user_message):
    history.append({"role": "user", "content": user_message})
    response = client.chat.completions.create(
        model="deepseek/deepseek-v4-flash",
        messages=history[-10:],  # keep only recent messages to control cost
    )
    reply = response.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(chat("Suggest a name for a chai delivery app."))
print(chat("Make it sound more premium."))

Sending only the last few messages keeps requests fast and cheap.

5. Stream the reply as it is written

Streaming shows text as soon as the model produces it, so users aren't staring at a blank screen.

stream = client.chat.completions.create(
    model="deepseek/deepseek-v4-flash",
    messages=[{"role": "user", "content": "Write a 4-line poem about Mumbai rain."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

6. Handle errors properly

import openai

try:
    response = client.chat.completions.create(
        model="deepseek/deepseek-v4-flash",
        messages=[{"role": "user", "content": "Hello"}],
    )
except openai.AuthenticationError:
    print("Check your API key.")
except openai.RateLimitError:
    print("Too many requests. Wait and retry.")
except openai.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")

A "model not found" error usually means the provider prefix is missing. Use openai/gpt-4o-mini, not gpt-4o-mini.

7. Track what each request costs

Every response includes the token counts you are billed for:

usage = response.usage
print(usage.prompt_tokens, usage.completion_tokens)

To turn that into rupees, multiply by the model's price per token. For DeepSeek V4 Flash (₹2.90 per 1M input tokens and ₹5.80 per 1M output tokens as of 4 October 2026):

cost_inr = usage.prompt_tokens * 2.90 / 1_000_000 + usage.completion_tokens * 5.80 / 1_000_000
print(f"This request cost about ₹{cost_inr:.4f}")

Your usage dashboard shows the exact rupee cost of every call, so you don't have to calculate it yourself.

8. Switch models with one line

ModelModel IDInput ₹ / 1MGood for
DeepSeek V4 Flashdeepseek/deepseek-v4-flash₹2.90Cheap default, coding, long context
GPT-4o miniopenai/gpt-4o-mini₹15.54Reliable all-rounder, reads images
Gemini 2.5 Flashgoogle/gemini-2.5-flash₹31.08Images, audio and video input
Claude Sonnet 5anthropic/claude-sonnet-5₹207.22Hard coding, writing and analysis

Browse every model with its rupee price in the model catalogue.

Putting it together: a reusable helper

def ask(prompt, model="deepseek/deepseek-v4-flash", system=None, max_tokens=500):
    messages = []
    if system:
        messages.append({"role": "system", "content": system})
    messages.append({"role": "user", "content": prompt})
    response = client.chat.completions.create(
        model=model, messages=messages, max_tokens=max_tokens
    )
    return response.choices[0].message.content

print(ask("Give me three Python project ideas for a college student."))

Frequently asked questions

Do I need the OpenAI library to call Claude or DeepSeek?

With Velona, yes, and that is the advantage: one library for every model. You change only the model value.

Can I use the requests library instead?

Yes. Send a POST request to https://velona.in/v1/chat/completions with your key in the Authorization: Bearer header and the same JSON body. The SDK just handles this for you.

How much does it cost to run these examples?

Running every example here on DeepSeek V4 Flash costs well under ₹1. A ₹10 top-up is plenty to learn with.

Building in JavaScript instead? Read how to use an AI API with JavaScript. Ready to start? Create your Velona account.