Skip to main content

Universe Reference

This document provides a complete reference for the Universe API, including endpoint addresses, request parameters, response formats, error codes, and other detailed information.


1. Overview

The Universe is a standardized RESTful API service that connects large language model capabilities with developer applications through a unified protocol. It supports HTTP requests and official SDK calls, is compatible with the OpenAI API protocol, and provides features such as chat completion and content generation.


2. API Endpoints

TypeEndpoint URLDescription
General Servicehttps://open.universeapi.com/api/paas/v4Suitable for all general-purpose scenarios (conversation, generation, analysis, etc.)
Dedicated Service (Coding)https://open.universeapi.com/api/coding/paas/v4Optimized specifically for code generation and programming assistance scenarios

How to Choose: For most scenarios, the general service endpoint is sufficient. If you are developing a code assistant, IDE plugin, or other programming-related product, it is recommended to use the dedicated coding endpoint for better code generation results.


3. Authentication

All API requests use HTTP Bearer tokens for authentication. The request header must include:

Authorization: Bearer YOUR_API_KEY
ParameterLocationRequiredDescription
AuthorizationRequest HeaderYesFormat: Bearer {api_key}, with a space after Bearer

Security Best Practices:

  • Do not hardcode API keys in your source code
  • Configure keys via environment variables or secret management services
  • Use separate keys for different projects, and set permission and quota limits
# Recommended: configure via environment variable
export UNIVERSE_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxx"

4. Available Models

Model NameAPI ParameterPositioning
Universe 3.0universe-3.0Lightweight and efficient, suitable for everyday general tasks
Universe 3.0 Prouniverse-3.0-proProfessional enhanced version with strong reasoning capabilities and high cost-effectiveness
Universe 4.5universe-4.5Flagship all-round model with the highest capability ceiling

For a detailed model capability comparison, please refer to the Model Product Introduction.


5. Chat Completions

This is the most core endpoint of the Universe API, used to send a list of messages to the model and receive a response.

5.1 Request

POST /chat/completions

Full request URL example:

https://open.universeapi.com/api/paas/v4/chat/completions

Request Parameters

ParameterTypeRequiredDefaultDescription
modelstringYes-Model name, e.g., universe-3.0-pro. See the model list above for available values.
messagesarrayYes-List of conversation messages, including role and content. See the message format description below.
temperaturenumberNo1.0Controls output randomness. Range: 0-2. Higher values produce more diverse output, lower values produce more deterministic output.
top_pnumberNo1.0Nucleus sampling parameter. Only samples from tokens with the highest probabilities. Adjust either this or temperature, not both.
max_tokensintegerNoModel defaultLimits the maximum number of tokens in the model output.
streambooleanNofalseWhether to enable streaming output. When enabled, results are pushed token by token in real time.
stopstring/arrayNonullStop sequences. The model stops generating when it produces the specified string. Up to 4 sequences can be set.
frequency_penaltynumberNo0Range: -2.0 to 2.0. Positive values decrease the repetition probability of tokens that have already appeared.
presence_penaltynumberNo0Range: -2.0 to 2.0. Positive values encourage the model to introduce new topics.
response_formatobjectNo-Specifies the output format, e.g., {"type": "json_object"} to force valid JSON output.
toolsarrayNo-List of tool/function definitions for Function Calling. See Section 5.4 for details.
tool_choicestring/objectNoautoControls whether and how the model calls tools. Options: auto, none, required.

Message Format (messages)

Each message in the message list contains the following fields:

FieldTypeRequiredDescription
rolestringYesMessage role: system, user, assistant, tool
contentstringYesMessage content
namestringNoName of the message sender (used in multi-user scenarios)

Role Descriptions:

RolePurposeUsage Recommendations
systemSets the model's role, behavior, and constraintsPlace at the very beginning of the message list; typically only one is set
userMessages sent by the userThe user's input in each turn of the conversation
assistantPrevious replies from the modelInclude conversation history for multi-turn dialogues
toolReturn results from tool/function callsUsed in conjunction with Function Calling

5.2 Non-Streaming Response

When stream=false (default), the server returns a complete JSON response:

{
"id": "chatcmpl-xxxxxxxx",
"object": "chat.completion",
"created": 1700000000,
"model": "universe-3.0-pro",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! I am the Universe AI assistant, happy to help you."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 18,
"total_tokens": 43
}
}

Response Field Descriptions

FieldTypeDescription
idstringUnique request identifier
objectstringObject type, fixed as chat.completion
createdintegerResponse creation time (Unix timestamp)
modelstringThe actual model name used
choicesarrayList of generation results (usually 1)
choices[].indexintegerResult index
choices[].messageobjectThe message content of the model's reply
choices[].message.rolestringFixed as assistant
choices[].message.contentstringThe text content generated by the model
choices[].finish_reasonstringStop reason: stop (normal completion), length (reached max_tokens), tool_calls (triggered tool call)
usageobjectToken usage statistics
usage.prompt_tokensintegerNumber of tokens consumed by the input
usage.completion_tokensintegerNumber of tokens consumed by the output
usage.total_tokensintegerTotal number of tokens consumed

5.3 Streaming Response

When stream=true, the server streams results chunk by chunk via the SSE (Server-Sent Events) protocol. Each data chunk has the following format:

{
"id": "chatcmpl-xxxxxxxx",
"object": "chat.completion.chunk",
"created": 1700000000,
"model": "universe-3.0-pro",
"choices": [
{
"index": 0,
"delta": {
"content": "Hello"
},
"finish_reason": null
}
]
}

At the end of the stream, a final chunk with finish_reason set to stop is sent, followed by the [DONE] marker:

data: [DONE]

Parsing Streaming Responses (Python)

response = client.chat.completions.create(
model="universe-3.0-pro",
messages=[
{"role": "system", "content": "You are a friendly AI assistant."},
{"role": "user", "content": "Tell me a short story"}
],
stream=True
)

for chunk in response:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)

Parsing Streaming Responses (cURL)

curl -X POST "https://open.universeapi.com/api/paas/v4/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-N \
-d '{
"model": "universe-3.0-pro",
"messages": [{"role": "user", "content": "Hello"}],
"stream": true
}'

Tip: In cURL, the -N parameter disables output buffering to ensure real-time reception of streaming data.


5.4 Function Calling (Tool Calls)

Function Calling allows the model to invoke external functions or tools during a conversation, enabling interaction with external systems.

Defining Tools

Define available tools in the tools parameter of the request:

{
"model": "universe-3.0-pro",
"messages": [
{"role": "user", "content": "What's the weather like in Beijing today?"}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g., Beijing"
}
},
"required": ["city"]
}
}
}
],
"tool_choice": "auto"
}

Handling Tool Call Responses

When the model decides to call a tool, the response's finish_reason will be tool_calls, and the message will contain the call information:

{
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_xxxxxxxx",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"Beijing\"}"
}
}]
},
"finish_reason": "tool_calls"
}]
}

Returning Tool Results

After calling the external function, return the results to the model as a tool role message:

{
"model": "universe-3.0-pro",
"messages": [
{"role": "user", "content": "What's the weather like in Beijing today?"},
{"role": "assistant", "content": null, "tool_calls": [{"id": "call_xxxxxxxx", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Beijing\"}"}}]},
{"role": "tool", "content": "{\"temperature\": 28, \"condition\": \"Sunny\"}", "tool_call_id": "call_xxxxxxxx"}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g., Beijing"
}
},
"required": ["city"]
}
}
}
]
}

The model will generate its final reply based on the results returned by the tool.


6. Code Examples

6.1 Python SDK Example

from universeai import UniverseClient

# Initialize the client
client = UniverseClient(api_key="YOUR_API_KEY")

# Non-streaming call
response = client.chat.completions.create(
model="universe-3.0-pro",
messages=[
{"role": "system", "content": "You are a professional translation assistant. Translate the user's input into English."},
{"role": "user", "content": "The weather is really nice today, perfect for a walk."}
],
temperature=0.3
)

print(response.choices[0].message.content)
print(f"Token usage: {response.usage.total_tokens}")

6.2 Java SDK Example

import universeai.UniverseClient;
import universeai.service.model.*;

public class ChatExample {
public static void main(String[] args) {
UniverseClient client = UniverseClient.builder()
.apiKey("YOUR_API_KEY")
.build();

ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
.model("universe-3.0-pro")
.messages(Arrays.asList(
ChatMessage.builder()
.role("system")
.content("You are a professional translation assistant. Translate the user's input into English.")
.build(),
ChatMessage.builder()
.role("user")
.content("The weather is really nice today, perfect for a walk.")
.build()
))
.temperature(0.3f)
.build();

ChatCompletionResponse response = client.chat().createChatCompletion(request);
System.out.println(response.getData().getChoices().get(0).getMessage());
}
}

6.3 cURL Example

curl -X POST "https://open.universeapi.com/api/paas/v4/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "universe-3.0-pro",
"messages": [
{"role": "system", "content": "You are a professional translation assistant. Translate the user input into English."},
{"role": "user", "content": "The weather is really nice today, perfect for a walk."}
],
"temperature": 0.3
}'

6.4 OpenAI SDK Compatible Call

from openai import OpenAI

client = OpenAI(
api_key="YOUR_UNIVERSE_API_KEY",
base_url="https://open.universeapi.com/api/paas/v4"
)

response = client.chat.completions.create(
model="universe-3.0-pro",
messages=[
{"role": "system", "content": "You are a professional translation assistant. Translate the user's input into English."},
{"role": "user", "content": "The weather is really nice today, perfect for a walk."}
],
temperature=0.3
)

print(response.choices[0].message.content)

7. Multi-turn Dialogue

To implement multi-turn dialogue, you need to pass the entire message history in the messages list:

messages = [
{"role": "system", "content": "You are a friendly AI assistant."},
{"role": "user", "content": "What is a large language model?"},
{"role": "assistant", "content": "A large language model (LLM) is a natural language processing model based on deep learning..."},
{"role": "user", "content": "How is it different from traditional NLP models?"},
]

response = client.chat.completions.create(
model="universe-3.0-pro",
messages=messages
)

Note: Each request requires the complete message history to be passed in, as the model does not automatically persist conversation state. It is recommended to summarize and compress overly long conversation histories to avoid exceeding the context window limit.


8. Error Codes

HTTP Status Codes

Status CodeMeaningCommon CausesSolution
400Bad RequestMalformed request body, missing required parameters, parameter values out of rangeCheck JSON format and required parameters
401UnauthorizedAPI key is invalid, missing, or not passed correctlyVerify the key is correct and check the request header format
403ForbiddenKey does not have permission to access the model, or request content violates usage policiesCheck key permissions and usage policies
404Not FoundModel name is misspelled or endpoint URL is incorrectVerify the model name and endpoint
429Too Many RequestsRequest frequency exceeds quota limitsReduce frequency or request a quota increase
500Internal Server ErrorInternal server errorRetry later; contact support if the issue persists
502Bad GatewayUpstream service is temporarily unavailableRetry later
503Service UnavailableSystem maintenance or overloadWait a few minutes and retry

Error Response Format

All error responses follow a unified format:

{
"error": {
"message": "Invalid API key provided.",
"type": "authentication_error",
"code": "invalid_api_key"
}
}
FieldDescription
error.messageHuman-readable error description
error.typeError type identifier
error.codeError code for programmatic handling

9. Rate Limits

LimitDescription
RPM (Requests Per Minute)Maximum number of requests allowed per minute
RPH (Requests Per Hour)Maximum number of requests allowed per hour
TPM (Tokens Per Minute)Maximum number of tokens allowed to be consumed per minute

When a rate limit is triggered, an HTTP 429 error is returned. Recommended handling approach:

import time

def call_with_retry(client, messages, max_retries=3):
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model="universe-3.0-pro",
messages=messages
)
except Exception as e:
if "429" in str(e) and attempt < max_retries - 1:
wait_time = 2 ** attempt # Exponential backoff: 1s, 2s, 4s
time.sleep(wait_time)
else:
raise

To increase your quota, please contact the technical support team.


10. Debugging Suggestions

MethodDescription
Inspect Requests and ResponsesPrint the complete request parameters and response content to troubleshoot formatting issues
Use Minimal ExamplesStart with the simplest possible prompt to test connectivity, then gradually increase complexity
Check the usage FieldVerify that token consumption matches your expectations
Compare cURL and SDKIf SDK calls fail, test with cURL first to rule out network issues
Online Debugging ToolsUse the online debugging tools provided in the console to quickly verify the API

Additional Resources

DocumentContent
Developer GuideQuick start, platform introduction, core concepts
Model Product IntroductionModel capability comparison, model selection guide
PricingBilling rules, model pricing, cost optimization
Prompt Engineering GuidePrompt writing tips, parameter tuning, template quick reference
FAQFAQ, troubleshooting, SDK installation, performance optimization