### Complete First Installation Wizard (JavaScript) Source: https://docs.newapi.ai/api/fei-system-initialization Initiates the system's first-time setup by creating the root administrator account and configuring system parameters. Requires administrator credentials. This endpoint does not require authentication. ```javascript const response = await fetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "admin", password: "password123", confirmPassword: "password123", SelfUseModeEnabled: false, DemoSiteEnabled: false }) }); const data = await response.json(); ``` -------------------------------- ### Get System Runtime Status (JavaScript) Source: https://docs.newapi.ai/api/fei-system-initialization Fetches the current operational status of the system, including version, start time, and feature flags. This endpoint does not require authentication. ```javascript const response = await fetch('/api/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` -------------------------------- ### Polling Strategy and Example Source: https://docs.newapi.ai/api/query-video Recommended polling intervals and an example code snippet for checking video generation status. ```APIDOC ## Polling Strategy ### Recommended Polling Intervals 1. **Initial Poll**: Wait 2-3 seconds after submitting a task before starting to poll. 2. **Polling Frequency**: - First 30 seconds: Poll every 5 seconds. - 30 seconds to 2 minutes: Poll every 10 seconds. - After 2 minutes: Poll every 30 seconds. 3. **Timeout Handling**: It is recommended to set a total timeout of 5-10 minutes. ### Polling Example Code ```javascript async function pollVideoStatus(taskId, maxAttempts = 30) { const baseUrl = 'https://your-newapi-server-address'; const headers = { 'Authorization': 'Bearer sk-xxxx', 'Content-Type': 'application/json' }; for (let attempt = 0; attempt < maxAttempts; attempt++) { try { const response = await fetch(`${baseUrl}/v1/video/generations/${taskId}`, { headers }); const result = await response.json(); if (result.status === 'succeeded') { return result; } else if (result.status === 'failed') { throw new Error(`Video generation failed: ${result.error?.message || 'Unknown error'}`); } // Wait before retrying const delay = attempt < 6 ? 5000 : (attempt < 12 ? 10000 : 30000); await new Promise(resolve => setTimeout(resolve, delay)); } catch (error) { console.error(`Attempt ${attempt + 1} failed:`, error); if (attempt === maxAttempts - 1) { throw error; } } } throw new Error('Max polling attempts reached'); } ``` ``` -------------------------------- ### POST /v1/chat/completions Source: https://docs.newapi.ai/api/openai-chat This endpoint provides chat completions from AI models. It supports the `logprobs` and `top_logprobs` parameters to get detailed probability information for each token in the completion. ```APIDOC ## POST /v1/chat/completions ### Description This endpoint generates chat completions using AI models. It allows for the retrieval of log probabilities for each token, providing insights into the model's token generation process. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The ID of the model to use for chat completions. - **messages** (array) - Required - A list of messages comprising the conversation so far. - **role** (string) - Required - The role of the author of a message (e.g., `system`, `user`, or `assistant`). - **content** (string) - Required - The content of the message. - **logprobs** (boolean) - Optional - Whether to return log probabilities for the completion choices. Defaults to false. - **top_logprobs** (integer) - Optional - An integer between 0 and 5 specifying the number of top log protons to return per token. Requires `logprobs` to be true. ### Request Example ```json { "model": "gpt-4.1", "messages": [ { "role": "user", "content": "你好!" } ], "logprobs": true, "top_logprobs": 2 } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the chat completion. - **object** (string) - The type of object returned, usually `chat.completion`. - **created** (integer) - The Unix timestamp (in seconds) of when the completion was created. - **model** (string) - The model used for the completion. - **choices** (array) - A list of completion choices. - **index** (integer) - The index of the choice. - **message** (object) - The message content and role. - **role** (string) - The role of the author of the message. - **content** (string) - The content of the message. - **logprobs** (object) - Contains log probabilities for the tokens in the completion. Only present if `logprobs` is true. - **content** (array) - A list of token log probability information. - **token** (string) - The generated token. - **logprob** (number) - The log probability of the token. - **bytes** (array) - The token in bytes. Null if the token cannot be encoded to bytes. - **top_logprobs** (array) - A list of the top log probabilities for this token. - **token** (string) - The top token. - **logprob** (number) - The log probability of the top token. - **bytes** (array) - The top token in bytes. Null if the token cannot be encoded to bytes. #### Response Example ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1702685778, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "你好!我能为你提供什么帮助?" }, "logprobs": { "content": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111], "top_logprobs": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111] }, { "token": "Hi", "logprob": -1.3190403, "bytes": [72, 105] } ] } ] } } ] } ``` ``` -------------------------------- ### Get Affiliate Code Information (JavaScript Fetch API) Source: https://docs.newapi.ai/api/fei-user This code example shows how to retrieve or generate a user's affiliate code using the Fetch API. It requires user authentication credentials. The response indicates success and provides the affiliate code, or generates one if it doesn't exist. ```javascript const response = await fetch('/api/user/aff', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_user_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` -------------------------------- ### Error Response Example Source: https://docs.newapi.ai/api/openai-audio An example of an error response from the API, indicating an issue with the request. It includes a message, error type, parameter, and error code. ```json { "error": { "message": "文件格式不支持", "type": "invalid_request_error", "param": "file", "code": "invalid_file_format" } } ``` -------------------------------- ### Partial Response Completion Example Source: https://docs.newapi.ai/api/anthropic-chat Shows how to provide a starting point for the assistant's response, allowing it to continue from a given point. This is useful for constraining or guiding the model's output. ```json [ {"role": "user", "content": "太阳的希腊语名字是什么? (A) Sol (B) Helios (C) Sun"}, {"role": "assistant", "content": "正确答案是 ("} ] ``` -------------------------------- ### POST /api/setup Source: https://docs.newapi.ai/api/fei-system-initialization Completes the first-time installation wizard by creating a root administrator account and initializing system configuration. This endpoint is publicly accessible. ```APIDOC ## POST /api/setup ### Description Completes the first-time installation wizard by creating a root administrator account and initializing system configuration. This endpoint is publicly accessible. ### Method POST ### Endpoint /api/setup ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - Administrator username (max 12 characters). - **password** (string) - Required - Administrator password (min 8 characters). - **confirmPassword** (string) - Required - Confirmation of the administrator password (must match password). - **SelfUseModeEnabled** (boolean) - Optional - Whether to enable self-use mode. - **DemoSiteEnabled** (boolean) - Optional - Whether to enable demo site mode. ### Request Example ```javascript const response = await fetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "admin", password: "password123", confirmPassword: "password123", SelfUseModeEnabled: false, DemoSiteEnabled: false }) }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A success message indicating completion. #### Response Example ```json { "success": true, "message": "系统初始化完成" } ``` #### Error Response (e.g., 400) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - An error message describing the failure (e.g., password mismatch, username length). #### Error Response Example ```json { "success": false, "message": "用户名长度不能超过12个字符" } ``` ``` -------------------------------- ### Error Handling Source: https://docs.newapi.ai/api/google-gemini-chat This section provides a comprehensive guide to error codes, their descriptions, and resolution strategies, along with an example error response. ```APIDOC ## Error Handling ### Common Error Codes - `400`: Bad Request - Malformed request or invalid parameters. - `401`: Unauthorized - Invalid or missing API key. - `403`: Forbidden - Insufficient permissions or quota exceeded. - `429`: Too Many Requests - Request frequency too high. - `500`: Internal Server Error - Server encountered an unexpected condition. ### Detailed Error Code Explanations - **400 `INVALID_ARGUMENT`**: Invalid request argument or format. **Solution**: Check request parameter format and required fields. - **400 `FAILED_PRECONDITION`**: Precondition for the request is not met. **Solution**: Ensure that the preconditions for the API call are met. - **401 `UNAUTHENTICATED`**: API key is invalid, missing, or expired. **Solution**: Verify the validity and format of the API key. - **403 `PERMISSION_DENIED`**: Insufficient permissions or quota exhausted. **Solution**: Check API key permissions or upgrade quota. - **404 `NOT_FOUND`**: The specified model or resource does not exist. **Solution**: Verify the model name and resource path. - **413 `PAYLOAD_TOO_LARGE`**: Request body is too large. **Solution**: Reduce the input content size or process in batches. - **429 `RESOURCE_EXHAUSTED`**: Request frequency exceeds limit or quota insufficient. **Solution**: Lower the request frequency or wait for quota reset. - **500 `INTERNAL`**: Internal server error. **Solution**: Retry the request; contact support if the issue persists. - **503 `UNAVAILABLE`**: Service is temporarily unavailable. **Solution**: Wait for a while and retry. - **504 `DEADLINE_EXCEEDED`**: Request timed out. **Solution**: Reduce input size or retry the request. ### Error Response Example ```json { "error": { "code": 400, "message": "Invalid argument: contents", "status": "INVALID_ARGUMENT", "details": [ { "@type": "type.googleapis.com/google.rpc.BadRequest", "fieldViolations": [ { "field": "contents", "description": "contents is required" } ] } ] } } ``` ``` -------------------------------- ### Best Practices Source: https://docs.newapi.ai/api/query-video Recommendations for effectively using the AI Video Generation API. ```APIDOC ## Best Practices 1. **Status Checking**: Regularly check task status to avoid excessive request frequency. 2. **Error Handling**: Properly handle various error conditions, including network and API errors. 3. **Timeout Settings**: Implement reasonable timeout durations to prevent indefinite waiting. 4. **Caching Strategy**: Consider caching results for completed videos. 5. **Concurrency Control**: Avoid initiating too many query requests simultaneously. 6. **Resource Cleanup**: Download and clean up unnecessary video files in a timely manner. ``` -------------------------------- ### Query Token Usage - cURL Request Example Source: https://docs.newapi.ai/api/token-usage An example using cURL to send a GET request to the token usage endpoint. It demonstrates how to include the Authorization header with your Bearer token. This is a common way to interact with the API for testing or scripting. ```bash curl -X GET https://yournewapi_server_address/api/usage/token \ -H "Authorization: Bearer $NEWAPI_API_KEY" ``` -------------------------------- ### Streaming Responses with Anthropic Messages API Source: https://docs.newapi.ai/api/anthropic-chat This `curl` example shows how to enable streaming responses from the Anthropic Messages API by setting `"stream": true`. The response will be delivered in chunks, starting with message metadata and then content blocks as they are generated. This is useful for real-time applications where immediate feedback is desired. ```bash curl https://你的newapi服务器地址/v1/messages \ --header "anthropic-version: 2023-06-01" \ --header "content-type: application/json" \ --header "x-api-key: $NEWAPI_API_KEY" \ --data \ '{ "model": "claude-3-5-sonnet-20241022", "messages": [ { "role": "user", "content": "讲个故事" } ], "stream": true }' ``` -------------------------------- ### GET /api/setup Source: https://docs.newapi.ai/api/fei-system-initialization Checks the system's initialization status, including database type and root user status. This endpoint is publicly accessible and does not require authentication. ```APIDOC ## GET /api/setup ### Description Checks the system's initialization status, including database type and root user status. This endpoint is publicly accessible. ### Method GET ### Endpoint /api/setup ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/setup', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains initialization status details: - **status** (boolean) - Whether the system has completed initialization. - **root_init** (boolean) - Whether the root user has been initialized. - **database_type** (string) - The type of database being used (e.g., "mysql", "postgres", "sqlite"). #### Response Example ```json { "success": true, "data": { "status": false, "root_init": true, "database_type": "sqlite" } } ``` #### Error Response (e.g., 500) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - An error message describing the failure. #### Error Response Example ```json { "success": false, "message": "系统错误" } ``` ``` -------------------------------- ### GET /api/status Source: https://docs.newapi.ai/api/fei-system-initialization Retrieves a summary of the system's operational status, including version, uptime, and configuration settings like OAuth and feature flags. This endpoint is publicly accessible. ```APIDOC ## GET /api/status ### Description Retrieves a summary of the system's operational status, including version, uptime, and configuration settings like OAuth and feature flags. This endpoint is publicly accessible. ### Method GET ### Endpoint /api/status ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - An empty string if successful. - **data** (object) - Contains system status details: - **version** (string) - The system version number. - **start_time** (number) - The system's start timestamp. - **email_verification** (boolean) - Whether email verification is enabled. - **github_oauth** (boolean) - Whether GitHub OAuth login is enabled. - **github_client_id** (string) - The GitHub OAuth client ID. - **system_name** (string) - The name of the system. - **quota_per_unit** (number) - The quota quantity per unit. - **display_in_currency** (boolean) - Whether to display in currency format. - **enable_drawing** (boolean) - Whether the drawing feature is enabled. - **enable_task** (boolean) - Whether the task feature is enabled. - **setup** (boolean) - Whether the system has completed initialization. #### Response Example ```json { "success": true, "message": "", "data": { "version": "v1.0.0", "start_time": 1640995200, "email_verification": false, "github_oauth": true, "github_client_id": "your_client_id", "system_name": "New API", "quota_per_unit": 500000, "display_in_currency": true, "enable_drawing": true, "enable_task": true, "setup": true } } ``` #### Error Response (e.g., 500) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - An error message describing the failure. #### Error Response Example ```json { "success": false, "message": "获取状态失败" } ``` ``` -------------------------------- ### Web Search Options Parameter Source: https://docs.newapi.ai/api/openai-chat Configuration for the web search tool, including context size and user location. ```APIDOC ## Web Search Options Parameter ### Description This tool searches the web for relevant results to use in the reply. ### Method Not Applicable (Parameter Description) ### Endpoint Not Applicable (Parameter Description) ### Parameters #### Request Body Parameters - **web_search_options** (object) - Optional - Configuration for the web search tool. - Properties: - **search_context_size** (string) - Optional - A high-level guidance for the amount of context window space to use for searching. Possible values are 'low', 'medium', or 'high'. 'medium' is the default. - **user_location** (object or null) - Optional - Approximate location parameters for the search. - Properties: - **approximate** (object) - Required - Approximate location parameters for the search. - Properties: - **city** (string) - Optional - Free-form text input for the user's city, e.g. San Francisco. - **country** (string) - Optional - The user's two-letter ISO country code, e.g. US. - **region** (string) - Optional - Free-form text input for the user's region, e.g. California. - **timezone** (string) - Optional - The user's IANA timezone, e.g. America/Los_Angeles. - **type** (string) - Required - The type of location approximation. Always 'approximate'. ``` -------------------------------- ### Test Backend and Dependencies (JavaScript) Source: https://docs.newapi.ai/api/fei-system-initialization Tests the connectivity and health of the system's backend components, including the database and Redis. Requires administrator authentication. ```javascript const response = await fetch('/api/status/test', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_admin_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` -------------------------------- ### Get Video Content with cURL Source: https://docs.newapi.ai/api/query-video This cURL example shows how to download the generated video file using its video ID. The response is a direct video stream, typically in MP4 format. ```shell curl 'https://你的newapi服务器地址/v1/videos/video_123/content' \ -H "Authorization: Bearer sk-xxxx" \ -o "video.mp4" ``` -------------------------------- ### Register New Account (JavaScript) Source: https://docs.newapi.ai/api/fei-user Creates a new user account. Supports email verification and referral codes. Requires username, password, and optionally email, verification_code, and aff_code. Returns success or failure messages. ```javascript const response = await fetch('/api/user/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "newuser", password: "password123", email: "user@example.com", verification_code: "123456", aff_code: "INVITE123" }) }); const data = await response.json(); ``` -------------------------------- ### System Instruction Configuration Source: https://docs.newapi.ai/api/google-gemini-chat Configure the system instruction for the developer, currently supporting text-based instructions. ```APIDOC ## System Instruction Configuration (`systemInstruction`) ### Description Developer-set system instructions. Currently, only text-based instructions are supported. ### SystemInstruction Object Properties - **content** (object) - Required - Content object, currently only supporting text. ``` -------------------------------- ### Query Single Task Status with Suno API (curl) Source: https://docs.newapi.ai/api/suno-music This example shows how to query the status of a single task using the Suno Music API. It sends a GET request to the /suno/fetch/{{task_id}} endpoint, where {{task_id}} is the ID of the task to query. The API returns detailed status information for the specified task. ```curl curl --location 'https://你的newapi服务器地址/suno/fetch/{{task_id}}' \ --header 'Authorization: Bearer $NEWAPI_API_KEY' ``` -------------------------------- ### Get All Groups List (Admin API) - JavaScript Example Source: https://docs.newapi.ai/api/fei-group This JavaScript code snippet demonstrates how to fetch a list of all user group names using the `/api/group/` endpoint. It requires administrator authentication via a Bearer token and a 'New-Api-User' header. The response includes a success status, a message, and an array of group names. ```javascript const response = await fetch('/api/group/', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_admin_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` -------------------------------- ### Audio Output Parameters Source: https://docs.newapi.ai/api/openai-chat Configure audio output settings when requesting audio modalities. ```APIDOC ## Audio Output Parameters ### Description Parameters for audio output. Required when requesting audio output with `modalities: ["audio"]`. ### Parameters #### Request Body - **audio** (object | null) - Optional - Parameters for audio output. - **format** (string) - Required - Specifies the output audio format. Must be one of: `wav`, `mp3`, `flac`, `opus`, or `pcm16`. - **voice** (string) - Required - The voice model will use for the response. Supported voices include: `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, and `shimmer`. ``` -------------------------------- ### POST /api/option/migrate_console_setting Source: https://docs.newapi.ai/api/fei-site-configuration Migrates console settings from older versions to the new configuration format. This includes API information, announcements, FAQs, and Uptime Kuma settings. This operation is accessible only by Root users. ```APIDOC ## POST /api/option/migrate_console_setting ### Description Migrates console settings from older versions to the new configuration format. This includes API information, announcements, FAQs, and Uptime Kuma settings. This operation is accessible only by Root users. ### Method POST ### Endpoint /api/option/migrate_console_setting ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const response = await fetch('/api/option/migrate_console_setting', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_root_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of successful migration. #### Response Example ```json { "success": true, "message": "migrated" } ``` #### Error Response Example ```json { "success": false, "message": "迁移失败" } ``` ### Notes Migration includes: - `ApiInfo` → `console_setting.api_info` - `Announcements` → `console_setting.announcements` - `FAQ` → `console_setting.faq` - `UptimeKumaUrl/UptimeKumaSlug` → `console_setting.uptime_kuma_groups` ``` -------------------------------- ### Mixed Content Blocks Example Source: https://docs.newapi.ai/api/anthropic-chat Example demonstrating a response containing both text and tool_use content blocks. ```json [ {"type": "text", "text": "你好,我是 Claude。"} ] ``` ```json [ { "type": "tool_use", "id": "toolu_xyz...", "name": "get_weather", "input": { "location": "北京" } } ] ``` ```json [ {"type": "text", "text": "根据天气查询结果:"}, { "type": "tool_use", "id": "toolu_xyz...", "name": "get_weather", "input": { "location": "北京" } } ] ``` -------------------------------- ### Text Content Block Example Source: https://docs.newapi.ai/api/anthropic-chat Example of a text content block representing standard text output from the model. ```json { "type": "text", // 必需,枚举值: "text",默认值 "text": "你好,我是 Claude。" // 必需,最大长度: 5000000,最小长度: 1 } ``` -------------------------------- ### Best Practices Source: https://docs.newapi.ai/api/openai-video Recommended guidelines for using the API effectively. ```APIDOC ## Best Practices 1. **Request Format**: Use `multipart/form-data` for requests, as recommended by OpenAI. 2. **`input_reference` Parameter**: For image-to-video functionality, use the `@filename` syntax when uploading image files. 3. **Prompt Optimization**: Craft detailed and specific prompts, including style and quality requirements. 4. **Parameter Settings**: Appropriately set duration and resolution based on your needs. 5. **Ali Wanxiang Specifics**: * Files cannot be uploaded directly; all resources must be passed via URLs. * Use the `metadata` parameter (as a JSON string) to pass all extended parameters. * For image-to-video, pass the image URL via `metadata.img_url`. * For frame-to-frame video, pass the frame URLs via `metadata.first_frame_url` and `metadata.last_frame_url`. 6. **Error Handling**: Implement robust retry mechanisms and error handling. 7. **Asynchronous Processing**: Video generation is an asynchronous task; periodically poll for status updates. 8. **Resource Management**: Download and clean up generated video files promptly to avoid storage issues. ``` -------------------------------- ### Function Calling with Gemini API Source: https://docs.newapi.ai/api/google-gemini-chat Example demonstrating function calling with the Gemini API. It defines tool functions (`enable_lights`, `set_light_color`, `stop_lights`) and configures the model for automatic function calling. The request includes system instructions and user content. ```shell cat > tools.json << EOF { "function_declarations": [ { "name": "enable_lights", "description": "Turn on the lighting system." }, { "name": "set_light_color", "description": "Set the light color. Lights must be enabled for this to work.", "parameters": { "type": "object", "properties": { "rgb_hex": { "type": "string", "description": "The light color as a 6-digit hex string, e.g. ff0000 for red." } }, "required": [ "rgb_hex" ] } }, { "name": "stop_lights", "description": "Turn off the lighting system." } ] } EOF curl "https://你的newapi服务器地址/v1beta/models/gemini-2.0-flash:generateContent?key=$NEWAPI_API_KEY" \ -H 'Content-Type: application/json' \ -d @<(echo ' { "system_instruction": { "parts": { "text": "You are a helpful lighting system bot. You can turn lights on and off, and you can set the color. Do not perform any other tasks." } }, "tools": ['$(cat tools.json)'], "tool_config": { "function_calling_config": {"mode": "auto"} }, "contents": { "role": "user", "parts": { "text": "Turn on the lights please." } } } ') 2>/dev/null |sed -n '/"content"/,/"finishReason"/p' ``` -------------------------------- ### Tool Result Content Block Example Source: https://docs.newapi.ai/api/anthropic-chat Example of a tool_result content block returned by the API after executing a tool, linking back to the tool_use_id. ```json [ { "type": "tool_result", "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "content": "北京当前天气晴朗,温度 25°C" } ] ``` -------------------------------- ### Custom Tool Definition Example Source: https://docs.newapi.ai/api/anthropic-chat An example of defining a custom tool, including its type, name, description, and input schema using JSON Schema. ```json [ { "type": "custom", "name": "get_weather", "description": "获取指定位置的当前天气", "input_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名称,如:北京" } }, "required": ["location"] } } ] ``` -------------------------------- ### Submit Payment Order (JavaScript Fetch API) Source: https://docs.newapi.ai/api/fei-user This example demonstrates creating an online payment order using the Fetch API. It supports various payment methods and requires the amount, payment method, and optionally a top-up code in the request body. The response includes payment details and a URL to complete the transaction. ```javascript const response = await fetch('/api/user/pay', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_user_token', 'New-Api-User': 'your_user_id' }, body: JSON.stringify({ amount: 10000, payment_method: "alipay", top_up_code: "" }) }); const data = await response.json(); ``` -------------------------------- ### Tools Configuration Source: https://docs.newapi.ai/api/google-gemini-chat Configure the tools available for the model to use, including function declarations and code execution capabilities. ```APIDOC ## Tools Configuration ### Description This section describes the configuration for `tools`, which is an array of tools that the model may use to generate the next response. Supported tools include functions and code execution. ### Tool Object Properties - **functionDeclarations** (array) - Optional - An optional list of function declarations. - **codeExecution** (object) - Optional - Enables the model to execute code. #### FunctionDeclaration Object Properties - **name** (string) - Required - The name of the function. - **description** (string) - Optional - A description of the function's purpose. - **parameters** (object) - Optional - The function parameters in JSON Schema format. #### FunctionCall Object Properties - **name** (string) - Required - The name of the function to call. - **args** (object) - Optional - Key-value pairs of the function's arguments. #### FunctionResponse Object Properties - **name** (string) - Required - The name of the function called. - **response** (object) - Required - The response data from the function call. #### ExecutableCode Object Properties - **language** (enum) - Required - The programming language of the code. - **code** (string) - Required - The code to execute. #### CodeExecutionResult Object Properties - **outcome** (enum) - Required - The status of the code execution result. - **output** (string) - Optional - The output content of the code execution. #### CodeExecution Object Properties - {} (empty object) - Enables the code execution functionality with an empty configuration object. ``` -------------------------------- ### Tool Use Content Block Example Source: https://docs.newapi.ai/api/anthropic-chat Example of a tool_use content block returned by the model, including the tool's ID, name, and input parameters. ```json [ { "type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_weather", "input": { "location": "北京" } } ] ``` -------------------------------- ### GET /api/status/test Source: https://docs.newapi.ai/api/fei-system-initialization Tests the connectivity and health of the backend and its dependent components, such as the database and Redis. Requires administrator authentication. ```APIDOC ## GET /api/status/test ### Description Tests the connectivity and health of the backend and its dependent components, such as the database and Redis. Requires administrator authentication. ### Method GET ### Endpoint /api/status/test ### Parameters #### Path Parameters None #### Query Parameters None #### Headers - **Authorization** (string) - Required - Bearer token for administrator authentication (e.g., 'Bearer your_admin_token'). - **New-Api-User** (string) - Required - User ID for the administrator. ### Request Example ```javascript const response = await fetch('/api/status/test', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_admin_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the test was successful. - **message** (string) - A message confirming all components tested successfully. - **data** (object) - Contains the status of tested components: - **database** (string) - Database connection status (e.g., "connected"). - **redis** (string) - Redis connection status (e.g., "connected"). - **external_apis** (string) - Status of external API integrations (e.g., "healthy"). #### Response Example ```json { "success": true, "message": "所有组件测试通过", "data": { "database": "connected", "redis": "connected", "external_apis": "healthy" } } ``` #### Error Response (e.g., 500) - **success** (boolean) - Indicates if the test was successful. - **message** (string) - An error message describing the component that failed. #### Error Response Example ```json { "success": false, "message": "数据库连接失败" } ``` ``` -------------------------------- ### Get Task Image Seed - GET Request Source: https://docs.newapi.ai/api/midjourney-proxy-image Retrieves the seed value used for generating a specific task's image. This is a GET request requiring a Bearer token for authentication. ```curl curl --location --request GET 'https://你的newapi服务器地址/mj/task/{id}/image-seed' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer $NEWAPI_API_KEY' \ --header 'Content-Type: application/json' ``` -------------------------------- ### Affiliate Credit Transfer (JavaScript Fetch API) Source: https://docs.newapi.ai/api/fei-user This code example demonstrates how to transfer affiliate reward credits to usable quota using a POST request with the Fetch API. It requires the user's authentication and the amount of quota to transfer in the request body. Successful transfers are confirmed with a message. ```javascript const response = await fetch('/api/user/aff_transfer', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_user_token', 'New-Api-User': 'your_user_id' }, body: JSON.stringify({ quota: 50000 }) }); const data = await response.json(); ``` -------------------------------- ### AI API Response Example Source: https://docs.newapi.ai/api/google-gemini-chat A complete example of a response object from the AI API, illustrating the structure of candidates, prompt feedback, usage metadata, model version, and response ID. ```json { "candidates": [ { "content": { "parts": [ { "text": "你好!我是 Gemini,一个由 Google 开发的人工智能助手。我可以帮助您解答问题、提供信息、协助写作、代码编程等多种任务。请告诉我有什么可以为您效劳的!" } ], "role": "model" }, "finishReason": "STOP", "index": 0, "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE", "blocked": false }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE", "blocked": false }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE", "blocked": false }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE", "blocked": false } ], "tokenCount": 47 } ], "promptFeedback": { "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE" } ] }, "usageMetadata": { "promptTokenCount": 4, "candidatesTokenCount": 47, "totalTokenCount": 51, "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 4 } ], "candidatesTokensDetails": [ { "modality": "TEXT", "tokenCount": 47 } ] }, "modelVersion": "gemini-2.0-flash", "responseId": "response-12345" } ``` -------------------------------- ### Response Example for Chat Completions with Logprobs (JSON) Source: https://docs.newapi.ai/api/openai-chat This is an example JSON response from the NewAPI AI API when requesting chat completions with log probabilities enabled. It includes the generated message and detailed logprobs for each token, including top logprobs. ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1702685778, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "你好!我能为你提供什么帮助?" }, "logprobs": { "content": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111], "top_logprobs": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111] }, { "token": "Hi", "logprob": -1.3190403, "bytes": [72, 105] } ] }, { "token": "!", "logprob": -0.02380986, "bytes": [ 33 ], "top_logprobs": [ { "token": "!", "logprob": -0.02380986, "bytes": [33] }, { "token": " there", "logprob": -3.787621, "bytes": [32, 116, 104, 101, 114, 101] } ] }, { "token": " How", "logprob": -0.000054669687, "bytes": [32, 72, 111, 119], "top_logprobs": [ { "token": " How", "logprob": -0.000054669687, "bytes": [32, 72, 111, 119] }, { "token": "<|end|>", "logprob": -10.953937, "bytes": null } ] }, { "token": " can", "logprob": -0.015801601, "bytes": [32, 99, 97, 110], "top_logprobs": [ { "token": " can", "logprob": -0.015801601, "bytes": [32, 99, 97, 110] }, { "token": " may", "logprob": -4.161023, "bytes": [32, 109, 97, 121] } ] }, { "token": " I", "logprob": -3.7697225e-6, "bytes": [ 32, 73 ], "top_logprobs": [ { "token": " I", "logprob": -3.7697225e-6, "bytes": [32, 73] }, { "token": " assist", "logprob": -13.596657, "bytes": [32, 97, 115, 115, 105, 115, 116] } ] }, { "token": " assist", "logprob": -0.04571125, "bytes": [32, 97, 115, 115, 105, 115, 116], "top_logprobs": [ { "token": " assist", "logprob": -0.04571125, "bytes": [32, 97, 115, 115, 105, 115, 116] }, { "token": " help", "logprob": -3.1089056, "bytes": [32, 104, 101, 108, 112] } ] }, { "token": " you", "logprob": -5.4385737e-6, "bytes": [32, 121, 111, 117], "top_logprobs": [ { "token": " you", "logprob": -5.4385737e-6, "bytes": [32, 121, 111, 117] }, { "token": " today", "logprob": -12.807695, "bytes": [32, 116, 111, 100, 97, 121] } ] }, { "token": " today", "logprob": -0.0040071653, "bytes": [32, 116, 111, 100, 97, 121], "top_logprobs": [ { "token": " today", "logprob": -0.0040071653, "bytes": [32, 116, 111, 100, 97, 121] }, { "token": "?", "logprob": -5.5247097, "bytes": [63] } ] }, { "token": "?", "logprob": -0.0008108172, "bytes": [63], "top_logprobs": [ { "token": "?", "logprob": -0.0008108172, "bytes": [63] }, { "token": "?\n", "logprob": -7.184561, "bytes": [63, 10] } ] } ] } } ] } ```