How to Call an AI API in Python (2026): Quickstart for Any Model
ai api pythoncall llm api pythonpython ai tutorialopenai api pythonai api quickstart

How to Call an AI API in Python (2026): Quickstart for Any Model

2026-07-15

Calling an AI API in Python

This is the shortest path from zero to a working call — for LLMs, images and video — using one key so you can switch models without rewriting anything. Get a key first: how to get an API key.

Setup

pip install requests
export LINKMODEL_API_KEY="sk_live_..."   # store in env, never hardcode

Your First LLM Call

import os, requests
 
resp = requests.post(
    "https://api.linkmodel.ai/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['LINKMODEL_API_KEY']}"},
    json={
        "model": "claude-sonnet-4-6",
        "messages": [{"role": "user", "content": "Explain vector databases in 2 sentences."}],
    },
    timeout=60,
)
resp.raise_for_status()
print(resp.json())

Switch models by changing one string — gpt-5.6-terra, gemini-3.5-flash, deepseek-v4-flash. That's the point of one key: A/B without new SDKs. See build an AI app with multiple models.

Generating an Image

r = requests.post(
    "https://api.linkmodel.ai/api/v1/image-generation",
    headers={"Authorization": f"Bearer {os.environ['LINKMODEL_API_KEY']}"},
    json={"model": "seedream-5.0-pro", "prompt": "Studio product shot, soft light, 2K"},
).json()
task_id = r["data"]["task_id"]      # async: poll for the result

Image and video are async — you get a task_id, then poll GET /api/v1/query/image-generation?task_id=... (or /api/v1/query/video-generation) until the task reports success.

Retries & Rate Limits

Wrap calls with backoff so a 429 or blip doesn't crash your job:

import time
def call(payload, tries=4):
    for i in range(tries):
        r = requests.post(URL, headers=HEADERS, json=payload, timeout=60)
        if r.status_code != 429:
            r.raise_for_status(); return r.json()
        time.sleep(2 ** i)          # exponential backoff
    raise RuntimeError("rate limited")

More in AI API rate limits and latency guide.

Good Habits

  • Keys in env vars / secrets manager, never in code or Git.
  • Set timeouts and handle non-200s.
  • Stream long responses for snappier UX — see streaming LLM responses.
  • Cache stable prompt prefixes to cut cost — prompt caching.

Bottom Line

One key, requests, and a model string is all you need to call LLMs, images and video from Python — then swap models freely as you optimize for cost and quality. Confirm exact endpoints in the docs.

Start free with a $1 credit and run your first call.

Related Posts