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

XFEstudio/gpt4free

First implementation of streamlit chat app in gui folder

952f7dbe
noptuno <repollo.marrero@gmail.com>
提交于

代码差异

8 个文件 +334 -3
Modified .gitignore +9 -0
@@ -7,6 +7,15 @@
7 7 /dataSources/
8 8 /dataSources.local.xml
9 9
10 # Ignore local python virtual environment
11 venv/
12
13 # Ignore streamlit_chat_app.py conversations pickle
14 conversations.pkl
15
16 # Ignore accounts created by api's
17 accounts.txt
18
10 19 .idea/
11 20
12 21 */__pycache__/
Modified gui/README.md +64 -3
@@ -1,11 +1,72 @@
1 1 # gpt4free gui
2 2
3 mode `streamlit_app.py` into base folder to run
3 This code provides a Graphical User Interface (GUI) for gpt4free. Users can ask questions and get answers from GPT-4 API's, utilizing multiple API implementations. The project contains two different Streamlit applications: `streamlit_app.py` and `streamlit_chat_app.py`.
4 4
5 Installation
6 ------------
7
8 1. Clone the repository.
9 2. Install the required dependencies with: `pip install -r requirements.txt`.
10 3. To use `streamlit_chat_app.py`, note that it depends on a pull request (PR #24) from the https://github.com/AI-Yash/st-chat/ repository, which may change in the future. The current dependency library can be found at https://github.com/AI-Yash/st-chat/archive/refs/pull/24/head.zip.
11
12 Usage
13 -----
14
15 Choose one of the Streamlit applications to run:
16
17 ### streamlit\_app.py
18
19 This application provides a simple interface for asking GPT-4 questions and receiving answers.
20
21 To run the application:
22
23 run:
24 ```arduino
25 streamlit run gui/streamlit_app.py
26 ```
27 <br>
28
29 <img width="724" alt="image" src="https://user-images.githubusercontent.com/98614666/234232449-0d5cd092-a29d-4759-8197-e00ba712cb1a.png">
30
31 <br>
32 <br>
5 33
6 34 preview:
35
7 36 <img width="1125" alt="image" src="https://user-images.githubusercontent.com/98614666/234232398-09e9d3c5-08e6-4b8a-b4f2-0666e9790c7d.png">
8 37
9 38
10 run:
11 <img width="724" alt="image" src="https://user-images.githubusercontent.com/98614666/234232449-0d5cd092-a29d-4759-8197-e00ba712cb1a.png">
39 ### streamlit\_chat\_app.py
40
41 This application provides a chat-like interface for asking GPT-4 questions and receiving answers. It supports multiple query methods, and users can select the desired API for their queries. The application also maintains a conversation history.
42
43 To run the application:
44
45 ```arduino
46 streamlit run streamlit_chat_app.py
47 ```
48
49 <br>
50
51 <img width="724" alt="image" src="image1.png">
52
53 <br>
54 <br>
55
56 preview:
57
58 <img width="1125" alt="image" src="image2.png">
59
60 Contributing
61 ------------
62
63 Feel free to submit pull requests, report bugs, or request new features by opening issues on the GitHub repository.
64
65 Bug
66 ----
67 There is a bug in `streamlit_chat_app.py` right now that I haven't pinpointed yet, probably is really simple but havent had the time to look for it. Whenever you open a new conversation or access an old conversation it will only start prompt-answering after the second time you input to the text input, other than that, everything else seems to work accordingly.
68
69 License
70 -------
71
72 This project is licensed under the MIT License.
Added gui/__init__.py +0 -0
此文件没有可显示的逐行差异。
Added gui/image1.png +0 -0
二进制文件已变更,无法进行逐行预览。
Added gui/image2.png +0 -0
二进制文件已变更,无法进行逐行预览。
Added gui/query_methods.py +163 -0
@@ -0,0 +1,163 @@
1 import forefront, quora, theb, you
2 import random
3
4
5
6 def query_forefront(question: str) -> str:
7 # create an account
8 token = forefront.Account.create(logging=True)
9
10 # get a response
11 try:
12 result = forefront.StreamingCompletion.create(token = token, prompt = 'hello world', model='gpt-4')
13
14 return result['response']
15
16 except Exception as e:
17 # Return error message if an exception occurs
18 return f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.'
19
20
21 def query_quora(question: str) -> str:
22 token = quora.Account.create(logging=False, enable_bot_creation=True)
23 response = quora.Completion.create(
24 model='gpt-4',
25 prompt=question,
26 token=token
27 )
28
29 return response.completion.choices[0].tex
30
31
32 def query_theb(question: str) -> str:
33 # Set cloudflare clearance cookie and get answer from GPT-4 model
34 try:
35 result = theb.Completion.create(
36 prompt = question)
37
38 return result['response']
39
40 except Exception as e:
41 # Return error message if an exception occurs
42 return f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.'
43
44
45 def query_you(question: str) -> str:
46 # Set cloudflare clearance cookie and get answer from GPT-4 model
47 try:
48 result = you.Completion.create(
49 prompt = question)
50
51 return result['response']
52
53 except Exception as e:
54 # Return error message if an exception occurs
55 return f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.'
56
57 # Define a dictionary containing all query methods
58 avail_query_methods = {
59 "Forefront": query_forefront,
60 "Quora": query_quora,
61 "Theb": query_theb,
62 "You": query_you,
63 # "Writesonic": query_writesonic,
64 # "T3nsor": query_t3nsor,
65 # "Phind": query_phind,
66 # "Ora": query_ora,
67 }
68
69 def query(user_input: str, selected_method: str = "Random") -> str:
70
71 # If a specific query method is selected (not "Random") and the method is in the dictionary, try to call it
72 if selected_method != "Random" and selected_method in avail_query_methods:
73 try:
74 return avail_query_methods[selected_method](user_input)
75 except Exception as e:
76 print(f"Error with {selected_method}: {e}")
77 return "😵 Sorry, some error occurred please try again."
78
79 # Initialize variables for determining success and storing the result
80 success = False
81 result = "😵 Sorry, some error occurred please try again."
82 # Create a list of available query methods
83 query_methods_list = list(avail_query_methods.values())
84
85 # Continue trying different methods until a successful result is obtained or all methods have been tried
86 while not success and query_methods_list:
87 # Choose a random method from the list
88 chosen_query = random.choice(query_methods_list)
89 # Find the name of the chosen method
90 chosen_query_name = [k for k, v in avail_query_methods.items() if v == chosen_query][0]
91 try:
92 # Try to call the chosen method with the user input
93 result = chosen_query(user_input)
94 success = True
95 except Exception as e:
96 print(f"Error with {chosen_query_name}: {e}")
97 # Remove the failed method from the list of available methods
98 query_methods_list.remove(chosen_query)
99
100 return result
101
102
103 __all__ = ['query', 'avail_query_methods']
104
105
106
107 # def query_ora(question:str)->str:
108 # result =""
109 # try:
110 # gpt4_chatbot_ids = ['b8b12eaa-5d47-44d3-92a6-4d706f2bcacf', 'fbe53266-673c-4b70-9d2d-d247785ccd91', 'bd5781cf-727a-45e9-80fd-a3cfce1350c6', '993a0102-d397-47f6-98c3-2587f2c9ec3a', 'ae5c524e-d025-478b-ad46-8843a5745261', 'cc510743-e4ab-485e-9191-76960ecb6040', 'a5cd2481-8e24-4938-aa25-8e26d6233390', '6bca5930-2aa1-4bf4-96a7-bea4d32dcdac', '884a5f2b-47a2-47a5-9e0f-851bbe76b57c', 'd5f3c491-0e74-4ef7-bdca-b7d27c59e6b3', 'd72e83f6-ef4e-4702-844f-cf4bd432eef7', '6e80b170-11ed-4f1a-b992-fd04d7a9e78c', '8ef52d68-1b01-466f-bfbf-f25c13ff4a72', 'd0674e11-f22e-406b-98bc-c1ba8564f749', 'a051381d-6530-463f-be68-020afddf6a8f', '99c0afa1-9e32-4566-8909-f4ef9ac06226', '1be65282-9c59-4a96-99f8-d225059d9001', 'dba16bd8-5785-4248-a8e9-b5d1ecbfdd60', '1731450d-3226-42d0-b41c-4129fe009524', '8e74635d-000e-4819-ab2c-4e986b7a0f48', 'afe7ed01-c1ac-4129-9c71-2ca7f3800b30', 'e374c37a-8c44-4f0e-9e9f-1ad4609f24f5']
111 # chatbot_id = random.choice(gpt4_chatbot_ids)
112 # model = ora.CompletionModel.load(chatbot_id, 'gpt-4')
113 # response = ora.Completion.create(model, question)
114 # result = response.completion.choices[0].text
115 # except Exception as e:
116 # print(f"Error : {e}")
117 # result = "😵 Sorry, some error occurred please try again."
118 # return result
119
120
121 # def query_writesonic(question:str)->str:
122 # account = writesonic.Account.create(logging = False)
123 # response = writesonic.Completion.create(
124 # api_key = account.key,
125 # prompt = question,
126 # )
127
128 # return response.completion.choices[0].text
129
130
131 # def query_t3nsor(question: str) -> str:
132 # messages = []
133
134 # user = question
135
136 # t3nsor_cmpl = t3nsor.Completion.create(
137 # prompt=user,
138 # messages=messages
139 # )
140
141 # messages.extend([
142 # {'role': 'user', 'content': user},
143 # {'role': 'assistant', 'content': t3nsor_cmpl.completion.choices[0].text}
144 # ])
145
146 # return t3nsor_cmpl.completion.choices[0].text
147
148
149
150 # def query_phind(question:str)->str:
151 # phind.cf_clearance = 'KvXc1rh.TFQG1rNF0eMlcpJbsdmJkYgvmqS42OOfqUk-1682393898-0-160'
152 # # phind.cf_clearance = 'heguhSRBB9d0sjLvGbQECS8b80m2BQ31xEmk9ChshKI-1682268995-0-160'
153 # # phind.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
154 # phind.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4.1 Safari/605.1.15'
155 # result = phind.Completion.create(
156 # model = 'gpt-4',
157 # prompt = question,
158 # results = phind.Search.create(question, actualSearch = False),
159 # creative = False,
160 # detailed = False,
161 # codeContext = '')
162 # # print(result.completion.choices[0].text)
163 # return result.completion.choices[0].text
Added gui/streamlit_chat_app.py +97 -0
@@ -0,0 +1,97 @@
1 import os
2 import sys
3
4 sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir))
5
6 import streamlit as st
7 from streamlit_chat import message
8 from query_methods import query, avail_query_methods
9 import pickle
10
11
12 conversations_file = "conversations.pkl"
13
14 def load_conversations():
15 try:
16 with open(conversations_file, "rb") as f:
17 return pickle.load(f)
18 except FileNotFoundError:
19 return []
20
21 def save_conversations(conversations, current_conversation):
22 updated = False
23 for i, conversation in enumerate(conversations):
24 if conversation == current_conversation:
25 conversations[i] = current_conversation
26 updated = True
27 break
28 if not updated:
29 conversations.append(current_conversation)
30 with open(conversations_file, "wb") as f:
31 pickle.dump(conversations, f)
32
33 st.header("Chat Placeholder")
34
35 if 'conversations' not in st.session_state:
36 st.session_state['conversations'] = load_conversations()
37
38 if 'input_text' not in st.session_state:
39 st.session_state['input_text'] = ''
40
41 if 'selected_conversation' not in st.session_state:
42 st.session_state['selected_conversation'] = None
43
44 if 'input_field_key' not in st.session_state:
45 st.session_state['input_field_key'] = 0
46
47 if 'query_method' not in st.session_state:
48 st.session_state['query_method'] = query
49
50 # Initialize new conversation
51 if 'current_conversation' not in st.session_state or st.session_state['current_conversation'] is None:
52 st.session_state['current_conversation'] = {'user_inputs': [], 'generated_responses': []}
53
54
55 input_placeholder = st.empty()
56 user_input = input_placeholder.text_input('You:', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}')
57 submit_button = st.button("Submit")
58
59 if user_input or submit_button:
60 output = query(user_input, st.session_state['query_method'])
61
62 st.session_state.current_conversation['user_inputs'].append(user_input)
63 st.session_state.current_conversation['generated_responses'].append(output)
64 save_conversations(st.session_state.conversations, st.session_state.current_conversation)
65 user_input = input_placeholder.text_input('You:', value='', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}') # Clear the input field
66
67
68 # Add a button to create a new conversation
69 if st.sidebar.button("New Conversation"):
70 st.session_state['selected_conversation'] = None
71 st.session_state['current_conversation'] = {'user_inputs': [], 'generated_responses': []}
72 st.session_state['input_field_key'] += 1
73
74
75 st.session_state['query_method'] = st.sidebar.selectbox(
76 "Select API:",
77 options=avail_query_methods.keys(),
78 index=0
79 )
80
81 # Sidebar
82 st.sidebar.header("Conversation History")
83
84 for i, conversation in enumerate(st.session_state.conversations):
85 if st.sidebar.button(f"Conversation {i + 1}: {conversation['user_inputs'][0]}", key=f"sidebar_btn_{i}"):
86 st.session_state['selected_conversation'] = i
87 st.session_state['current_conversation'] = st.session_state.conversations[i]
88
89 if st.session_state['selected_conversation'] is not None:
90 conversation_to_display = st.session_state.conversations[st.session_state['selected_conversation']]
91 else:
92 conversation_to_display = st.session_state.current_conversation
93
94 if conversation_to_display['generated_responses']:
95 for i in range(len(conversation_to_display['generated_responses']) - 1, -1, -1):
96 message(conversation_to_display["generated_responses"][i], key=f"display_generated_{i}")
97 message(conversation_to_display['user_inputs'][i], is_user=True, key=f"display_user_{i}")
Modified requirements.txt +1 -0
@@ -9,3 +9,4 @@ streamlit==1.21.0
9 9 selenium
10 10 fake-useragent
11 11 twocaptcha
12 https://github.com/AI-Yash/st-chat/archive/refs/pull/24/head.zip