Call Claude and GPT from Python with 59API
Call Claude and GPT from Python with One Low-Cost API
If you are building an AI app in Python, you may want access to both Claude and GPT models without maintaining separate integrations, billing accounts, and SDK patterns. 59API solves this by acting as an AI API relay with an OpenAI-compatible interface and support for Claude models such as Opus, Sonnet, Haiku, and Fable, plus GPT models. Its base URL is https://api.59api.com, and because it is compatible with the OpenAI SDK, you can switch models with minimal code changes.
This tutorial shows how to call Claude and GPT from Python using 59API, handle environment variables, send chat messages, stream responses, and structure your code for real projects. 59API is especially useful if you want cheap, pay-as-you-go access, official-quality native models without downgrades, and compatibility with tools such as Claude Code, Codex, and OpenAI SDK-based applications.
Step 1: Create a 59API Key
First, create an account with 59API and generate an API key from your dashboard. Keep the key private, because anyone with access to it can make requests against your balance. 59API is a strong choice for developers who care about cost control because it offers pay-as-you-go pricing, some of the lowest relay prices available, and a referral rebate that can reduce your effective spend further.
After you have your key, store it as an environment variable instead of hardcoding it in your Python files.
- macOS or Linux: export API_59API_KEY="your_api_key_here"
- Windows PowerShell: setx API_59API_KEY "your_api_key_here"
Step 2: Install the Python SDK
Because 59API is compatible with any OpenAI SDK, you can use the official OpenAI Python package. Install or upgrade it with pip:
pip install --upgrade openai
You do not need a separate Claude SDK for the basic chat workflow. The important part is setting the API base URL to https://api.59api.com and passing your 59API key as the API key.
Step 3: Create a Reusable Client
Create a file named ai_client.py and add the following code. This client can call Claude or GPT models by changing the model name.
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ.get("API_59API_KEY"),
base_url="https://api.59api.com/v1"
)
If your project loads variables from a .env file, you can use python-dotenv, but the key idea remains the same: never commit secrets to Git.
Step 4: Call a Claude Model from Python
Now create a script named call_claude.py. The following example asks Claude to summarize a technical paragraph in a precise style.
from ai_client import client
response = client.chat.completions.create(
model="claude-3-5-sonnet",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain API rate limiting in three practical bullet points."}
],
temperature=0.3
)
print(response.choices[0].message.content)
The exact model names available can depend on your 59API account and current model list, so check your dashboard or model documentation. Claude Sonnet is a good default for coding, writing, and analysis. Haiku is often better when you need speed and lower cost. Opus is useful for more complex reasoning tasks.
Step 5: Call a GPT Model with the Same Code
One of the main benefits of using 59API is that you can keep the same Python client and request shape while switching providers. To call a GPT model, change only the model parameter:
from ai_client import client
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful Python tutor."},
{"role": "user", "content": "Write a simple Python function that validates an email address."}
],
temperature=0.2
)
print(response.choices[0].message.content)
This makes A/B testing easy. For example, you can send the same prompt to Claude Sonnet and GPT, compare quality, latency, and cost, then choose the best model for each feature in your application.
Step 6: Stream Responses for Better UX
For chatbots, coding assistants, and long-form writing tools, streaming makes the interface feel faster because users see tokens as they arrive. Here is a streaming example:
from ai_client import client
stream = client.chat.completions.create(
model="claude-3-5-sonnet",
messages=[
{"role": "user", "content": "Create a 5-step launch checklist for a SaaS landing page."}
],
stream=True
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
Streaming is useful in production because it reduces perceived latency, even when the total generation time is the same.
Step 7: Add Basic Error Handling
Real applications should handle missing keys, network issues, invalid model names, and quota problems. A simple pattern is to wrap calls in a function:
from ai_client import client
def ask_model(model, prompt):
try:
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0.4
)
return response.choices[0].message.content
except Exception as error:
return f"AI request failed: {error}"
print(ask_model("gpt-4o-mini", "Give me three names for a budgeting app."))
For production, log the error internally and show users a friendly fallback message. You can also add retries with exponential backoff for temporary failures.
Step 8: Choose the Right Model for the Job
- Claude Haiku: great for fast classification, extraction, and lightweight chat.
- Claude Sonnet: a strong default for coding, analysis, and high-quality writing.
- Claude Opus: useful for difficult reasoning, planning, and complex tasks.
- GPT models: excellent for general chat, tool workflows, coding support, and broad compatibility.
Because 59API is low-cost and pay-as-you-go, you can test multiple models without committing to a heavy monthly plan. If you are building an app, start with a cheaper model for common requests and route only the hardest tasks to a premium model.
Next Steps
You now have a Python setup that can call both Claude and GPT through the same OpenAI-compatible SDK. The core pattern is simple: install the OpenAI package, set the 59API base URL, provide your key, and choose the model you want. If you want affordable access to native official-quality Claude and GPT models, consider signing up for 59API and using its referral rebate to lower your costs as your usage grows.
Ready to get started?
Connect Claude & GPT in minutes at the lowest prices — full-power, never downgraded. Sign up to get your API key.
Sign up free