XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

refactored you code added error handling and updated regex for parsing response

f43107aa
Raju Komati <komatiraju032@gmail.com>
提交于

代码差异

3 个文件 +98 -82
Modified testing/you_test.py +7 -12
@@ -1,10 +1,7 @@
1 1 import you
2 2
3 3 # simple request with links and details
4 response = you.Completion.create(
5 prompt = "hello world",
6 detailed = True,
7 includelinks = True)
4 response = you.Completion.create(prompt="hello world", detailed=True, include_links=True)
8 5
9 6 print(response)
10 7
@@ -16,17 +13,15 @@ print(response)
16 13 # }
17 14 # }
18 15
19 #chatbot
16 # chatbot
20 17
21 18 chat = []
22 19
23 20 while True:
24 21 prompt = input("You: ")
25
26 response = you.Completion.create(
27 prompt = prompt,
28 chat = chat)
29
22
23 response = you.Completion.create(prompt=prompt, chat=chat)
24
30 25 print("Bot:", response["response"])
31
32 chat.append({"question": prompt, "answer": response["response"]})
26
27 chat.append({"question": prompt, "answer": response["response"]})
Modified you/README.md +9 -9
@@ -5,9 +5,9 @@ import you
5 5
6 6 # simple request with links and details
7 7 response = you.Completion.create(
8 prompt = "hello world",
9 detailed = True,
10 includelinks = True,)
8 prompt="hello world",
9 detailed=True,
10 include_links=True, )
11 11
12 12 print(response)
13 13
@@ -19,18 +19,18 @@ print(response)
19 19 # }
20 20 # }
21 21
22 #chatbot
22 # chatbot
23 23
24 24 chat = []
25 25
26 26 while True:
27 27 prompt = input("You: ")
28
28
29 29 response = you.Completion.create(
30 prompt = prompt,
31 chat = chat)
32
30 prompt=prompt,
31 chat=chat)
32
33 33 print("Bot:", response["response"])
34
34
35 35 chat.append({"question": prompt, "answer": response["response"]})
36 36 ```
Modified you/__init__.py +82 -61
@@ -1,78 +1,99 @@
1 from tls_client import Session
2 from re import findall
3 from json import loads, dumps
4 from uuid import uuid4
1 import re
2 from json import loads
3 from uuid import uuid4
4
5 from fake_useragent import UserAgent
6 from tls_client import Session
5 7
6 8
7 9 class Completion:
10 @staticmethod
8 11 def create(
9 prompt : str,
10 page : int = 1,
11 count : int = 10,
12 safeSearch : str = "Moderate",
13 onShoppingpage : bool = False,
14 mkt : str = "",
15 responseFilter : str = "WebPages,Translations,TimeZone,Computation,RelatedSearches",
16 domain : str = "youchat",
17 queryTraceId : str = None,
18 chat : list = [],
19 includelinks : bool = False,
20 detailed : bool = False,
21 debug : bool = False ) -> dict:
22
23 client = Session(client_identifier="chrome_108")
24 client.headers = {
25 "authority" : "you.com",
26 "accept" : "text/event-stream",
27 "accept-language" : "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
28 "cache-control" : "no-cache",
29 "referer" : "https://you.com/search?q=who+are+you&tbm=youchat",
30 "sec-ch-ua" : '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
31 "sec-ch-ua-mobile" : "?0",
32 "sec-ch-ua-platform": '"Windows"',
33 "sec-fetch-dest" : "empty",
34 "sec-fetch-mode" : "cors",
35 "sec-fetch-site" : "same-origin",
36 'cookie' : f'safesearch_guest=Moderate; uuid_guest={str(uuid4())}',
37 "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
38 }
12 prompt: str,
13 page: int = 1,
14 count: int = 10,
15 safe_search: str = 'Moderate',
16 on_shopping_page: bool = False,
17 mkt: str = '',
18 response_filter: str = 'WebPages,Translations,TimeZone,Computation,RelatedSearches',
19 domain: str = 'youchat',
20 query_trace_id: str = None,
21 chat: list = None,
22 include_links: bool = False,
23 detailed: bool = False,
24 debug: bool = False,
25 ) -> dict:
26 if chat is None:
27 chat = []
28
29 client = Session(client_identifier='chrome_108')
30 client.headers = Completion.__get_headers()
39 31
40 response = client.get(f"https://you.com/api/streamingSearch", params = {
41 "q" : prompt,
42 "page" : page,
43 "count" : count,
44 "safeSearch" : safeSearch,
45 "onShoppingPage" : onShoppingpage,
46 "mkt" : mkt,
47 "responseFilter" : responseFilter,
48 "domain" : domain,
49 "queryTraceId" : str(uuid4()) if queryTraceId is None else queryTraceId,
50 "chat" : str(chat), # {"question":"","answer":" '"}
51 }
32 response = client.get(
33 f'https://you.com/api/streamingSearch',
34 params={
35 'q': prompt,
36 'page': page,
37 'count': count,
38 'safeSearch': safe_search,
39 'onShoppingPage': on_shopping_page,
40 'mkt': mkt,
41 'responseFilter': response_filter,
42 'domain': domain,
43 'queryTraceId': str(uuid4()) if query_trace_id is None else query_trace_id,
44 'chat': str(chat), # {'question':'','answer':' ''}
45 },
52 46 )
53
54
47
55 48 if debug:
56 49 print('\n\n------------------\n\n')
57 50 print(response.text)
58 51 print('\n\n------------------\n\n')
59 52
60 youChatSerpResults = findall(r'youChatSerpResults\ndata: (.*)\n\nevent', response.text)[0]
61 thirdPartySearchResults = findall(r"thirdPartySearchResults\ndata: (.*)\n\nevent", response.text)[0]
62 #slots = findall(r"slots\ndata: (.*)\n\nevent", response.text)[0]
63
64 text = response.text.split('}]}\n\nevent: youChatToken\ndata: {"youChatToken": "')[-1]
65 text = text.replace('"}\n\nevent: youChatToken\ndata: {"youChatToken": "', '')
66 text = text.replace('event: done\ndata: I\'m Mr. Meeseeks. Look at me.\n\n', '')
67 text = text[:-4] # trims '"}', along with the last two remaining newlines
53 if 'youChatToken' not in response.text:
54 return Completion.__get_failure_response()
55
56 you_chat_serp_results = re.search(
57 r'(?<=event: youChatSerpResults\ndata:)(.*\n)*?(?=event: )', response.text
58 ).group()
59 third_party_search_results = re.search(
60 r'(?<=event: thirdPartySearchResults\ndata:)(.*\n)*?(?=event: )', response.text
61 ).group()
62 # slots = findall(r"slots\ndata: (.*)\n\nevent", response.text)[0]
63
64 text = ''.join(re.findall(r'{\"youChatToken\": \"(.*?)\"}', response.text))
68 65
69 66 extra = {
70 'youChatSerpResults' : loads(youChatSerpResults),
71 #'slots' : loads(slots)
67 'youChatSerpResults': loads(you_chat_serp_results),
68 # 'slots' : loads(slots)
72 69 }
73 70
74 71 return {
75 'response': text,
76 'links' : loads(thirdPartySearchResults)['search']["third_party_search_results"] if includelinks else None,
77 'extra' : extra if detailed else None,
72 'response': text.replace('\\n', '\n').replace('\\\\', '\\'),
73 'links': loads(third_party_search_results)['search']['third_party_search_results']
74 if include_links
75 else None,
76 'extra': extra if detailed else None,
78 77 }
78
79 @classmethod
80 def __get_headers(cls) -> dict:
81 return {
82 'authority': 'you.com',
83 'accept': 'text/event-stream',
84 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
85 'cache-control': 'no-cache',
86 'referer': 'https://you.com/search?q=who+are+you&tbm=youchat',
87 'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
88 'sec-ch-ua-mobile': '?0',
89 'sec-ch-ua-platform': '"Windows"',
90 'sec-fetch-dest': 'empty',
91 'sec-fetch-mode': 'cors',
92 'sec-fetch-site': 'same-origin',
93 'cookie': f'safesearch_guest=Moderate; uuid_guest={str(uuid4())}',
94 'user-agent': UserAgent().random,
95 }
96
97 @classmethod
98 def __get_failure_response(cls) -> dict:
99 return dict(response='Unable to fetch the response, Please try again.', links=[], extra={})