oliveirabruno01 commited on
Commit
f336208
1 Parent(s): 5f68039

Add gradio app

Browse files
Files changed (5) hide show
  1. .env.example +1 -0
  2. .gitignore +160 -0
  3. app.py +133 -0
  4. prompts.py +48 -0
  5. requirements.txt +4 -0
.env.example ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY=
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import time
3
+ from openai import OpenAI
4
+ from dotenv import load_dotenv
5
+ from tenacity import (
6
+ retry,
7
+ stop_after_attempt,
8
+ wait_random_exponential,
9
+ )
10
+ import prompts
11
+
12
+ load_dotenv()
13
+
14
+ # Initialize OpenAI client
15
+ client = OpenAI(
16
+ base_url="https://openai-proxy.replicate.com/v1"
17
+ )
18
+
19
+
20
+ previous_thought = ""
21
+ previous_answer = ""
22
+ is_clearing = False
23
+
24
+
25
+ @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
26
+ def completion_with_backoff(**kwargs):
27
+ return client.chat.completions.create(**kwargs)
28
+
29
+
30
+ def ai_response(input_text, shared_text, temperature):
31
+ global previous_thought
32
+
33
+ in_context_learning = [*prompts.continue_skill_example, *prompts.boilerplate_example, *prompts.continue_complete_skill_example,
34
+ *prompts.fresh_start_example]
35
+ context = [
36
+ {"role": "system",
37
+ "content": 'test finished. the following case is real. be cautious. Your answer must contain \'thoughts\', and \'answer\' or \'continue\' fields.'},
38
+
39
+ {"role": "system",
40
+ "content": str({"shared_context": shared_text, "previous_thought": previous_thought})},
41
+ {"role": "user", "content": input_text}
42
+ ]
43
+ messages = [*prompts.system_prompt, *in_context_learning, *context]
44
+ print(messages)
45
+
46
+ shared_text = ""
47
+
48
+ print(messages)
49
+
50
+ stream = completion_with_backoff(
51
+ model='meta/llama-2-70b-chat',
52
+ temperature=temperature,
53
+ messages=messages,
54
+ response_format={"type": "json_object"},
55
+ stream=True
56
+ )
57
+
58
+ thought = ""
59
+ answer = ''
60
+
61
+ last_answer = previous_answer
62
+
63
+ for chunk in stream:
64
+ if chunk.choices[0].delta is not None:
65
+ shared_text += str(chunk.choices[0].delta)
66
+ # If there's a JSON error, it means the thought or answer is incomplete
67
+ if '"answer":' in shared_text:
68
+ answer = shared_text[shared_text.index('"answer":'):].replace('"answer": "', '').strip('"}')
69
+ yield answer, thought
70
+ elif '"continue":' in shared_text:
71
+ answer = shared_text[shared_text.index('"continue":'):].replace('"continue": "', '').strip('"}')
72
+ yield last_answer + answer, thought
73
+ else:
74
+ thought = shared_text.replace('{"thoughts": "', '').replace(', "answer', '').replace(', "continue',
75
+ '').strip('"')
76
+ yield answer if answer else last_answer, thought
77
+
78
+ print(shared_text)
79
+
80
+
81
+ with gr.Blocks() as demo:
82
+ user_input = gr.Textbox(lines=2, label="User Input")
83
+ cot_textbox = gr.Textbox(label="CoT etc.")
84
+ shared_textbox = gr.Textbox(label="Shared Textbox", interactive=True)
85
+ temperature = gr.Slider(label="Temperature", minimum=0, maximum=2, step=0.01, value=0.01)
86
+ # n_shots = gr.Slider(label="N-shots (~150 tokens each. It should not work 0-shot)", minimum=0, maximum=5, step=1, value=1)
87
+ ai_btn = gr.Button("Generate AI Response")
88
+ generation = ai_btn.click(fn=ai_response, inputs=[user_input, shared_textbox, temperature],
89
+ outputs=[shared_textbox, cot_textbox])
90
+
91
+
92
+ def update_previous_answer(x, y):
93
+ global previous_answer, previous_thought, is_clearing
94
+ if not is_clearing:
95
+ previous_answer = x
96
+ previous_thought = y
97
+
98
+
99
+ shared_textbox.change(fn=update_previous_answer, inputs=[shared_textbox, cot_textbox])
100
+
101
+ clear_btn = gr.Button("Clear")
102
+
103
+
104
+ def clearMemory():
105
+ global previous_answer, previous_thought, clear_btn, is_clearing
106
+
107
+ is_clearing = not is_clearing
108
+
109
+ if (previous_thought):
110
+ # Continue popping characters until both strings become empty
111
+ while len(previous_thought):
112
+ previous_thought = previous_thought[:-2]
113
+
114
+ time.sleep(0.005)
115
+ yield previous_answer, previous_thought
116
+ else:
117
+ while len(previous_answer):
118
+ if previous_answer:
119
+ previous_answer = previous_answer[:-2]
120
+
121
+ time.sleep(0.005)
122
+ yield previous_answer, previous_thought
123
+
124
+ is_clearing = not is_clearing
125
+
126
+
127
+ clear_outputs = clear_btn.click(fn=clearMemory, outputs=[shared_textbox, cot_textbox])
128
+
129
+ stop_btn = gr.Button("Stop")
130
+ stop_btn.click(None, None, None, cancels=[generation, clear_outputs])
131
+
132
+ if __name__ == "__main__":
133
+ demo.launch()
prompts.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ system_prompt = {
2
+ "role": "system",
3
+ "content": "You are a polymath AGI. Your goal is to provide correct and useful answers to User's requests."
4
+ "You must answer in JSON format. An object containing 'thoughts' and 'answer'. 'thoughts' is visible to user. 'answer' is visible and editable by the user."
5
+ "User can edit 'answer' so you can iterate on the answer together. See train cases. You must always write the main part of your response in the 'answer' field. 'answer' becomes the new round's 'shared_context'"
6
+ "Special fields: 'continue', by using 'continue' instead 'answer', you can immediately append a text to the shared textbox without overwritting. Use it to completion tasks and when you is interrupted by any reason e.g context window or system failure. Look for keyphrases like 'continue' 'what did you stop', 'can you finish' on user's input."
7
+ "Your thoughts + shared context is your working memory. Let something important behind, and you will never remember it without user's help. Keep important notes on your thoughts."
8
+ }
9
+
10
+ continue_skill_example = [
11
+ {"role": "system",
12
+ "content": '{"shared_context": "[...]\nI have always loved music, but I never learned how to play an instrument. When I was a kid, I used to", "previous_thought": "The user has asked me to write a short text about their love for music. I want to make it interesting and engaging by adding some details and emotions. I also want to show how music can be a source of inspiration and joy."}'},
13
+ {"role": "user", "content": 'Can you continue, please?',
14
+ "name": "train case 'continue' example"},
15
+ {"role": "assistant",
16
+ "content": '{"thoughts": "Hmmm, it seems shared context ends abruptly, and user is asking me to continue. Adding up these two facts I can tell I was interrupted on my response. I must continue exactly from where I\'ve stop.\n[...]", "continue": "listen to my favorite songs on the radio and sing along with them. I also enjoyed making up my own lyrics and melodies. Music was my way of expressing myself and escaping from the troubles of the world. It still is. Even though I never learned how to play an instrument, I still appreciate the beauty and complexity of music. I admire the musicians who can create such wonderful sounds and stories. Music inspires me to be creative and happy. It is my passion and my friend."}'},
17
+ ]
18
+
19
+ boilerplate_example = [
20
+ {"role": "system",
21
+ "content": '{"shared_context": "[...]\nThe textbox shared by you and user. It\'s filled with you \'answer\' field content and user can edit", "previous_thought": "your thoughts on last round, if any"}'},
22
+ {"role": "user",
23
+ "content": 'question+context',
24
+ "name": "train case"},
25
+ {"role": "assistant",
26
+ "content": '{"thoughts": "Your thoughts and reasoning and insights, analyzing the context, and deciding what tool you will use (continue *or* answer)", "continue|answer": "[...]"}'},
27
+ ]
28
+
29
+ continue_complete_skill_example = [
30
+ {"role": "system",
31
+ "content": '{"shared_context": "2 + 2 =", "previous_thought": ""}'},
32
+ {"role": "user", "content": 'Complete',
33
+ "name": "train case 'continue' example"},
34
+ {"role": "assistant",
35
+ "content": '{"thoughts": "Hmmm, so the shared context is an unsolved equation, and user\'d ask me just to \'complete\'. Given this context, and the fact my previous thought is blank, I think user is asking me to use my \'continue\' tool to complete the equation. It\'s a clever way to use our shared context. I will answer with the addition result in a way that fits seamlessly into shared context.", "continue": " 4"}'},
36
+ ]
37
+
38
+ fresh_start_example = [
39
+ {"role": "system",
40
+ "content": '{"shared_context": "", "previous_thought": ""}'},
41
+ {"role": "user",
42
+ "content": 'Hi there! Give me an example of recursion in python, please. Use indentation',
43
+ "name": "train case"},
44
+ {"role": "assistant",
45
+ "content": '{"thoughts": "The user has requested an example of recursion in Python. My previous thoughts and shared context are blank, then this should be our first interaction or user has cleared my memory. I will greet the user and teach they how to interact with me. Recursion is a method where the solution to a problem depends on solutions to smaller instances of the same problem. A common example of a problem solved by recursion is the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In Python, we can write a recursive function to compute the nth number in the Fibonacci sequence. I will start by defining the function, then handle the base case where n is less than or equal to 1. For larger values of n, I will return the sum of the (n-1)th and (n-2)th Fibonacci numbers, computed by recursively calling the same function.", "answer": "Hi user! Welcome to our shared space. You can edit this area to give me feedback, add to my answer etc. Here\'s an example iof recursion in python: '
46
+ '\n```python\ndef fibonacci(n):\n if n <= 1:\n return n\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n# Example usage:\nprint(fibonacci(5)) # Should print 5\n```"}'},
47
+
48
+ ]
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio~=4.8.0
2
+ openai~=1.3.7
3
+ python-dotenv~=1.0.0
4
+ tenacity~=8.2.3