Call Claude and GPT from Python with 59API
What you will build
This tutorial shows how to call both Claude and GPT from one Python program through 59API. Because 59API provides an OpenAI-compatible interface, you can use the familiar OpenAI Python SDK and switch models by changing one string. The same approach works for chatbots, document tools, coding assistants, and batch scripts.
59API is useful when you want pay-as-you-go access without maintaining separate integrations. It offers native official-quality Claude and GPT models, including Claude Opus, Sonnet, Haiku, and Fable options, at pricing that is among the lowest for relay services.
1. Create an API key and install the SDK
Sign up for a 59API account, create an API key, and check the model list in your dashboard. Copy the exact model IDs shown there because names can change as providers release new versions.
Install the OpenAI SDK with:
pip install openai
Store the key in an environment variable rather than placing it directly in source code. On macOS or Linux, for example:
export 59API_API_KEY='your-api-key'
On Windows, set the equivalent environment variable through PowerShell or System Settings.
2. Create an OpenAI-compatible client
Import the SDK and point its base URL to 59API. The API key is read at runtime from your environment:
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ['59API_API_KEY'],
base_url='https://api.59api.com'
)
Using an environment variable keeps secrets out of Git repositories, screenshots, and deployed frontend code. For a web application, make this call only on your server.
3. Write one reusable request function
Chat Completions uses a list of messages. The system message defines behavior, while the user message contains the task. The function below returns the assistant's text and accepts any model ID supported by your 59API account:
def ask(model, prompt):
response = client.chat.completions.create(
model=model,
messages=[
{'role': 'system', 'content': 'Be accurate and concise.'},
{'role': 'user', 'content': prompt}
],
temperature=0.2
)
return response.choices[0].message.content
A lower temperature is useful for extraction, classification, and technical answers. Increase it when you want more variation in creative output.
4. Call Claude and GPT
Replace the example IDs below with the exact Claude and GPT IDs displayed in your 59API model list:
claude_model = 'your-claude-sonnet-model-id'
gpt_model = 'your-gpt-model-id'
claude_answer = ask(claude_model, 'Summarize why API versioning matters in three sentences.')
gpt_answer = ask(gpt_model, 'Write a Python function that validates an email address.')
print('Claude:')
print(claude_answer)
print('GPT:')
print(gpt_answer)
The request format stays the same even though the underlying providers differ. You can route long-context work to a Claude model, use a fast Haiku or GPT option for short tasks, and select a stronger Opus or GPT model for complex reasoning.
5. Add basic production safeguards
- Handle timeouts and rate-limit errors with retries and exponential backoff.
- Set application-level limits for prompt size and output length to control spend.
- Log the selected model, latency, and response usage, but never log API keys or sensitive prompts.
- Validate model IDs during deployment so a typo does not cause failures at runtime.
- Keep provider-specific behavior out of your business logic; the shared function makes model switching simple.
6. Control cost with 59API
Since 59API is pay-as-you-go, you pay for actual usage instead of committing to a large subscription. Start with a lower-cost model for routine requests and reserve premium models for tasks that need their extra capability. Review token usage regularly and cache repeated results where appropriate.
If you want to try this setup, create a 59API account, add a small balance, and test both models with the script above. 59API also offers a referral rebate, which can further reduce costs when you share the service with other developers.
Common troubleshooting checks
- Confirm that the base URL is exactly https://api.59api.com.
- Check that the key is present in the same shell or process running Python.
- Copy the model ID exactly from the dashboard.
- Print the full exception while testing, but remove sensitive data before sharing logs.
Prêt à commencer ?
Connectez Claude et GPT en quelques minutes aux prix les plus bas, sans bridage. Inscrivez-vous pour votre clé API.
Inscription gratuite