{"id":25236841,"url":"https://github.com/gweidart/pyplexityai","last_synced_at":"2025-04-05T18:13:37.999Z","repository":{"id":276838778,"uuid":"930478256","full_name":"gweidart/pyplexityai","owner":"gweidart","description":"A clean, lightweight, and modern Python client for PerplexityAI's API. ","archived":false,"fork":false,"pushed_at":"2025-02-10T18:33:23.000Z","size":412,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-11T01:37:43.531Z","etag":null,"topics":["anthropic-claude","api","chatgpt","client","cursor","gemini-api","gpt-4o","gpt-5","llm","o1","o3","o3-mini","openai","perplexity-ai-api","perplexityai","pyplexityai","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gweidart.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-10T17:40:53.000Z","updated_at":"2025-02-22T14:52:02.000Z","dependencies_parsed_at":null,"dependency_job_id":"2350c0aa-53ae-4a81-87a2-89d8ac87aee6","html_url":"https://github.com/gweidart/pyplexityai","commit_stats":null,"previous_names":["gweidart/pyplexityai"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gweidart%2Fpyplexityai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gweidart%2Fpyplexityai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gweidart%2Fpyplexityai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gweidart%2Fpyplexityai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gweidart","download_url":"https://codeload.github.com/gweidart/pyplexityai/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247378139,"owners_count":20929297,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["anthropic-claude","api","chatgpt","client","cursor","gemini-api","gpt-4o","gpt-5","llm","o1","o3","o3-mini","openai","perplexity-ai-api","perplexityai","pyplexityai","python"],"created_at":"2025-02-11T15:32:09.255Z","updated_at":"2025-04-05T18:13:37.973Z","avatar_url":"https://github.com/gweidart.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"### PyPlexityAI\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./assets/images/PyPlexityAI.png\" alt=\"PyPlexityAI\" width=\"650\"\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://img.shields.io/badge/PerplexityAI-133B39?style=for-the-badge\u0026amp;logo=perplexity\u0026amp;logoColor=white\u0026amp;logoSize=auto\" alt=\"Static Badge\"\u003e      \u003cimg src=\"https://img.shields.io/badge/pip_install-pyplexityai-%23FFE873?style=for-the-badge\u0026amp;logo=pypi\u0026amp;logoColor=FFD43B\u0026amp;logoSize=auto\u0026amp;labelColor=4B8BBE\" alt=\"Static Badge\"\u003e      \u003cimg src=\"https://img.shields.io/badge/pypy-3.10-blue?style=for-the-badge\u0026amp;logo=pypy\u0026amp;logoColor=FFD43B\u0026amp;logoSize=auto\" alt=\"Static Badge\"\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\nA clean, lightweight, and modern Python client for \u003ca href=\"https://docs.perplexity.ai/home\"\u003ePerplexityAI's\u003c/a\u003e API.\n\u003c/p\u003e\n\n\u003e \u003ch4\u003e\u003cdetails\u003e\n\u003e \u003csummary\u003eTable of Contents (Click to expand)\u003c/summary\u003e\n\u003e\n\u003e- [PyPlexityAI](#pyplexityai)\n\u003e    - [Performance](#performance)\n\u003e    - [Compatibility](#compatibility)\n\u003e    - [Installation](#installation)\n\u003e    - [Basic Usage](#basic-usage)\n\u003e    - [Features](#features)\n\u003e    - [Search Parameters](#search-parameters)\n\u003e    - [Model Matrix](#model-matrix)\n\u003e       - [Current Generation (Recommended)](#current-generation-recommended)\n\u003e       - [Model Selection Guide](#model-selection-guide)\n\u003e    - [Error Handling](#error-handling)\n\u003e    - [Streaming Support](#streaming-support)\n\u003e       - [Basic Streaming](#basic-streaming)\n\u003e       - [OpenAI-Compatible Streaming](#openai-compatible-streaming)\n\u003e       - [Async Streaming](#async-streaming)\n\u003e       - [Stream Processing](#stream-processing)\n\u003e       - [OpenAI Compatibility](#openai-compatibility)\n\u003e       - [Batch Processing](#batch-processing)\n\u003e       - [Model Selection](#model-selection)\n\u003e       - [Search Modes and Focus Areas](#search-modes-and-focus-areas)\n\u003e  - [Development](#development)\n\u003e  - [License](#license)\n\u003e \u003c/details\u003e\u003c/h4\u003e\n\n- Sync/Async API interfaces\n- OpenAI-compatible streaming\n- Model selection guide with performance benchmarks\n- Robust error handling with detailed diagnostics\n\n### Performance\n- PyPy-optimized core components\n- Connection pooling \u0026 automatic retries\n- Efficient streaming support\n- Zero-copy parsing for high throughput\n\n### Compatibility\n- Full OpenAI API schema support\n- Automatic type conversion\n- Context manager interfaces\n- Cross-platform compatibility\n\n## Installation\n\n```bash\npip install pyplexityai  # Basic installation\npip install pyplexityai[async]  # With additional async support\n```\n\n## Basic Usage\n\n```python\nfrom pyplexityai import PerplexityClient\nfrom pyplexityai.errors import AuthenticationError\n\n# Initialize with your API key\nclient = PerplexityClient(\"your-api-key\")\n\ntry:\n    # Simple synchronous search\n    result = client.search_sync(\"What is quantum computing?\")\n    print(result[\"text\"])\nfinally:\n    client.close()\n\n# Or use as a context manager (recommended)\nwith PerplexityClient(\"your-api-key\") as client:\n    result = client.search_sync(\"What is quantum computing?\")\n    print(result[\"text\"])\n```\n\n## Features\n\n- Simple API key authentication\n- Synchronous and streaming search modes\n- Multiple model options\n- Clean, typed codebase\n- Robust error handling with detailed diagnostics\n- OpenAI-compatible interface\n- Async support\n- No unnecessary dependencies\n- **Built with PyPy and JIT-GIL enhancements for optimal performance**\n- Optimized for high-throughput applications\n\n\u003e [!IMPORTANT]\n\u003e This library is not affiliated with Perplexity AI. It is a community-driven project.\n\n## Search Parameters\n\n| Parameter       | Type    | Default                  | Description                          |\n|-----------------|---------|--------------------------|--------------------------------------|\n| `mode`          | str     | \"concise\"                | \"copilot\" for detailed responses     |\n| `search_focus`  | str     | \"internet\"               | Specialized sources (see below)      |\n| `timeout`       | float   | 30.0                     | Seconds before timeout               |\n| `model`         | str     | \"sonar-pro\"              | Model to use (see Model Matrix)      |\n\n**Search Focus Options**: `internet`, `scholar`, `writing`, `wolfram`, `youtube`, `reddit`\n\n## Model Matrix\n\n| Model               | Context | Speed | Output Limit | Best For               | Type              |\n|---------------------|---------|-------|--------------|------------------------|-------------------|\n| sonar-reasoning-pro | 127k    | ⚡⚡⚡   | 8k           | Complex reasoning      | Chat Completion   |\n| sonar-pro           | 200k    | ⚡⚡    | 8k           | General purpose        | Chat Completion   |\n| sonar-reasoning     | 127k    | ⚡⚡⚡   | 4k           | Quick CoT responses    | Chat Completion   |\n| sonar               | 127k    | ⚡⚡    | 4k           | Everyday conversations | Chat Completion   |\n\n#### Current Generation (Recommended)\n- `sonar-reasoning-pro`: Best for complex chain-of-thought reasoning (8k output limit)\n- `sonar-pro`: General purpose model with 200k context window\n- `sonar-reasoning`: Fast chain-of-thought responses\n- `sonar`: Balanced everyday use model\n\n#### Legacy Models (Deprecating February 22, 2025)\n- `llama-3.1-sonar-small-128k-online`\n- `llama-3.1-sonar-large-128k-online`\n- `llama-3.1-sonar-huge-128k-online`\n\n### Model Selection Guide\n- Default model: `sonar-pro` (recommended for most use cases)\n- Complex reasoning: `sonar-reasoning-pro`\n- Quick responses: `sonar-reasoning`\n- General chat: `sonar`\n- Maximum context: `sonar-pro` (200k tokens)\n\n## Error Handling\n\nThe client uses robust error handling with detailed diagnostics:\n\n- `AuthenticationError`: API key validation issues\n- `InvalidParameterError`: Invalid parameter values\n- `SearchError`: Search request failures\n- `PerplexityTimeoutError`: Request timeouts\n- `WebSocketError`: WebSocket connection issues\n\n```python\nfrom pyplexityai import PerplexityClient\nfrom pyplexityai.errors import (\n    AuthenticationError,\n    SearchError,\n    InvalidParameterError,\n    PerplexityTimeoutError,\n)\n```\n\n*Each error includes:*\n- Descriptive message\n- Detailed causes\n- Helpful hints\n- Additional notes\n- Error codes for programmatic handling\n\n```python\ntry:\n    with PerplexityClient(\"your-api-key\") as client:\n        result = client.search_sync(\"What is quantum computing?\")\nexcept AuthenticationError as e:\n    print(f\"Authentication failed: {e.message}\")\n    print(f\"Hint: {e.hint_stmt}\")\nexcept InvalidParameterError as e:\n    print(f\"Invalid parameter: {e.message}\")\n    print(f\"Valid values: {e.causes[-1]}\")\nexcept SearchError as e:\n    print(f\"Search failed: {e.message}\")\n    print(f\"Causes: {e.causes}\")\nexcept PerplexityTimeoutError as e:\n    print(f\"Request timed out: {e.message}\")\n```\n\n## Streaming Support\n\n### Basic Streaming\n\n```python\nfrom pyplexityai import PerplexityClient\n\nwith PerplexityClient(\"your-api-key\") as client:\n    # Stream responses chunk by chunk\n    for chunk in client.search(\"What is quantum computing?\"):\n        if \"text\" in chunk:\n            print(chunk[\"text\"], end=\"\", flush=True)\n```\n\n### OpenAI-Compatible Streaming\n\n```python\nfrom pyplexityai import OpenAICompatibleClient, ChatMessage\n\nclient = OpenAICompatibleClient(\"your-api-key\")\n\nmessages = [\n    ChatMessage(role=\"user\", content=\"Explain quantum computing\", name=None)\n]\n\n# Stream tokens as they arrive\nfor response in client.create_chat_completion(\n    messages=messages,\n    model=\"sonar-pro\",\n    stream=True,\n):\n    if \"delta\" in response[\"choices\"][0]:\n        if content := response[\"choices\"][0][\"delta\"].get(\"content\"):\n            print(content, end=\"\", flush=True)\n```\n\n### Async Streaming\n\n```python\nfrom pyplexityai import AsyncPerplexityClient\n\nasync with AsyncPerplexityClient(\"your-api-key\") as client:\n    # Stream responses asynchronously\n    async for chunk in client.async_search(\"What is quantum computing?\"):\n        if \"text\" in chunk:\n            print(chunk[\"text\"], end=\"\", flush=True)\n```\n\n### OpenAI-Compatible Streaming\n\n```python\nfrom pyplexityai import OpenAICompatibleClient\nfrom pyplexityai.client_types import ChatMessage\n\nasync with OpenAICompatibleClient(\"your-api-key\") as client:\n    messages = [\n        ChatMessage(role=\"user\", content=\"Explain quantum computing\", name=None)\n    ]\n\n    # Stream tokens as they arrive\n    async for response in client.acreate_chat_completion(\n        messages=messages,\n        model=\"sonar-pro\",\n        stream=True,\n    ):\n        if content := response.choices[0].delta.content:\n            print(content, end=\"\", flush=True)\n```\n\n### Batch Processing\n\n```python\nfrom pyplexityai import AsyncPerplexityClient\nfrom pyplexityai.errors import PerplexityTimeoutError\n\nasync def batch_search(queries: list[str], api_key: str) -\u003e dict[str, str]:\n    results = {}\n    async with AsyncPerplexityClient(api_key) as client:\n        for query in queries:\n            try:\n                result = await client.async_search_sync(\n                    query,\n                    timeout=45.0  # Longer timeout for batch\n                )\n                results[query] = result[\"text\"]\n            except PerplexityTimeoutError:\n                results[query] = \"Error: timeout\"\n                continue\n    return results\n\n# Example batch processing\nqueries = [\n    \"What is Python?\",\n    \"What is JavaScript?\",\n    \"What is Rust?\"\n]\nresults = await batch_search(queries, \"your-api-key\")\nfor query, result in results.items():\n    print(f\"\\nQuery: {query}\")\n    print(f\"Result: {result}\")\n```\n\n### Model Selection\n\n```python\nfrom pyplexityai import PerplexityClient\n\nwith PerplexityClient(\"your-api-key\") as client:\n    # Use reasoning-optimized model\n    result = client.search_sync(\n        \"Explain the implications of quantum entanglement\",\n        model=\"sonar-reasoning-pro\"\n    )\n    print(result[\"text\"])\n\n    # Use general purpose model with streaming\n    for chunk in client.search(\n        \"Write a Python function to implement quicksort\",\n        model=\"sonar-pro\"\n    ):\n        if \"text\" in chunk:\n            print(chunk[\"text\"], end=\"\", flush=True)\n```\n\n### Search Modes and Focus Areas\n\n```python\nfrom pyplexityai import AsyncPerplexityClient\n\nasync with AsyncPerplexityClient(\"your-api-key\") as client:\n    # Copilot mode (more detailed responses)\n    async for chunk in client.async_search(\n        query=\"Explain how BERT works\",\n        mode=\"copilot\",\n        model=\"sonar-pro\"\n    ):\n        if \"text\" in chunk:\n            print(chunk[\"text\"], end=\"\", flush=True)\n\n    # Scholar focus (academic sources)\n    result = await client.async_search_sync(\n        query=\"Latest developments in fusion energy\",\n        mode=\"concise\",\n        search_focus=\"scholar\"\n    )\n    print(result[\"text\"])\n```\n\n## Development\n\n```bash\n# Create virtual environment\nuv venv --python pypy\n\n# Activate virtual environment\nsource .venv/bin/activate\n\n# Install development dependencies\nuv pip install -e \".[dev]\"\n\n# Run tests\nuv run test.py  # Run all tests\nuv run test.py errors  # Run specific test(s)\n\n# Run type checks\npyright  # Strict type checking\n\n# Run linter\nruff check . --fix --unsafe-fixes\n\n# Run formatter\nruff format .\n```\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgweidart%2Fpyplexityai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgweidart%2Fpyplexityai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgweidart%2Fpyplexityai/lists"}