Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Unofficial API Wrapper for Perplexity.ai + Account Generator with Web Interface

License

NotificationsYou must be signed in to change notification settings

helallao/perplexity-ai

Repository files navigation

TestsPythonLicense

Perplexity AI is a Python module that leveragesEmailnator to generate new accounts for unlimited pro queries. It supports both synchronous and asynchronous APIs, as well as a web interface for users who prefer a GUI-based approach.

Features

  • Account Generation: Automatically generate Gmail accounts using Emailnator
  • Unlimited Pro Queries: Bypass query limits by creating new accounts
  • Web Interface: Automate account creation and usage via a browser
  • Sync & Async APIs: Full support for both synchronous and asynchronous programming
  • Type Safety: Complete type hints for better IDE support
  • Robust Error Handling: Custom exceptions for better error management
  • Comprehensive Logging: Structured logging for debugging
  • File Upload: Support for document analysis and Q&A
  • Streaming Responses: Real-time response streaming
  • Retry Logic: Automatic retry with exponential backoff
  • Rate Limiting: Built-in rate limiting to prevent abuse

Installation

Basic Installation

pip install -e.

With Driver Support (Web Interface)

pip install -e".[driver]"patchright install chromium

Development Installation

pip install -e".[dev]"

This includes testing tools (pytest, pytest-cov, pytest-asyncio), linting (flake8, black, isort, mypy), and all optional dependencies.

Quick Start

Basic Usage

importperplexity# Create clientclient=perplexity.Client()# Make a queryresponse=client.search("What is artificial intelligence?")print(response['answer'])

With Account (for enhanced features)

importperplexity# Your Perplexity cookiescookies= {'next-auth.csrf-token':'your-token','next-auth.session-token':'your-session',}client=perplexity.Client(cookies)# Use enhanced modesresponse=client.search("Complex query here",mode='pro',model='gpt-5.2',sources=['scholar'])

Streaming Responses

forchunkinclient.search("Explain quantum computing",stream=True):if'answer'inchunk:print(chunk['answer'],end='',flush=True)

Async Usage

importasyncioimportperplexity_asyncasyncdefmain():client=awaitperplexity_async.Client()response=awaitclient.search("What is machine learning?")print(response['answer'])asyncio.run(main())

Documentation

Usage

Web Interface

The web interface automates account creation and usage in a browser.Patchright uses"Chrome User Data Directory" to be completely undetected, it'sC:\Users\YourName\AppData\Local\Google\Chrome\User Data for Windows, as shown below:

importosfromperplexity.driverimportDrivercli=Driver()cli.run(rf'C:\\Users\\{os.getlogin()}\\AppData\\Local\\Google\\Chrome\\User Data')

To use your own Chrome instance, enable remote debugging (it may enter dead loop in Cloudflare):

  1. Add--remote-debugging-port=9222 to Chrome's shortcut target.
  2. Pass the port to theDriver.run() method:
cli.run(rf'C:\\Users\\{os.getlogin()}\\AppData\\Local\\Google\\Chrome\\User Data',port=9222)

API Usage

Synchronous API

Below is an example code for simple usage, without using your own account or generating new accounts.

importperplexityperplexity_cli=perplexity.Client()# model = model for mode, which can only be used in own accounts, that is {#     'auto': [None],#     'pro': [None, 'sonar', 'gpt-5.2', 'claude-4.5-sonnet', 'grok-4-1'],#     'reasoning': [None, 'gpt-5.2-thinking', 'claude-4.5-sonnet-thinking', 'gemini-3.0-pro', 'kimi-k2-thinking', 'grok-4.1-reasoning'],#     'deep research': [None]# }# sources = ['web', 'scholar', 'social']# files = a dictionary which has keys as filenames and values as file data# stream = returns a generator when enabled and just final response when disabled# language = ISO 639 code of language you want to use# follow_up = last query info for follow-up queries, you can directly pass response from a query, look at second example below# incognito = Enables incognito mode, for people who are using their own accountresp=perplexity_cli.search('Your query here',mode='auto',model=None,sources=['web'],files={},stream=False,language='en-US',follow_up=None,incognito=False)print(resp)# second example to show how to use follow-up queries and stream responseforiinperplexity_cli.search('Your query here',stream=True,follow_up=resp):print(i)

And this is how you use your own account, you need to get your cookies in order to use your own account. Look atHow To Get Cookies,

importperplexityperplexity_cookies= {<yourcookieshere>}perplexity_cli=perplexity.Client(perplexity_cookies)resp=perplexity_cli.search('Your query here',mode='reasoning',model='gpt-5.2-thinking',sources=['web'],files={'myfile.txt':open('file.txt').read()},stream=False,language='en-US',follow_up=None,incognito=False)print(resp)

And finally account generating, you need to get cookies forEmailnator to use this feature. Look atHow To Get Cookies,

importperplexityemailnator_cookies= {<yourcookieshere>}perplexity_cli=perplexity.Client()perplexity_cli.create_account(emailnator_cookies)# Creates a new gmail, so your 5 pro queries will be renewed.resp=perplexity_cli.search('Your query here',mode='reasoning',model=None,sources=['web'],files={'myfile.txt':open('file.txt').read()},stream=False,language='en-US',follow_up=None,incognito=False)print(resp)

Asynchronous API

Below is an example code for simple usage, without using your own account or generating new accounts.

importasyncioimportperplexity_asyncasyncdeftest():perplexity_cli=awaitperplexity_async.Client()# mode = ['auto', 'pro', 'reasoning', 'deep research']# model = model for mode, which can only be used in own accounts, that is {#     'auto': [None],#     'pro': [None, 'sonar', 'gpt-5.2', 'claude-4.5-sonnet', 'grok-4-1'],#     'reasoning': [None, 'gpt-5.2-thinking', 'claude-4.5-sonnet-thinking', 'gemini-3.0-pro', 'kimi-k2-thinking', 'grok-4.1-reasoning'],#     'deep research': [None]# }# sources = ['web', 'scholar', 'social']# files = a dictionary which has keys as filenames and values as file data# stream = returns a generator when enabled and just final response when disabled# language = ISO 639 code of language you want to use# follow_up = last query info for follow-up queries, you can directly pass response from a query, look at second example below# incognito = Enables incognito mode, for people who are using their own accountresp=awaitperplexity_cli.search('Your query here',mode='auto',model=None,sources=['web'],files={},stream=False,language='en-US',follow_up=None,incognito=False)print(resp)# second example to show how to use follow-up queries and stream responseasyncforiinawaitperplexity_cli.search('Your query here',stream=True,follow_up=resp):print(i)asyncio.run(test())

And this is how you use your own account, you need to get your cookies in order to use your own account. Look atHow To Get Cookies,

importasyncioimportperplexity_asyncperplexity_cookies= {<yourcookieshere>}asyncdeftest():perplexity_cli=awaitperplexity_async.Client(perplexity_cookies)resp=awaitperplexity_cli.search('Your query here',mode='reasoning',model='gpt-5.2-thinking',sources=['web'],files={'myfile.txt':open('file.txt').read()},stream=False,language='en-US',follow_up=None,incognito=False)print(resp)asyncio.run(test())

And finally account generating, you need to get cookies foremailnator to use this feature. Look atHow To Get Cookies,

importasyncioimportperplexity_asyncemailnator_cookies= {<yourcookieshere>}asyncdeftest():perplexity_cli=awaitperplexity_async.Client()awaitperplexity_cli.create_account(emailnator_cookies)# Creates a new gmail, so your 5 pro queries will be renewed.resp=awaitperplexity_cli.search('Your query here',mode='reasoning',model=None,sources=['web'],files={'myfile.txt':open('file.txt').read()},stream=False,language='en-US',follow_up=None,incognito=False)print(resp)asyncio.run(test())

How to Get Cookies

Perplexity (to use your own account)

  • OpenPerplexity.ai website and login to your account.
  • Click F12 orCtrl + Shift + I to open inspector.
  • Go to the "Network" tab in the inspector.
  • Refresh the page, right click the first request, hover on "Copy" and click to "Copy as cURL (bash)".
  • Now go to theCurlConverter and paste your code here. The cookies dictionary will appear, copy and use it in your codes.

Emailnator (for account generating)

  • OpenEmailnator website and verify you're human.
  • Click F12 orCtrl + Shift + I to open inspector.
  • Go to the "Network" tab in the inspector.
  • Refresh the page, right click the first request, hover on "Copy" and click to "Copy as cURL (bash)".
  • Now go to theCurlConverter and paste your code here. The cookies dictionary will appear, copy and use it in your codes.
  • Cookies forEmailnator are temporary, you need to renew them continuously.

API Reference

Client Class

classClient:def__init__(self,cookies:Optional[Dict[str,str]]=None):"""        Initialize Perplexity client.        Args:            cookies: Optional Perplexity account cookies for enhanced features        """defsearch(self,query:str,mode:str='auto',model:Optional[str]=None,sources:List[str]= ['web'],files:Dict[str,Union[str,bytes]]= {},stream:bool=False,language:str='en-US',follow_up:Optional[Dict]=None,incognito:bool=False    )->Union[Dict,Generator]:"""        Search with Perplexity AI.        Args:            query: Search query            mode: Search mode ('auto', 'pro', 'reasoning', 'deep research')            model: Model to use (depends on mode)            sources: Information sources (['web', 'scholar', 'social'])            files: Files to upload {filename: content}            stream: Enable streaming responses            language: ISO 639 language code            follow_up: Previous query for context            incognito: Enable incognito mode        Returns:            Response dict with 'answer' key, or generator if stream=True        """defcreate_account(self,emailnator_cookies:Dict[str,str]):"""        Create new account using Emailnator.        Args:            emailnator_cookies: Emailnator cookies for account creation        """

Available Models

{'auto': [None],'pro': [None,'sonar','gpt-5.2','claude-4.5-sonnet','grok-4-1'],'reasoning': [None,'gpt-5.2-thinking','claude-4.5-sonnet-thinking','gemini-3.0-pro','kimi-k2-thinking','grok-4.1-reasoning'],'deep research': [None]}

Custom Exceptions

fromperplexity.exceptionsimport (PerplexityError,# Base exceptionAuthenticationError,# Authentication failedRateLimitError,# Rate limit exceededNetworkError,# Network issuesValidationError,# Invalid parametersResponseParseError,# Failed to parse responseAccountCreationError,# Account creation failedFileUploadError,# File upload failed)

Testing

Run All Tests

pytest tests/ -v

With Coverage

pytest tests/ --cov=perplexity --cov=perplexity_async --cov-report=html

Run Specific Tests

pytest tests/test_utils.py -vpytest tests/test_config.py -v

Development

Setup Development Environment

# Clone repositorygit clone https://github.com/yourusername/perplexity-ai.gitcd perplexity-ai# Install in development modepip install -e".[dev]"# Run testspytest# Format codeblack perplexity perplexity_async# Check typesmypy perplexity perplexity_async# Lintflake8 perplexity perplexity_async

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run tests and linting
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Troubleshooting

Common Issues

Issue: Response returnsNone

  • Solution: The API structure may have changed. CheckChangelog for updates.

Issue: Account creation fails

  • Solution: Emailnator cookies expire frequently. Get fresh cookies fromEmailnator.com.

Issue: File upload fails

  • Solution: Ensure you have a valid Perplexity account with file upload quota available.

Issue: Rate limiting

  • Solution: Use built-in rate limiting or wait between requests. Consider using async API for better concurrency.

Getting Help

Changelog

SeeCHANGELOG.md for detailed changes and bug fixes.

Roadmap

SeeIMPROVEMENTS.md for planned improvements and features.

License

This project is licensed under the MIT License. See theLICENSE file for details.

Acknowledgments

  • Perplexity.ai for the amazing AI search engine
  • Emailnator for temporary email service
  • All contributors who help improve this project

Disclaimer

This is an unofficial API wrapper. Use responsibly and respect Perplexity.ai's terms of service. This project is for educational purposes only.

About

Unofficial API Wrapper for Perplexity.ai + Account Generator with Web Interface

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors11

Languages


[8]ページ先頭

©2009-2025 Movatter.jp