Open AI API Python: Use the OpenAI SDK With Our Model

For open ai api python code, you do not need a special library. The official openai package works with this service once you set a different base URL and key, and the model ID is uncensored. Below is a full walkthrough with copy-paste examples.
Key points
- Install openai, then pass base_url and api_key to the client; nothing else in your code changes.
- Streaming, JSON mode and tool calling all work through the same SDK methods.
- Catch RateLimitError and retry; limits are 300 requests per minute and 8 concurrent on a full key.
- Cost is $0.15 per 1M input tokens and $0.50 per 1M output tokens, charged only for successful requests.
Install and make the first call
You need Python 3.9 or newer and the official SDK. Create an API key first on the key page; new accounts can claim $0.50 of trial credit there with one click, with no card.
pip install openai
export API_KEY="your-key-here"
Now the smallest working script. The client takes the base URL and the key; the request uses the model ID uncensored.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aiapisource.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise writing assistant."},
{"role": "user", "content": "Give me three opening lines for a mystery novel."},
],
temperature=0.8,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)
That is the whole integration. The service implements POST /v1/chat/completions and GET /v1/models, which covers what most scripts use. It is a text model only, so image, audio and embeddings endpoints are not available.
What this is, and what it is not
The SDK is made by OpenAI, but the endpoint here is not OpenAI's. It is a hosted open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. There is no routing to GPT or any other vendor's model. That is why you change the base URL: you are talking to a different server that accepts the same request format.
If you are moving an existing project, search it for OpenAI( and for hard-coded model names. Those are the only two places that need editing. The GPT API production checklist on this site covers habits that apply to any OpenAI-format endpoint, such as timeouts and retries.
Stream the reply
For chat interfaces you want tokens as they are produced. Set stream=True and iterate. Ask for usage at the end if you want billing numbers:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a four-line poem about a night train."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
The guard on chunk.choices matters: the last chunk can carry usage and no choices. Also, a streamed request holds one of your concurrent slots until the stream ends, so always read it to the end or close it.
JSON mode
When your code needs to parse the answer, switch on JSON mode and describe the keys in the prompt:
import json
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "user", "content": "Return JSON with keys name (string) and traits (list of 3 strings) for a fictional ship captain."}
],
)
character = json.loads(resp.choices[0].message.content)
print(character["name"], character["traits"])
Valid JSON is the likely outcome, not a promise of your exact schema, so check the keys and retry once on failure.
Tool calling
Describe functions in tools, run whatever the model asks for, and send the result back with role: "tool":
import json
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = {"value": 14, "sides": args["sides"]} # replace with real logic
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)
You can pass tool_choice to force a function. The arguments come as a JSON string, so always run them through json.loads and validate them before use.
Errors, retries and async
The SDK retries some failures on its own, and you can set the count with max_retries. For rate limits, catch the exception and wait. The API returns HTTP 429 with the code rate_limited when you pass the per-minute limit, with concurrency when too many requests run at once, and with a Retry-After: 5 header on temporary overload.
import time
from openai import RateLimitError
def ask(prompt, tries=4):
for attempt in range(tries):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError:
time.sleep(5 * (attempt + 1))
raise RuntimeError("Still rate limited after retries")
For batches, use the async client and cap parallelism below your limit. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60.
import asyncio, os
from openai import AsyncOpenAI
aclient = AsyncOpenAI(base_url="https://api.aiapisource.com/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(6)
async def one(prompt):
async with sem:
r = await aclient.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
async def main():
prompts = [f"Write a tagline for product number {i}." for i in range(20)]
results = await asyncio.gather(*(one(p) for p in prompts))
print(len(results), "done")
asyncio.run(main())
Using 6 of the 8 slots leaves room for other traffic on the same key.
Keep a conversation going
The API is stateless. It remembers nothing between calls, so a chat is just the list of messages you send each time. Append the reply to the list and send the whole list again:
history = [{"role": "system", "content": "You are a patient writing coach."}]
def chat(user_text):
history.append({"role": "user", "content": user_text})
r = client.chat.completions.create(model="uncensored", messages=history)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("Give me a prompt for a short story."))
print(chat("Make it darker and set it in a harbour town."))
Each call sends more tokens than the last, and input tokens are billed on every call. When the list gets long, drop the oldest turns or replace them with a short summary. The context window is 100,000 tokens for prompt plus completion, which is a lot, but a long history makes every request more expensive and slower to start.
Sampling settings are passed through: temperature, top_p, stop, seed and the frequency and presence penalties. Set seed and a low temperature when you want repeatable test runs.
Estimate cost before a big run
Billing is per token from prepaid credit: $0.15 per 1M input tokens and $0.50 per 1M output tokens. Failed or refused requests are not charged, and credit never expires. Take a batch of 10,000 requests with 1,500 input tokens and 400 output tokens each. Input is 15,000,000 tokens, which is 15 x $0.15 = $2.25. Output is 4,000,000 tokens, which is 4 x $0.50 = $2.00. The batch costs $4.25.
The response headers include X-Balance-USD, so you can read your remaining balance in code through client.chat.completions.with_raw_response.create(...). Top-ups are any whole amount from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200. The pricing page lists payment options, and the quickstart lists every supported parameter, including stop, seed and the penalties.
More guides
Questions and answers
Can I use the official OpenAI Python package with this API?
Yes. Install openai, set base_url to the service endpoint and api_key to your key, and call chat.completions.create with the model uncensored.
Do I need a different library for streaming or tools?
No. Streaming, JSON mode and tool calling work through the same SDK methods, with the usual parameters.
Is this OpenAI's model?
No. It is an open-weight model run by an independent provider. The request format is the same, which is why the SDK works.
Do my prompts train the model?
No. Prompts sent through the API are not used for training.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.