helallao / perplexity-ai Goto Github PK
View Code? Open in Web Editor NEWUnofficial API Wrapper for Perplexity.ai + Account Generator
Home Page: https://perplexity.ai
License: MIT License
Unofficial API Wrapper for Perplexity.ai + Account Generator
Home Page: https://perplexity.ai
License: MIT License
I'm running the task on perplexity webpage with the file :
Next, I'm running the code with streamlit and asking the same question and followup on the same file:
backend_uuid = None
first_query = st.session_state.last_perplexity_response is None
if not first_query:
backend_uuid = st.session_state.last_perplexity_response['backend_uuid']
if first_query:
my_file = (open('apple_cake.txt', 'rb').read(), 'txt')
perplexity_response = st.session_state.perplexity_cli.search(prompt, mode='concise', file = my_file)
else:
perplexity_response = st.session_state.perplexity_cli.search(prompt, mode='concise', follow_up = backend_uuid)
bot_response = perplexity_response['text']['answer']
st.session_state.last_perplexity_response = perplexity_response
I edited the source code of perplexity class to be compatible with python 3.7, never tried it in >=3.8 and got this error. I have already tried to get new headers and cookies through following the steps provided but still got the same error.
WebSocketConnectionClosedException Traceback (most recent call last)
/var/folders/sm/rngfstvd2t3b49qbz92lcgmw0000gn/T/ipykernel_2130/3636085025.py in
5 # focus = ['internet', 'scholar', 'writing', 'wolfram', 'youtube', 'reddit', 'wikipedia']
6 # file = (data, filetype) perplexity supports two file types, txt and pdf
----> 7 print(perplexity_cli.search('india’s facets.cloud raises $4m for self-serve devops', mode='concise', focus='internet'))
8
9 # perplexity_cli.create_account(emailnator_headers, emailnator_cookies) # Call this function when you're out of copilots
/var/folders/sm/rngfstvd2t3b49qbz92lcgmw0000gn/T/ipykernel_2130/839763154.py in search(self, query, mode, focus, file)
223 'frontend_uuid': self.frontend_uuid,
224 'gpt4': False,
--> 225 'language': 'en-US',
226 }
227 ]))
~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/websocket/_app.py in send(self, data, opcode)
180 if not self.sock or self.sock.send(data, opcode) == 0:
181 raise WebSocketConnectionClosedException(
--> 182 "Connection is already closed.")
183
184 def close(self, **kwargs):
WebSocketConnectionClosedException: Connection is already closed.
I wanted to send a bot with this api to the server, but it gives an error:
HTTPSConnectionPool(host='www.perplexity.ai', port=443): Max retries exceeded with url: /search/dc2e0bc5-4518-49a4-9a9c-2af9a1e10523 (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))
can you tell me how to fix it please?
hello!
do you have any suggestions on how to parse perplexity's answers into readable view?
I already tried many ways, but it's not a json answer, also it has problems with converting into a dictionary
so, how do you parse it's answers?
Python 3.11
Package | Version |
---|---|
aiohttp | 3.8.6 |
aiosignal | 1.3.1 |
async-timeout | 4.0.3 |
attrs | 23.1.0 |
beautifulsoup4 | 4.12.2 |
bs4 | 0.0.1 |
certifi | 2023.7.22 |
charset-normalizer | 3.3.1 |
frozenlist | 1.4.0 |
idna | 3.4 |
lxml | 4.9.3 |
lxml-stubs | 0.4.0 |
multidict | 6.0.4 |
pip | 23.3.1 |
requests | 2.31.0 |
requests-toolbelt | 1.0.0 |
setuptools | 68.2.2 |
soupsieve | 2.5 |
urllib3 | 2.0.7 |
websocket-client | 1.6.4 |
wheel | 0.41.2 |
yarl | 1.9.2 |
I've encountered an issue while using both the async and normal methods. Despite my efforts, I'm not receiving any return. I've ensured that the cookie is correctly obtained and placed, and I've followed the methods outlined in the READ.me and in Issue #4.
Upon further investigation, I've found that the email is successfully created and a registration confirmation is received. However, the code seems to hang at while not self._last_file_upload_info: pass
, failing to get the upload URL for the file. If no file is attached, the code gets stuck at while True: while not self._last_answer: pass
.
I'm seeking insight into why this might be happening. Can you replicate this issue on your end? I appreciate your assistance.
This method with copy cookie still work?
Cuz i got fail from today
I'm trying to use my own account, however I am not able to get past the first websocket request. I am very sure I have copied the cookies/headers correctly with this #4
I'm starting to suspect it could be the t parameter in the url.
In perplexity.py line 87 - self.t = format(random.getrandbits(32), '08x')
, we're creating the t token as a random string of characters and we are using the same values for every websocket request we make.
This is not consistent the dynamic t tokens being generated as we observe the network packages back and forth on Chrome
Hii there I'm getting the following error
Error: Handshake status 400 Bad Request
Traceback (most recent call last):
File "e:*\perplexity-ai-main\test.py", line 73, in
print(perplexity_cli.search('Tell me somthing about life', mode='copilot', focus='internet', file=(open('myfile.txt', 'rb').read(), 'txt')))
File "e:*\perplexity-ai-main\perplexity.py", line 143, in search
self.ws.send(f'{420 + self.n}' + json.dumps([
File "C:*************\AppData\Local\Programs\Python\Python39\lib\site-packages\websocket_app.py", line 183, in send
raise WebSocketConnectionClosedException(
websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.
Even with the latest headers the code raises the following stack trace:
File "~/PerplexityAI/_perplexity.py", line 72, in init
self.sid = json.loads(self.session.get(f'https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:])['sid']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/[email protected]/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/[email protected]/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/[email protected]/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Is it possible to run a follow-up query after response from search method?
First of all, thanks for this. This works quite well, but I often get the error that the tokens are expired. Is there a way to also automate that? The user still has to manually bypass Cloudflare with clicks, but it would make updating the tokens a lot easier.
Please guide.
Not use temp mail
Error: Handshake status 403 Forbidden -+-+- {'date': 'Fri, 08 Sep 2023 13:15:23 GMT', 'content-type': 'text/html;
charset=UTF-8', 'transfer-encoding': 'chunked', 'connection': 'close', 'cross-origin-embedder-policy': 'require-corp',
'cross-origin-opener-policy': 'same-origin', 'cross-origin-resource-policy': 'same-origin', 'origin-agent-cluster': '?1',
'permissions-policy': 'accelerometer=(),autoplay=(),camera=(),clipboard-read=(),clipboard-write=(),geolocation=
(),gyroscope=(),hid=(),interest-cohort=(),magnetometer=(),microphone=(),payment=(),publickey-credentials-get=
(),screen-wake-lock=(),serial=(),sync-xhr=(),usb=()', 'referrer-policy': 'same-origin', 'x-frame-options': 'SAMEORIGIN',
'cf-mitigated': 'challenge', 'cache-control': 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-
check=0', 'expires': 'Thu, 01 Jan 1970 00:00:01 GMT', 'server': 'cloudflare', 'cf-ray': '803775c15c4af429-BOM'} -+-+- None
I tried to use my own account to access (refer to #4), and I got this issue.
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
Cell In[2], line 1
----> 1 perplexity_cli = perplexity.Client(perplexity_headers, perplexity_cookies)
File ~/workspace/perplexity-ai-v2/perplexity.py:78, in Client.__init__(self, headers, cookies)
76 self.t = format(random.getrandbits(32), '08x')
77 print(self.session.get(f'[https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1](https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}%27).text[1):])
---> 78 self.sid = json.loads(self.session.get(f'[https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:])['sid](https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}%27).text[1:])[%27sid)']
79 self.frontend_uuid = str(uuid4())
80 self.frontend_session_id = str(uuid4())
File ~/anaconda3/lib/python3.10/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
341 s = s.decode(detect_encoding(s), 'surrogatepass')
343 if (cls is None and object_hook is None and
344 parse_int is None and parse_float is None and
345 parse_constant is None and object_pairs_hook is None and not kw):
--> 346 return _default_decoder.decode(s)
347 if cls is None:
348 cls = JSONDecoder
File ~/anaconda3/lib/python3.10/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
332 def decode(self, s, _w=WHITESPACE.match):
333 """Return the Python representation of ``s`` (a ``str`` instance
334 containing a JSON document).
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):
File ~/anaconda3/lib/python3.10/json/decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I checked the content of self.session.get(f'[https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:]
:
!DOCTYPE html><html lang="en-US"><head><title>Just a moment...</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta name="robots" content="noindex,nofollow"><meta name="viewport" content="width=device-width,initial-scale=1"><link href="/cdn-cgi/styles/challenges.css" rel="stylesheet"></head><body class="no-js"><div class="main-wrapper" role="main"><div class="main-content"><noscript><div id="challenge-error-title"><div class="h2"><span class="icon-wrapper"><div class="heading-icon warning-icon"></div></span><span id="challenge-error-text">Enable JavaScript and cookies to continue</span></div></div></noscript></div></div><script>(function(){window._cf_chl_opt={cvId: '2',cZone: "[www.perplexity.ai](https://www.perplexity.ai/)",cType: 'managed',cNounce: '24664',cRay: '806b2f80ac3c2889',cHash: '267f20784df18fd',cUPMDTk: "\/socket.io\/?EIO=4&transport=polling&t=d8480b84&__cf_chl_tk=FI0YS7VSAqP6oipLvZ1On93V3.LFqlPN2c2U1BFjGlU-1694721305-0-gaNycGzNEdA",cFPWv: 'g',cTTimeMs: '1000',cMTimeMs: '0',cTplV: 5,cTplB: 'cf',cK: "visitor-time",fa: "\/socket.io\/?EIO=4&transport=polling&t=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r0sdDWWksiul5Gdk9zeTpHYx89H90Riwo5OSIjODu5o2AnkTng9WdR0O2A8eVU76Lz2ZRbsx8IJWzI6jiy4+Dd',t: 'MTY5NDcyMTMwNS43MTgwMDA=',cT: Math.floor(Date.now() / 1000),m: 'FmdXWG+swhpuYNTAOifF+9naCD9KkyjhhSeay4IuBeo=',i1: 'jJX8TaNIoKjG3dkh5woZ/w==',i2: 'h69uOJUSvrdYjOS3VgQtHQ==',zh: 'NU8ixJjbvuzjjI0VYVlScfuo4FsYASw7wpJI5etvkPw=',uh: 'tZzwk0UXBB6aZMwUSrybzD1mMJwGI/1CIIfoh4RzeeI=',hh: 'Y4wbTy2+H//SzqXCr/ut8Fn8eNgcrMRWkXlJV1vMwRU=',}};var cpo = document.createElement('script');cpo.src = '/cdn-cgi/challenge-platform/h/g/orchestrate/chl_page/v1?ray=806b2f80ac3c2889';window._cf_chl_opt.cOgUHash = location.hash === '' && location.href.indexOf('#') !== -1 ? '#' : location.hash;window._cf_chl_opt.cOgUQuery = location.search === '' && location.href.slice(0, location.href.length - window._cf_chl_opt.cOgUHash.length).indexOf('?') !== -1 ? '?' : location.search;if (window.history && window.history.replaceState) {var ogU = location.pathname + window._cf_chl_opt.cOgUQuery + window._cf_chl_opt.cOgUHash;history.replaceState(null, null, "\/socket.io\/?EIO=4&transport=polling&t=d8480b84&__cf_chl_rt_tk=FI0YS7VSAqP6oipLvZ1On93V3.LFqlPN2c2U1BFjGlU-1694721305-0-gaNycGzNEdA" + window._cf_chl_opt.cOgUHash);cpo.onload = function() {history.replaceState(null, null, ogU);}}document.getElementsByTagName('head')[0].appendChild(cpo);}());</script><script defer src="https://static.cloudflareinsights.com/beacon.min.js/v8b253dfea2ab4077af8c6f58422dfbfd1689876627854" integrity="sha512-bjgnUKX4azu3dLTVtie9u6TKqgx29RBwfj3QXYt5EKfWM/9hPSAI/4qcV5NACjwAo8UtTeWefx6Zq5PHcMm7Tg==" data-cf-beacon='{"rayId":"806b2f80ac3c2889","version":"2023.8.0","b":1,"token":"92730c73a9e747fbb6a25e1d6657122d","si":100}' crossorigin="anonymous"></script>
It seems I cannot bypass cloudflare. This is the first time I use this script so I do not think it is because I sent too many requests. Could you please check if this also happens at your side? Would this be because they updated their firewall policy? Thanks.
Hi, I already followed the steps provided but getting this error JSONDecodeError: Expecting value: line 1 column 1 (char 0) from running this code perplexity_cli = Client(perplexity_headers, perplexity_cookies)
JSONDecodeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 perplexity_cli = Client(perplexity_headers, perplexity_cookies)
2 #perplexity_cli.create_account(emailnator_headers, emailnator_cookies) # Creates a new gmail, so your 5 copilots will be renewed. You can pass this one if you are not going to use "copilot" mode
3
4 # modes = ['concise', 'copilot']
5 # focus = ['internet', 'scholar', 'writing', 'wolfram', 'youtube', 'reddit', 'wikipedia']
3 frames
in init(self, headers, cookies)
68
69 self.t = format(random.getrandbits(32), '08x')
---> 70 self.sid = json.loads(self.session.get(f'https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:])['sid']
71 self.frontend_uuid = str(uuid4())
72 self.frontend_session_id = str(uuid4())
/usr/lib/python3.10/json/init.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
344 parse_int is None and parse_float is None and
345 parse_constant is None and object_pairs_hook is None and not kw):
--> 346 return _default_decoder.decode(s)
347 if cls is None:
348 cls = JSONDecoder
/usr/lib/python3.10/json/decoder.py in decode(self, s, _w)
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):
/usr/lib/python3.10/json/decoder.py in raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
Good Day!
Thank you for the script it does work wonderfully, Yesterday I had the script working well on copilot mode and also it was creating new accounts using emailnator, but somehow today it stopped working keeps getting the error Perplexity account creating error: <Response [400]> , 1st I thought cloudfare is blocking me but I am able to query prompts on concise mode and also can access the website via Google Chrome, I have double checked all my headers and cookies for both Emailnator and Perplexity there seem to be in order, Is there something I am missing.
Your help is greatly appreciated?
Hi, thanks for this amazing code,
Unfortunately, I couldn't run the code
The first version gives this error, the first error was not finding "myfile.txt" I had to create empty myfile.txt file to get this new error:
For the Asynchronous Version, I get this error:
I'm not a professional in coding, a simple explanation would be much appreciated.
Thanks
I run it with below code:
import json
import time
import requests
import random
from bs4 import BeautifulSoup
from websocket import WebSocketApp
from uuid import uuid4
from threading import Thread
cookies = {
'cf_clearance': 'LH02k9dzyA4wEdXW0m5WANalfq.sx6VDjhgkiGXkHag-1690102887-0-160.0.0',
'_ga': 'GA1.1.415630709.1690102894',
'g_state': '{"i_l":0}',
.............
}
headers = {
'authority': 'www.perplexity.ai',
'accept': '*/*',
'accept-language': 'en-US,en;q=0.9,vi;q=0.8',
'content-type': 'application/json',
..........
}
def souper(x):
return BeautifulSoup(x, 'lxml')
class Emailnator:
def __init__(self, headers, cookies, domain=False, plus=True, dot=True, google_mail=False):
self.inbox = []
self.inbox_ads = []
self.s = requests.Session()
self.s.headers.update(headers)
self.s.cookies.update(cookies)
data = {'email': []}
if domain:
data['email'].append('domain')
if plus:
data['email'].append('plusGmail')
if dot:
data['email'].append('dotGmail')
if google_mail:
data['email'].append('googleMail')
response = self.s.post('https://www.emailnator.com/generate-email', json=data).json()
self.email = response['email'][0]
for ads in self.s.post('https://www.emailnator.com/message-list', json={'email': self.email}).json()['messageData']:
self.inbox_ads.append(ads['messageID'])
def reload(self, wait=False, retry_timeout=5):
self.new_msgs = []
while True:
for msg in self.s.post('https://www.emailnator.com/message-list', json={'email': self.email}).json()['messageData']:
if msg['messageID'] not in self.inbox_ads and msg not in self.inbox:
self.new_msgs.append(msg)
if wait and not self.new_msgs:
time.sleep(retry_timeout)
else:
break
self.inbox += self.new_msgs
return self.new_msgs
def open(self, msg_id):
return self.s.post('https://www.emailnator.com/message-list', json={'email': self.email, 'messageID': msg_id}).text
class Client:
def __init__(self, headers, cookies):
self.session = requests.Session()
self.session.headers.update(headers)
self.session.cookies.update(cookies)
self.session.get(f'https://www.perplexity.ai/search/{str(uuid4())}')
self.t = format(random.getrandbits(32), '08x')
self.sid = json.loads(self.session.get(f'https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:])['sid']
self.frontend_uuid = str(uuid4())
self.frontend_session_id = str(uuid4())
self._last_answer = None
self.copilot = 0
self.n = 1
assert self.session.post(f'https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}&sid={self.sid}', data='40{"jwt":"anonymous-ask-user"}').text == 'OK'
self.ws = WebSocketApp(
url=f'wss://www.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}',
cookie='; '.join([f'{x}={y}' for x, y in self.session.cookies.get_dict().items()]),
on_open=lambda ws: ws.send('2probe'),
on_message=self.on_message,
on_error=lambda ws, err: print(f'Error: {err}'),
)
Thread(target=self.ws.run_forever).start()
time.sleep(1)
def create_account(self, headers, cookies):
emailnator_cli = Emailnator(headers, cookies, dot=False, google_mail=True)
resp = self.session.post('https://www.perplexity.ai/api/auth/signin/email', data={
'email': emailnator_cli.email,
'csrfToken': self.session.cookies.get_dict()['next-auth.csrf-token'].split('%')[0],
'callbackUrl': 'https://www.perplexity.ai/',
'json': 'true',
})
if resp.ok:
new_msgs = emailnator_cli.reload(wait=True)
new_account_link = souper(emailnator_cli.open(new_msgs[0]['messageID'])).select('a')[1].get('href')
self.session.get(new_account_link)
self.session.get('https://www.perplexity.ai/')
self.copilot = 5
return True
def on_message(self, ws, message):
if message == '2':
ws.send('3')
elif message == '3probe':
ws.send('5')
if message.startswith(str(430 + self.n)):
response = json.loads(message[3:])[0]
response['text'] = json.loads(response['text'])
self._last_answer = response
def search(self, query, mode='concise', focus='internet'):
assert mode in ['concise', 'copilot'], 'Search modes --> ["concise", "copilot"]'
assert focus in ['internet', 'scholar', 'writing', 'wolfram', 'youtube', 'reddit', 'wikipedia'], 'Search focus modes --> ["internet", "scholar", "writing", "wolfram", "youtube", "reddit", "wikipedia"]'
assert self.copilot > 0 if mode == 'copilot' else True, 'You have used all of your copilots'
self.copilot = self.copilot - 1 if mode == 'copilot' else self.copilot
self.n += 1
self._last_answer = None
self.ws.send(f'{420 + self.n}' + json.dumps([
'perplexity_ask',
query,
{
'source': 'default',
'mode': mode,
'last_backend_uuid': None,
'read_write_token': '',
'conversational_enabled': True,
'frontend_session_id': self.frontend_session_id,
'search_focus': focus,
'frontend_uuid': self.frontend_uuid,
'gpt4': False,
'language': 'en-US',
}
]))
while not self._last_answer:
pass
return self._last_answer
print('__init__')
perplexity_cli = Client(headers, cookies)
print('__search__')
print(perplexity_cli.search('What is iso 9001?'))
Output:
init
search
Cookies are not working since today.
I tried the updated code but still get 403.
Exception: File upload cannot be used in concise mode
Do you plan to enable file uploads in concise mode?
Hi, I'm getting this error while running my script ModuleNotFoundError: No module named 'perplexity' Can anyone help me with this? I used the code example in the readme file and followed every step of it, i ran this command "pip3 install requests&&pip3 install beautifulsoup4&&pip3 install lxml&&pip3 install websocket-client&&pip3 install requests-toolbelt"
and pip3 install perplexity is just not working
Hi there!
I'm using your module with my own credentials (I got PRO account) and since today I'm getting AssertionError upon client initialization at this point .
Looks like this happens because of CloudFlare. Any ideas?
Hi Mate,
How can I use only Claude2/GPT4 in all my queries?
Is there a way to turn the Copilot function on or off?
code:
import perplexity
labs_cli = perplexity.LabsClient()
# model = ['pplx-7b-online', 'pplx-70b-online', 'pplx-7b-chat', 'pplx-70b-chat', 'mistral-7b-instruct', 'codellama-34b-instruct', 'llama-2-70b-chat', 'llava-7b-chat', 'mixtral-8x7b-instruct', 'mistral-medium']
print(labs_cli.ask('hi', model='mixtral-8x7b-instruct'))
error:
Traceback (most recent call last):
File "c:/Users/drime/Documents/drimef0_projects/koboldai_characters/samplers/sampler_perplexity.py", line 3, in <module>
labs_cli = perplexity.LabsClient()
File "c:\Users\drime\Documents\drimef0_projects\characters_bot\samplers\perplexity.py", line 409,
in __init__
self.sid = json.loads(self.session.get(f'https://labs-api.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:])['sid']
File "C:\Users\drime\.pyenv\pyenv-win\versions\3.8.9\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\drime\.pyenv\pyenv-win\versions\3.8.9\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\drime\.pyenv\pyenv-win\versions\3.8.9\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
self.session.get(f'https://labs-api.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}').text[1:]
returns this:
!DOCTYPE html><html lang="en-US"><head><title>Just a moment...</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta name="robots" content="noindex,nofollow"><meta name="viewport" content="width=device-width,initial-scale=1"><link href="/cdn-cgi/styles/challenges.css"
rel="stylesheet"><meta http-equiv="refresh" content="375"></head><body class="no-js"><div class="main-wrapper" role="main"><div class="main-content"><noscript><div id="challenge-error-title"><div class="h2"><span class="icon-wrapper"><div class="heading-icon warning-icon"></div></span><span id="challenge-error-text">Enable JavaScript and cookies
to continue</span></div></div></noscript></div></div><script>....................................................................
The request seems to be blocked
I followed the tutorial but encountered Error: Handshake status 400 Bad Request
. What could be the reason?
Hi, thanks for the great work.
I was just trying the example, but I´m having the problem, that the program is not terminating, only by pressing ctrl-c. Are there any resources still opened?
Code:
resp = perplexity_cli.search('Your query here', mode='copilot', focus='internet', solvers={
'text': my_text_prompt_solver,
'checkbox': my_checkbox_prompt_solver
})
print(resp["text"]["answer"])
(not more)
I'm sorry, but your question is unclear. Please provide a specific query or topic for me to search. Based on the search results, I found information on how to write a query letter to literary agents[4], how to perform a query in a database[3], and the meaning of the word "query"[5]. If you have a specific question related to any of these topics, I would be happy to help you.
(NOT TERMINATING)
^CException ignored in: <module 'threading' from '/usr/lib/python3.10/threading.py'>
Traceback (most recent call last):
File "/usr/lib/python3.10/threading.py", line 1567, in _shutdown
lock.acquire()
Hi There,
Thanks for the wonderful contribution for this wrapper. I am not python person and don't know the process handeling much, Currently the program works perfectly when I run my code as $python3 mycode.py , it prints the output but doesn't exit. I am looking to run this as shell script and pipe the response to a file or to another script (non python). How do I achieve that?
I want the program to run and exit with unix process success code so the next thing in the pipe can take over.
What are my options?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.