OpenAI SDK
Chat Completions, streaming, tools and embeddings with the OpenAI SDK.
Morphogen is compatible with the OpenAI API. Set base_url and your Morphogen key, and the rest of your code stays the same. Python, TypeScript and any client with a configurable URL work.
Connect
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.morphogen.ru/v1",
api_key=os.environ["MORPHOGEN_API_KEY"],
)You can use any text model from client.models.list(), not only GPT: claude-sonnet-5 answers through the same client.
Request
resp = client.chat.completions.create(
model="claude-sonnet-5",
max_tokens=300,
messages=[
{"role": "system", "content": "Отвечай коротко."},
{"role": "user", "content": "Чем отличается TCP от UDP?"},
],
)
print(resp.choices[0].message.content)
print(resp.usage.total_tokens)Always pass max_tokens: without it, an amount based on the maximum response length is reserved, and with a small balance the request returns 402. Request parameters: Chat Completions.
Streaming
stream = client.chat.completions.create(
model="claude-sonnet-5",
max_tokens=300,
stream=True,
messages=[{"role": "user", "content": "Напиши хокку про дождь"}],
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)Tool calls
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Погода в городе",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
resp = client.chat.completions.create(
model="gpt-6-sol",
max_tokens=300,
tools=tools,
messages=[{"role": "user", "content": "Какая погода в Казани?"}],
)
call = resp.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)Run the function on your side and return the result in a message with role: "tool" in the next request. Tools work on models that support tool use.
Embeddings
emb = client.embeddings.create(model="bge-m3", input=["Как вернуть товар?"])
print(len(emb.data[0].embedding))Parameters: Embeddings.
Responses API
The same client calls client.responses.create(...). There is no stored history: do not pass store=True and previous_response_id, or you get 400 stateful_not_supported. Details: Responses.
Error handling
import openai
try:
client.chat.completions.create(model="claude-sonnet-5", max_tokens=100, messages=[...])
except openai.RateLimitError as e:
print("лимит, повторите через", e.response.headers.get("retry-after"), "с")
except openai.APIStatusError as e:
print(e.status_code, e.body)The error code is in e.body["error"]["code"]. All codes: Errors.