### Node.js Integration Example for Pplx2Api Source: https://context7.com/yushangxiao/pplx2api/llms.txt Provides a Node.js example demonstrating basic chat, streaming responses, and search capabilities using the OpenAI Node.js SDK with Pplx2Api. ```APIDOC ## Node.js Integration Example ### Description This section demonstrates how to integrate with Pplx2Api using the OpenAI Node.js SDK. It covers basic chat, streaming responses, and using the search mode. ### Setup Ensure you have Node.js installed. Install the OpenAI SDK: ```bash npm install openai ``` ### Code Examples #### 1. Basic Chat Completion Performs a standard chat completion request. ```javascript const OpenAI = require('openai'); const client = new OpenAI({ apiKey: 'your_api_key', baseURL: 'http://localhost:8080/v1' }); async function basicChat() { const response = await client.chat.completions.create({ model: 'claude-4-6-sonnet', messages: [ { role: 'system', content: '你是一个有帮助的助手。' }, { role: 'user', content: '什么是量子计算?' } ], stream: false }); console.log(response.choices[0].message.content); } ``` #### 2. Streaming Response Handles chat completions that are streamed back in chunks. ```javascript async function streamChat() { const stream = await client.chat.completions.create({ model: 'claude-4-6-sonnet', messages: [ { role: 'user', content: '写一首关于编程的诗' } ], stream: true }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ''; process.stdout.write(content); } console.log(); } ``` #### 3. Search Mode (Web Browsing) Utilizes a model with web browsing capabilities to answer questions based on current information. ```javascript async function searchChat() { const response = await client.chat.completions.create({ model: 'gpt-5.4-search', messages: [ { role: 'user', content: '今天有什么重要的科技新闻?' } ], stream: false }); console.log(response.choices[0].message.content); } ``` #### 4. Executing All Examples An async IIFE to run all the above chat functions. ```javascript (async () => { await basicChat(); await streamChat(); await searchChat(); })(); ``` ``` -------------------------------- ### Python Examples for Pplx2Api Source: https://context7.com/yushangxiao/pplx2api/llms.txt Demonstrates how to use the Pplx2Api with Python for tasks like code analysis, image analysis, and basic chat. ```APIDOC ## Python Examples for Pplx2Api ### Description This section provides Python code examples for interacting with the Pplx2Api, showcasing its capabilities for different AI tasks. ### Code Examples #### 1. Using Thinking Mode for Code Analysis This example demonstrates how to use the `claude-4.6-sonnet-think` model to analyze code complexity. ```python from perplexityai import Client client = Client() response = client.chat.completions.create( model="claude-4.6-sonnet-think", messages=[ {"role": "user", "content": "分析这段代码的时间复杂度:for i in range(n): for j in range(n): print(i, j)"} ], stream=False ) print(response.choices[0].message.content) ``` #### 2. Image Analysis This example shows how to perform image analysis by encoding an image and sending it with a text prompt. ```python import base64 from perplexityai import Client def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8") client = Client() image_data = encode_image("example.jpg") response = client.chat.completions.create( model="claude-4-6-sonnet", messages=[ { "role": "user", "content": [ {"type": "text", "text": "描述这张图片的内容"}, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{image_data}" } } ] } ], stream=False ) print(response.choices[0].message.content) ``` ``` -------------------------------- ### Node.js: Basic, Streaming, and Search Chat Completions with Pplx2api Source: https://context7.com/yushangxiao/pplx2api/llms.txt This Node.js example showcases three ways to interact with the Pplx2api service using the OpenAI Node.js SDK. It includes a basic chat completion, a streaming chat completion for real-time responses, and a search-enabled chat completion for accessing current information. ```javascript const OpenAI = require('openai'); const client = new OpenAI({ apiKey: 'your_api_key', baseURL: 'http://localhost:8080/v1' }); async function basicChat() { const response = await client.chat.completions.create({ model: 'claude-4-6-sonnet', messages: [ { role: 'system', content: '你是一个有帮助的助手。' }, { role: 'user', content: '什么是量子计算?' } ], stream: false }); console.log(response.choices[0].message.content); } async function streamChat() { const stream = await client.chat.completions.create({ model: 'claude-4-6-sonnet', messages: [ { role: 'user', content: '写一首关于编程的诗' } ], stream: true }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ''; process.stdout.write(content); } console.log(); } async function searchChat() { const response = await client.chat.completions.create({ model: 'gpt-5.4-search', messages: [ { role: 'user', content: '今天有什么重要的科技新闻?' } ], stream: false }); console.log(response.choices[0].message.content); } (async () => { await basicChat(); await streamChat(); await searchChat(); })(); ``` -------------------------------- ### Pplx2Api Image Analysis API Request Source: https://github.com/yushangxiao/pplx2api/blob/main/README.md This example shows how to perform image analysis using the Pplx2Api. It demonstrates sending a request with both text and an image URL (base64 encoded) to the chat completions endpoint. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-3.7-sonnet", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "这张图片里有什么?" }, { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,...". } } ] } ] }' ``` -------------------------------- ### GET /v1/models Source: https://context7.com/yushangxiao/pplx2api/llms.txt Retrieves a list of all supported models, including standard and search-enabled variants. ```APIDOC ## GET /v1/models ### Description Returns a list of available AI models supported by the proxy. ### Method GET ### Endpoint /v1/models ### Parameters #### Query Parameters - **Authorization** (header) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **data** (array) - List of model objects containing the model id. #### Response Example { "data": [ {"id": "claude-4-6-sonnet"}, {"id": "claude-4-6-sonnet-search"} ] } ``` -------------------------------- ### GET /health Source: https://context7.com/yushangxiao/pplx2api/llms.txt Checks the health status of the Pplx2Api service. ```APIDOC ## GET /health ### Description Checks if the service is running correctly. ### Method GET ### Endpoint /health ### Parameters #### Query Parameters - **Authorization** (header) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **status** (string) - The status of the service (e.g., "ok"). #### Response Example { "status": "ok" } ``` -------------------------------- ### Deployment Options Source: https://github.com/yushangxiao/pplx2api/blob/main/README.md Information on how to deploy and run the Pplx2Api service using Docker or Docker Compose. ```APIDOC ## Docker Deployment ### Description Instructions for deploying Pplx2Api using Docker. ### Command ```bash docker run -d \ -p 8080:8080 \ -e SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0**,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0** \ -e APIKEY=123 \ -e IS_INCOGNITO=true \ -e MAX_CHAT_HISTORY_LENGTH=10000 \ -e NO_ROLE_PREFIX=false \ --name pplx2api \ ghcr.io/yushangxiao/pplx2api:latest ``` ### Environment Variables - **SESSIONS**: Required. Comma-separated Perplexity AI session tokens. - **APIKEY**: Required. Your custom API key for authentication. - **IS_INCOGNITO**: Optional. Use private sessions (default: true). - **MAX_CHAT_HISTORY_LENGTH**: Optional. Maximum chat history length before converting to a file (default: 10000). - **NO_ROLE_PREFIX**: Optional. Do not prepend role to messages (default: false). ``` ```APIDOC ## Docker Compose Deployment ### Description Instructions for deploying Pplx2Api using Docker Compose. ### File: `docker-compose.yml` ```yaml version: '3' services: pplx2api: image: ghcr.io/yushangxiao/pplx2api:latest container_name: pplx ports: - "8080:8080" environment: - SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0**,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0** - ADDRESS=0.0.0.0:8080 - APIKEY=123 - PROXY=http://proxy:2080 # Optional - MAX_CHAT_HISTORY_LENGTH=10000 - NO_ROLE_PREFIX=false - IS_INCOGNITO=true - SEARCH_RESULT_COMPATIBLE=false restart: unless-stopped ``` ### Command ```bash docker-compose up -d ``` ### Environment Variables - **SESSIONS**: Required. Comma-separated Perplexity AI session tokens. - **ADDRESS**: Optional. Server address and port (default: `0.0.0.0:8080`). - **APIKEY**: Required. Your custom API key for authentication. - **PROXY**: Optional. HTTP proxy URL. - **MAX_CHAT_HISTORY_LENGTH**: Optional. Maximum chat history length before converting to a file (default: 10000). - **NO_ROLE_PREFIX**: Optional. Do not prepend role to messages (default: false). - **IS_INCOGNITO**: Optional. Use private sessions (default: true). - **SEARCH_RESULT_COMPATIBLE**: Optional. Disable search result scaling blocks for better client compatibility (default: false). ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/yushangxiao/pplx2api/llms.txt A reference template for the .env file, detailing all available configuration parameters for the Pplx2Api service. ```bash SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0...,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0... APIKEY=your_secure_api_key_here ADDRESS=0.0.0.0:8080 PROXY=http://127.0.0.1:2080 IS_INCOGNITO=true MAX_CHAT_HISTORY_LENGTH=10000 NO_ROLE_PREFIX=false SEARCH_RESULT_COMPATIBLE=false PROMPT_FOR_FILE=You must immerse yourself in the role of assistant in txt file... IGNORE_SEARCH_RESULT=false IGNORE_MODEL_MONITORING=false IS_MAX_SUBSCRIBE=false ``` -------------------------------- ### Integrate with OpenAI Python SDK Source: https://context7.com/yushangxiao/pplx2api/llms.txt Demonstrates how to connect the OpenAI Python SDK to the Pplx2Api service to perform standard and search-enabled chat completions. ```python from openai import OpenAI client = OpenAI( api_key="your_api_key", base_url="http://localhost:8080/v1" ) # Standard chat completion response = client.chat.completions.create( model="claude-4-6-sonnet", messages=[{"role": "user", "content": "请用一句话解释人工智能是什么?"}], stream=False ) # Streaming response stream = client.chat.completions.create( model="claude-4-6-sonnet", messages=[{"role": "user", "content": "写一个关于机器学习的简短介绍"}], stream=True ) # Search-enabled completion response = client.chat.completions.create( model="claude-4-6-sonnet-search", messages=[{"role": "user", "content": "最新的 AI 发展动态是什么?"}], stream=False ) ``` -------------------------------- ### Docker Deployment for Pplx2Api Source: https://github.com/yushangxiao/pplx2api/blob/main/README.md This snippet shows how to deploy Pplx2Api using Docker. It includes environment variables for session tokens, API keys, and other configurations. It also demonstrates deployment using Docker Compose. ```bash docker run -d \ -p 8080:8080 \ -e SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0**,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0** \ -e APIKEY=123 \ -e IS_INCOGNITO=true \ -e MAX_CHAT_HISTORY_LENGTH=10000 \ -e NO_ROLE_PREFIX=false \ -e SEARCH_RESULT_COMPATIBLE=false \ --name pplx2api \ ghcr.io/yushangxiao/pplx2api:latest ``` ```yaml version: '3' services: pplx2api: image: ghcr.io/yushangxiao/pplx2api:latest container_name: pplx ports: - "8080:8080" environment: - SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0**,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0** - ADDRESS=0.0.0.0:8080 - APIKEY=123 - PROXY=http://proxy:2080 # 可选 - MAX_CHAT_HISTORY_LENGTH=10000 - NO_ROLE_PREFIX=false - IS_INCOGNITO=true - SEARCH_RESULT_COMPATIBLE=false restart: unless-stopped ``` -------------------------------- ### Deploy Pplx2Api with Docker Source: https://context7.com/yushangxiao/pplx2api/llms.txt Provides the command to run the Pplx2Api container with essential environment variables for session tokens, API keys, and proxy settings. ```bash docker run -d \ -p 8080:8080 \ -e SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0...,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0... \ -e APIKEY=your_secure_api_key \ -e IS_INCOGNITO=true \ -e MAX_CHAT_HISTORY_LENGTH=10000 \ -e NO_ROLE_PREFIX=false \ -e SEARCH_RESULT_COMPATIBLE=false \ -e PROXY=http://proxy:2080 \ -e IGNORE_SEARCH_RESULT=false \ -e IGNORE_MODEL_MONITORING=false \ -e IS_MAX_SUBSCRIBE=false \ --name pplx2api \ ghcr.io/yushangxiao/pplx2api:latest ``` -------------------------------- ### Interact with HuggingFace Compatible Routes Source: https://context7.com/yushangxiao/pplx2api/llms.txt Shows how to use the /hf/v1/ prefix for chat completions and model listing, specifically designed for HuggingFace Space deployments. ```bash curl -X POST http://localhost:8080/hf/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "gpt-5.4", "messages": [ { "role": "user", "content": "Hello!" } ], "stream": false }' curl -X GET http://localhost:8080/hf/v1/models \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Manage Deployment with Docker Compose Source: https://context7.com/yushangxiao/pplx2api/llms.txt Configuration file and commands for managing the Pplx2Api service lifecycle using Docker Compose. ```yaml version: '3' services: pplx2api: image: ghcr.io/yushangxiao/pplx2api:latest container_name: pplx2api ports: - "8080:8080" environment: - SESSIONS=session_token_1,session_token_2 - ADDRESS=0.0.0.0:8080 - APIKEY=your_secure_api_key - IS_INCOGNITO=true - MAX_CHAT_HISTORY_LENGTH=10000 - NO_ROLE_PREFIX=false - SEARCH_RESULT_COMPATIBLE=false - PROXY=http://proxy:2080 - IGNORE_SEARCH_RESULT=false - IGNORE_MODEL_MONITORING=false - IS_MAX_SUBSCRIBE=false restart: unless-stopped ``` ```bash docker-compose up -d docker-compose logs -f pplx2api docker-compose down ``` -------------------------------- ### Environment Variable Configuration Source: https://context7.com/yushangxiao/pplx2api/llms.txt Detailed explanation of environment variable configurations for Pplx2Api. ```APIDOC ## Environment Variable Configuration ### Description Provides a comprehensive overview and explanation of all available environment variables for configuring Pplx2Api. ### `.env` File Example ```bash # Required: Perplexity Session Token # Obtain the value of __Secure-next-auth.session-token from the Cookie on the Perplexity website # Separate multiple accounts with English commas, supports automatic round-robin and retry on failure SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0...,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0... # Required: API Authentication Key APIKEY=your_secure_api_key_here # Service listening address (default: 0.0.0.0:8080) ADDRESS=0.0.0.0:8080 # HTTP proxy address (optional) PROXY=http://127.0.0.1:2080 # Incognito mode, conversations are not saved on the Perplexity official website (default: true) IS_INCOGNITO=true # Maximum chat history length, context exceeding this length will be uploaded as a file (default: 10000) MAX_CHAT_HISTORY_LENGTH=10000 # Disable message role prefix (default: false) NO_ROLE_PREFIX=false # Search result compatibility mode, disable scaling blocks (default: false) SEARCH_RESULT_COMPATIBLE=false # System prompt for uploading context as a file PROMPT_FOR_FILE=You must immerse yourself in the role of assistant in txt file... # Ignore search results (default: false) IGNORE_SEARCH_RESULT=false # Ignore model monitoring (default: false) IGNORE_MODEL_MONITORING=false # Max subscriber mode, enable advanced models like Claude Opus (default: false) IS_MAX_SUBSCRIBE=false ``` ### Variable Descriptions - **SESSIONS**: Your Perplexity session token(s). Use comma separation for multiple accounts. Essential for authentication. - **APIKEY**: A secure API key for authenticating requests to your Pplx2Api service. - **ADDRESS**: The network interface and port the service listens on. Defaults to `0.0.0.0:8080`. - **PROXY**: Specifies an HTTP proxy to use for outgoing requests. Optional. - **IS_INCOGNITO**: If set to `true`, conversations are not saved on the Perplexity website. Defaults to `true`. - **MAX_CHAT_HISTORY_LENGTH**: Defines the maximum number of tokens for chat history. Content exceeding this limit will be treated as a file upload. Defaults to `10000`. - **NO_ROLE_PREFIX**: If `true`, role prefixes (like `User:` or `Assistant:`) are not added to messages. Defaults to `false`. - **SEARCH_RESULT_COMPATIBLE**: Enables a compatibility mode for search results, disabling scaling blocks. Defaults to `false`. - **PROMPT_FOR_FILE**: A system prompt used when context is uploaded as a file, guiding the AI's behavior. - **IGNORE_SEARCH_RESULT**: If `true`, search results will not be displayed. Defaults to `false`. - **IGNORE_MODEL_MONITORING**: If `true`, model monitoring features are disabled. Defaults to `false`. - **IS_MAX_SUBSCRIBE**: If `true`, enables access to advanced models available for Max subscribers. Defaults to `false`. ``` -------------------------------- ### Python SDK Integration Source: https://context7.com/yushangxiao/pplx2api/llms.txt Integrate Pplx2Api services using the OpenAI Python SDK. ```APIDOC ## Python SDK Integration ### Description Demonstrates how to integrate with Pplx2Api using the popular OpenAI Python SDK, including basic chat, streaming responses, and utilizing the search mode. ### Setup First, ensure you have the `openai` library installed: ```bash pip install openai ``` ### Basic Chat Completion ```python from openai import OpenAI # Configure the client to connect to the Pplx2Api service client = OpenAI( api_key="your_api_key", base_url="http://localhost:8080/v1" ) # Basic chat completion response = client.chat.completions.create( model="claude-4-6-sonnet", messages=[ {"role": "system", "content": "你是一个有帮助的助手。"}, {"role": "user", "content": "请用一句话解释人工智能是什么?"} ], stream=False ) print(response.choices[0].message.content) ``` ### Streaming Response ```python # Streaming response stream = client.chat.completions.create( model="claude-4-6-sonnet", messages=[ {"role": "user", "content": "写一个关于机器学习的简短介绍"} ], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) print() ``` ### Using Search Mode ```python # Use search mode to get the latest information response = client.chat.completions.create( model="claude-4-6-sonnet-search", messages=[ {"role": "user", "content": "最新的 AI 发展动态是什么?"} ], stream=False ) print(response.choices[0].message.content) ``` ``` -------------------------------- ### Docker Deployment Source: https://context7.com/yushangxiao/pplx2api/llms.txt Quickly deploy the service using Docker, supporting multi-account round-robin and full environment variable configuration. ```APIDOC ## Docker Deployment ### Description Deploy the Pplx2Api service using Docker. This command allows for quick setup and configuration via environment variables. ### Command ```bash docker run -d \ -p 8080:8080 \ -e SESSIONS=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0...,eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0... \ -e APIKEY=your_secure_api_key \ -e IS_INCOGNITO=true \ -e MAX_CHAT_HISTORY_LENGTH=10000 \ -e NO_ROLE_PREFIX=false \ -e SEARCH_RESULT_COMPATIBLE=false \ -e PROXY=http://proxy:2080 \ -e IGNORE_SEARCH_RESULT=false \ -e IGNORE_MODEL_MONITORING=false \ -e IS_MAX_SUBSCRIBE=false \ --name pplx2api \ ghcr.io/yushangxiao/pplx2api:latest ``` ### Environment Variables - **SESSIONS**: Perplexity session tokens (comma-separated for multiple accounts). - **APIKEY**: API authentication key. - **IS_INCOGNITO**: Enable incognito mode (default: `true`). - **MAX_CHAT_HISTORY_LENGTH**: Maximum chat history length before context is uploaded as a file (default: `10000`). - **NO_ROLE_PREFIX**: Whether to add role prefix to messages (default: `false`). - **SEARCH_RESULT_COMPATIBLE**: Enable search result compatibility mode (default: `false`). - **PROXY**: HTTP proxy address (e.g., `http://proxy:2080`). - **IGNORE_SEARCH_RESULT**: Ignore search result display (default: `false`). - **IGNORE_MODEL_MONITORING**: Ignore model monitoring (default: `false`). - **IS_MAX_SUBSCRIBE**: Enable Max subscriber mode for advanced models (default: `false`). ``` -------------------------------- ### HuggingFace Compatible Routes Source: https://context7.com/yushangxiao/pplx2api/llms.txt Provides routes with the `/hf/v1/` prefix for easy deployment in HuggingFace Spaces. ```APIDOC ## Chat Completions (HuggingFace Compatible) ### Description Uses the `/hf/v1/chat/completions` endpoint for chat interactions, compatible with HuggingFace deployments. ### Method POST ### Endpoint `/hf/v1/chat/completions` ### Parameters #### Request Body - **model** (string) - Required - The model to use, e.g., `gpt-5.4`. - **messages** (array) - Required - An array of message objects. - **role** (string) - Required - The role of the message sender (`user`, `assistant`, `system`). - **content** (string) - Required - The content of the message. - **stream** (boolean) - Optional - Whether to stream the response. ### Request Example ```json { "model": "gpt-5.4", "messages": [ { "role": "user", "content": "Hello!" } ], "stream": false } ``` ## List Models (HuggingFace Compatible) ### Description Retrieves a list of available models using the `/hf/v1/models` endpoint. ### Method GET ### Endpoint `/hf/v1/models` ### Parameters None ### Request Example ```bash curl -X GET http://localhost:8080/hf/v1/models \ -H "Authorization: Bearer YOUR_API_KEY" ``` ``` -------------------------------- ### Pplx2Api Use Cases and Integration Source: https://context7.com/yushangxiao/pplx2api/llms.txt Details the primary use cases for Pplx2Api, including seamless switching to Perplexity AI, enabling web search for AI applications, and deploying as an internal AI gateway. It also covers integration methods and deployment options. ```APIDOC ## Pplx2Api Use Cases and Integration ### Description This section outlines the main applications of Pplx2Api and provides guidance on how to integrate and deploy it. ### Key Use Cases * **Seamless OpenAI API Transition**: Easily switch existing OpenAI-API-compatible applications to use Perplexity AI's backend. * **Unified Model Access**: Access multiple AI models through a single, standardized interface. * **Web Search Integration**: Equip AI applications with real-time information retrieval capabilities through web search. * **Internal AI Gateway**: Deploy as a centralized AI gateway within an enterprise, enhancing service availability and stability with features like multi-account rotation and automatic retries. ### Integration Methods Pplx2Api offers a standard OpenAI-compatible API, allowing direct integration with any OpenAI SDK (Python, Node.js, Go, etc.). ### Deployment Options * **Docker & Docker Compose**: Facilitates quick setup and deployment in various environments. * **HuggingFace Spaces**: Provides a compatible route for one-click deployment on the HuggingFace platform. ### Configuration Key functionalities like session management, proxy settings, and privacy mode can be flexibly configured using environment variables to meet specific business requirements. ``` -------------------------------- ### Docker Compose Deployment Source: https://context7.com/yushangxiao/pplx2api/llms.txt Use Docker Compose for more convenient deployment management. ```APIDOC ## Docker Compose Deployment ### Description Deploy and manage Pplx2Api using Docker Compose for a streamlined experience. ### `docker-compose.yml` Example ```yaml version: '3' services: pplx2api: image: ghcr.io/yushangxiao/pplx2api:latest container_name: pplx2api ports: - "8080:8080" environment: # Perplexity official website Cookie __Secure-next-auth.session-token value # Separate multiple accounts with English commas, supports automatic round-robin and retry on failure - SESSIONS=session_token_1,session_token_2 - ADDRESS=0.0.0.0:8080 - APIKEY=your_secure_api_key # Privacy mode, conversations are not saved on the official website - IS_INCOGNITO=true # Context exceeding this length will be uploaded as a file - MAX_CHAT_HISTORY_LENGTH=10000 # Whether to add role prefix before messages - NO_ROLE_PREFIX=false # Disable search result scaling blocks, compatible with more clients - SEARCH_RESULT_COMPATIBLE=false # HTTP proxy address (optional) - PROXY=http://proxy:2080 # Ignore search result display - IGNORE_SEARCH_RESULT=false # Ignore model monitoring - IGNORE_MODEL_MONITORING=false # Whether it is a Max subscription user (enables more models) - IS_MAX_SUBSCRIBE=false restart: unless-stopped ``` ### Docker Compose Commands - **Start service**: `docker-compose up -d` - **View logs**: `docker-compose logs -f pplx2api` - **Stop service**: `docker-compose down` ``` -------------------------------- ### Python: Analyze Code Complexity and Image Content with Pplx2api Source: https://context7.com/yushangxiao/pplx2api/llms.txt This Python snippet demonstrates how to use the Pplx2api client to analyze code for time complexity and to describe the content of an image. It utilizes the 'claude-4.6-sonnet-think' model for code analysis and 'claude-4-6-sonnet' for image analysis, requiring base64 encoding for image data. ```python import base64 response = client.chat.completions.create( model="claude-4.6-sonnet-think", messages=[ {"role": "user", "content": "分析这段代码的时间复杂度:for i in range(n): for j in range(n): print(i, j)"} ], stream=False ) print(response.choices[0].message.content) def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8") image_data = encode_image("example.jpg") response = client.chat.completions.create( model="claude-4-6-sonnet", messages=[ { "role": "user", "content": [ {"type": "text", "text": "描述这张图片的内容"}, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{image_data}" } } ] } ], stream=False ) print(response.choices[0].message.content) ``` -------------------------------- ### Think Model (Reasoning Process) API Source: https://context7.com/yushangxiao/pplx2api/llms.txt Utilizes models with the `-think` suffix to obtain the AI's reasoning process, which is outputted within `` tags. This is useful for understanding how the AI arrives at its conclusions. Supports streaming responses. Requires an API key. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-4.6-sonnet-think", "messages": [ { "role": "user", "content": "解决这个数学问题:如果 x + 2y = 10 且 2x - y = 5,求 x 和 y 的值" } ], "stream": true }' # 响应示例(流式) data: {"id":"...","object":"chat.completion.chunk","created":...,"model":"...","choices":[{"index":0,"delta":{"content":""},"logprobs":null,"finish_reason":null}]} data: {"id":"...","object":"chat.completion.chunk","created":...,"model":"...","choices":[{"index":0,"delta":{"content":"让我分析这个方程组..."},"logprobs":null,"finish_reason":null}]} data: {"id":"...","object":"chat.completion.chunk","created":...,"model":"...","choices":[{"index":0,"delta":{"content":"\n\n"},"logprobs":null,"finish_reason":null}]} data: {"id":"...","object":"chat.completion.chunk","created":...,"model":"...","choices":[{"index":0,"delta":{"content":"解:x = 4, y = 3"},"logprobs":null,"finish_reason":null}]} data: [DONE] ``` -------------------------------- ### List Available Models API Source: https://context7.com/yushangxiao/pplx2api/llms.txt Retrieves a list of all models supported by the Pplx2Api service, including standard and search-enabled versions. This endpoint is useful for discovering available AI models. Requires an API key for authorization. ```bash curl -X GET http://localhost:8080/v1/models \ -H "Authorization: Bearer YOUR_API_KEY" # 响应示例 { "data": [ {"id": "claude-4-6-sonnet"}, {"id": "claude-4-6-sonnet-search"}, {"id": "claude-4.6-sonnet-think"}, {"id": "claude-4.6-sonnet-think-search"}, {"id": "gpt-5.4"}, {"id": "gpt-5.4-search"}, {"id": "gpt-5.4-think"}, {"id": "gpt-5.4-think-search"}, {"id": "gemini-3.1-pro"}, {"id": "gemini-3.1-pro-search"} ] } ``` -------------------------------- ### Chat Completions API (Streaming) Source: https://context7.com/yushangxiao/pplx2api/llms.txt Provides chat responses in a streaming format, delivering content in real-time. This is ideal for interactive applications that require immediate feedback. It uses the same endpoint as non-streaming but with `stream: true`. Requires an API key. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-4-6-sonnet", "messages": [ { "role": "user", "content": "写一首关于春天的诗" } ], "stream": true }' # 流式响应示例 data: {"id":"550e8400-e29b-41d4-a716-446655440000","object":"chat.completion.chunk","created":1699000000,"model":"claude-3-7-sonnet-20250219","choices":[{"index":0,"delta":{"content":"春"},"logprobs":null,"finish_reason":null}]} data: {"id":"550e8400-e29b-41d4-a716-446655440001","object":"chat.completion.chunk","created":1699000000,"model":"claude-3-7-sonnet-20250219","choices":[{"index":0,"delta":{"content":"风"},"logprobs":null,"finish_reason":null}]} data: [DONE] ``` -------------------------------- ### Perform Search-Enabled Chat Completion via cURL Source: https://context7.com/yushangxiao/pplx2api/llms.txt Demonstrates how to trigger a chat completion request with internet search capabilities enabled by using a model with the '-search' suffix. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-4-6-sonnet-search", "messages": [ { "role": "user", "content": "今天的科技新闻有哪些?" } ], "stream": true }' ``` -------------------------------- ### POST /v1/chat/completions Source: https://context7.com/yushangxiao/pplx2api/llms.txt Sends chat messages to the selected model. Supports standard chat, streaming, image analysis, and think mode. ```APIDOC ## POST /v1/chat/completions ### Description Interacts with the AI model to generate responses based on provided messages. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model ID to use. - **messages** (array) - Required - List of message objects (role, content). - **stream** (boolean) - Optional - Whether to stream the response. ### Request Example { "model": "claude-4-6-sonnet", "messages": [{"role": "user", "content": "Hello!"}], "stream": false } ### Response #### Success Response (200) - **id** (string) - Unique identifier for the completion. - **choices** (array) - List of generated responses. #### Response Example { "id": "550e8400-e29b-41d4-a716-446655440000", "choices": [{"message": {"role": "assistant", "content": "Hello! How can I help?"}}] } ``` -------------------------------- ### Chat Completions API (Non-Streaming) Source: https://context7.com/yushangxiao/pplx2api/llms.txt Sends a chat message and receives a complete response. This is suitable for scenarios where real-time output is not required. It supports system and user roles, and requires specifying the model and messages. Requires an API key. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-4-6-sonnet", "messages": [ { "role": "system", "content": "你是一个有帮助的助手。" }, { "role": "user", "content": "请解释什么是量子计算?" } ], "stream": false }' # 响应示例 { "id": "550e8400-e29b-41d4-a716-446655440000", "object": "chat.completion", "created": 1699000000, "model": "claude-3-7-sonnet-20250219", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "量子计算是一种利用量子力学原理进行计算的技术...", "refusal": null, "annotation": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0 } } ``` -------------------------------- ### Image Recognition Analysis API Source: https://context7.com/yushangxiao/pplx2api/llms.txt Enables analysis of images by sending Base64 encoded image data. This feature allows for visual understanding and description of image content. It's part of the chat completions endpoint, with image data included in the `content` field. Requires an API key. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-4-6-sonnet", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "请描述这张图片中的内容" }, { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj..." } } ] } ], "stream": true }' # 响应将包含图像内容的详细描述 ``` -------------------------------- ### Pplx2Api Chat Completion API Request Source: https://github.com/yushangxiao/pplx2api/blob/main/README.md This snippet demonstrates how to make a chat completion request to the Pplx2Api using cURL. It shows how to include the API key for authentication and send messages to the model. ```bash curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "claude-3.7-sonnet", "messages": [ { "role": "user", "content": "你好,Claude!" } ], "stream": true }' ``` -------------------------------- ### Web Search Mode Source: https://context7.com/yushangxiao/pplx2api/llms.txt Enables web search functionality using models with a -search suffix to fetch the latest information and return search sources. ```APIDOC ## POST /v1/chat/completions (Web Search Mode) ### Description Enables web search functionality using models with a `-search` suffix to fetch the latest information and return search sources. ### Method POST ### Endpoint `/v1/chat/completions` ### Parameters #### Request Body - **model** (string) - Required - The model to use, e.g., `claude-4-6-sonnet-search`. - **messages** (array) - Required - An array of message objects. - **role** (string) - Required - The role of the message sender (`user`, `assistant`, `system`). - **content** (string) - Required - The content of the message. - **stream** (boolean) - Optional - Whether to stream the response. ### Request Example ```json { "model": "claude-4-6-sonnet-search", "messages": [ { "role": "user", "content": "今天的科技新闻有哪些?" } ], "stream": true } ``` ### Response #### Success Response (200) - The response will contain search results and source links. #### Response Example ``` 回答内容... --- [1] 新闻标题 - https://example.com/news1 摘要内容... [2] 另一篇新闻 - https://example.com/news2 摘要内容... ``` ```