louis030195 commited on
Commit
9572c0e
β€’
1 Parent(s): e7436ec

Add application file

Browse files
Files changed (7) hide show
  1. .gitignore +2 -0
  2. .vscode/settings.json +3 -0
  3. Makefile +15 -0
  4. README.md +5 -3
  5. app.py +153 -0
  6. requirements-test.txt +13 -0
  7. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ env
2
+ .env
.vscode/settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "python.formatting.provider": "black"
3
+ }
Makefile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ push:
2
+ git add .
3
+ git commit -m "πŸ™ˆ"
4
+ git push
5
+
6
+
7
+ install: ## [DEVELOPMENT] Install the API dependencies
8
+ virtualenv env; \
9
+ source env/bin/activate; \
10
+ pip install -r requirements.txt; \
11
+ pip install -r requirements-test.txt
12
+ @echo "Done, run '\033[0;31msource env/bin/activate\033[0m' to activate the virtual environment"
13
+
14
+ run: ## [DEVELOPMENT] Run the streamlit app
15
+ streamlit run app.py
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
  title: Infinite Memory Chatgpt
3
- emoji: ⚑
4
- colorFrom: blue
5
- colorTo: purple
6
  sdk: streamlit
7
  sdk_version: 1.17.0
8
  app_file: app.py
@@ -11,3 +11,5 @@ license: mit
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
  title: Infinite Memory Chatgpt
3
+ emoji: πŸ“š
4
+ colorFrom: red
5
+ colorTo: indigo
6
  sdk: streamlit
7
  sdk_version: 1.17.0
8
  app_file: app.py
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+ https://embedbase.xyz
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ try:
4
+ import dotenv
5
+ except ImportError:
6
+ pass
7
+
8
+ dotenv.load_dotenv()
9
+ import openai
10
+ import os
11
+ import streamlit.components.v1 as components
12
+ import requests
13
+ import asyncio
14
+
15
+ openai.api_key = os.getenv("OPENAI_API_KEY")
16
+ embedbase_api_key = os.getenv("EMBEDBASE_API_KEY")
17
+
18
+ URL = "https://embedbase-hosted-usx5gpslaq-uc.a.run.app"
19
+ local_history = []
20
+
21
+
22
+ async def add_to_dataset(dataset_id: str, data: str):
23
+ response = requests.post(
24
+ f"{URL}/v1/{dataset_id}",
25
+ headers={
26
+ "Content-Type": "application/json",
27
+ "Authorization": "Bearer " + embedbase_api_key,
28
+ },
29
+ json={
30
+ "documents": [
31
+ {
32
+ "data": data,
33
+ },
34
+ ],
35
+ },
36
+ )
37
+ response.raise_for_status()
38
+ return response.json()
39
+
40
+
41
+ async def search_dataset(dataset_id: str, query: str, limit: int = 3):
42
+ response = requests.post(
43
+ f"{URL}/v1/{dataset_id}/search",
44
+ headers={
45
+ "Content-Type": "application/json",
46
+ "Authorization": "Bearer " + embedbase_api_key,
47
+ },
48
+ json={
49
+ "query": query,
50
+ "top_k": limit,
51
+ },
52
+ )
53
+ response.raise_for_status()
54
+ return response.json()
55
+
56
+
57
+ async def chat(user_input: str, conversation_name: str) -> str:
58
+ local_history.append(user_input)
59
+
60
+ history = await search_dataset(
61
+ f"infinite-pt-{conversation_name}",
62
+ # searching using last 4 messages from local history
63
+ "\n\n---\n\n".join(local_history[-4:]),
64
+ limit=3,
65
+ )
66
+ print("history", history)
67
+ response = openai.ChatCompletion.create(
68
+ model="gpt-3.5-turbo",
69
+ messages=[
70
+ {
71
+ "role": "system",
72
+ "content": "You are a helpful assistant.",
73
+ },
74
+ *[
75
+ {
76
+ "role": "assistant",
77
+ "content": h["data"],
78
+ }
79
+ for h in history["similarities"][-5:]
80
+ ],
81
+ {"role": "user", "content": user_input},
82
+ ],
83
+ )
84
+ message = response.choices[0]["message"]
85
+ await add_to_dataset(f"infinite-pt-{conversation_name}", message["content"])
86
+
87
+ local_history.append(message)
88
+
89
+ return message["content"]
90
+
91
+
92
+ from datetime import datetime
93
+
94
+ # conversation name is date like ddmmyy_hhmmss
95
+ # conversation_name = datetime.now().strftime("%d%m%y_%H%M%S")
96
+ conversation_name = st.text_input("Conversation name", "purpose")
97
+
98
+ # eg not local dev
99
+ if not os.getenv("OPENAI_API_KEY"):
100
+ embedbase_api_key = st.text_input(
101
+ "Your Embedbase key", "get it here <https://app.embedbase.xyz/signup>"
102
+ )
103
+ openai_key = st.text_input(
104
+ "Your OpenAI key", "get it here <https://platform.openai.com/account/api-keys>"
105
+ )
106
+ openai.api_key = openai_key
107
+ user_input = st.text_input("You", "How can I reach maximum happiness this year?")
108
+ if st.button("Send"):
109
+ infinite_pt_response = asyncio.run(chat(user_input, conversation_name))
110
+ st.markdown(
111
+ f"""
112
+ Infinite-PT
113
+ """
114
+ )
115
+ st.write(infinite_pt_response)
116
+
117
+ components.html(
118
+ """
119
+ <script>
120
+ const doc = window.parent.document;
121
+ buttons = Array.from(doc.querySelectorAll('button[kind=primary]'));
122
+ const send = buttons.find(el => el.innerText === 'Send');
123
+ doc.addEventListener('keydown', function(e) {
124
+ switch (e.keyCode) {
125
+ case 13:
126
+ send.click();
127
+ break;
128
+ }
129
+ });
130
+ </script>
131
+ """,
132
+ height=0,
133
+ width=0,
134
+ )
135
+
136
+
137
+ st.markdown(
138
+ """
139
+ [Source code](https://huggingface.co/spaces/louis030195/infinite-memory-chatgpt)
140
+ """
141
+ )
142
+
143
+ st.markdown(
144
+ """
145
+ Built with ❀️ by [louis030195](https://louis030195.com).
146
+ """
147
+ )
148
+
149
+ st.markdown(
150
+ """
151
+ Powered by [Embedbase](https://embedbase.xyz).
152
+ """
153
+ )
requirements-test.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ black
2
+ mypy
3
+ pylint
4
+ pytest-cov
5
+ pytest-xdist
6
+ pytest
7
+ ipykernel
8
+ ipywidgets
9
+ httpx
10
+ trio
11
+ pytest-asyncio
12
+ watchdog
13
+ python-dotenv
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ openai
3
+ tenacity
4
+ python-dotenv