momegas commited on
Commit
ec49eb9
β€’
1 Parent(s): 3d169b1

πŸ€– Documentation megabot... Go!

Browse files
.github/workflows/hr-sync.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+
6
+ # to run this workflow manually from the Actions tab
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ sync-to-hub:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v3
14
+ with:
15
+ fetch-depth: 0
16
+ lfs: true
17
+ - name: Push to hub
18
+ env:
19
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
20
+ run: git push https://HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/HF_USERNAME/megabots main
Makefile CHANGED
@@ -26,6 +26,9 @@ trace:
26
  freeze:
27
  $(PIP) freeze > requirements.txt
28
 
 
 
 
29
  help:
30
  @echo "install - install dependencies"
31
  @echo "test - run tests"
 
26
  freeze:
27
  $(PIP) freeze > requirements.txt
28
 
29
+ gradio:
30
+ gradio app.py
31
+
32
  help:
33
  @echo "install - install dependencies"
34
  @echo "test - run tests"
README.md CHANGED
@@ -1,16 +1,16 @@
1
  # πŸ€– Megabots
2
 
3
  [![Tests](https://github.com/momegas/qnabot/actions/workflows/python-package.yml/badge.svg)](https://github.com/momegas/qnabot/actions/workflows/python-package.yml)
4
- [![Python Version](https://img.shields.io/badge/python-%203.10%20-blue.svg)](#supported-python-versions)
5
  [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
6
  [![License](https://img.shields.io/badge/License-MIT-informational.svg)](https://github.com/momegas/megabots/blob/main/LICENCE)
7
  ![](https://dcbadge.vercel.app/api/server/zkqDWk5S7P?style=flat&n&compact=true)
8
 
9
-
10
  πŸ€– Megabots provides State-of-the-art, production ready LLM apps made mega-easy, so you don't have to build them from scratch 🀯 Create a bot, now 🫡
11
 
12
  - πŸ‘‰ Join us on Discord: https://discord.gg/zkqDWk5S7P
13
  - ✈️ Work is managed in this project: https://github.com/users/momegas/projects/5/views/2
 
14
 
15
  **The Megabots library can be used to create bots that:**
16
 
@@ -44,7 +44,7 @@ import os
44
 
45
  os.environ["OPENAI_API_KEY"] = "my key"
46
 
47
- # Create a bot πŸ‘‰ with one line of code. Automatically loads your data from ./index or index.pkl.
48
  # Keep in mind that you need to have one or another.
49
  qnabot = bot("qna-over-docs")
50
 
@@ -244,6 +244,7 @@ sequenceDiagram
244
  API -->> User: Return response
245
 
246
  ```
 
247
  ## How to contribute?
248
 
249
  We welcome any suggestions, problem reports, and contributions!
 
1
  # πŸ€– Megabots
2
 
3
  [![Tests](https://github.com/momegas/qnabot/actions/workflows/python-package.yml/badge.svg)](https://github.com/momegas/qnabot/actions/workflows/python-package.yml)
4
+ [![Python Version](https://img.shields.io/badge/python-%203.10%20-blue.svg)](#supported-python-versions)
5
  [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
6
  [![License](https://img.shields.io/badge/License-MIT-informational.svg)](https://github.com/momegas/megabots/blob/main/LICENCE)
7
  ![](https://dcbadge.vercel.app/api/server/zkqDWk5S7P?style=flat&n&compact=true)
8
 
 
9
  πŸ€– Megabots provides State-of-the-art, production ready LLM apps made mega-easy, so you don't have to build them from scratch 🀯 Create a bot, now 🫡
10
 
11
  - πŸ‘‰ Join us on Discord: https://discord.gg/zkqDWk5S7P
12
  - ✈️ Work is managed in this project: https://github.com/users/momegas/projects/5/views/2
13
+ - πŸ€– Documentation bot: https://huggingface.co/spaces/momegas/megabots
14
 
15
  **The Megabots library can be used to create bots that:**
16
 
 
44
 
45
  os.environ["OPENAI_API_KEY"] = "my key"
46
 
47
+ # Create a bot πŸ‘‰ with one line of code. Automatically loads your data from ./index or index.pkl.
48
  # Keep in mind that you need to have one or another.
49
  qnabot = bot("qna-over-docs")
50
 
 
244
  API -->> User: Return response
245
 
246
  ```
247
+
248
  ## How to contribute?
249
 
250
  We welcome any suggestions, problem reports, and contributions!
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is an example of what you can build with πŸ€–Megabots.
3
+ It is hosted here: https://huggingface.co/spaces/momegas/megabots
4
+
5
+ """
6
+
7
+ from megabots import bot, create_interface
8
+
9
+ prompt = """
10
+ You are programming assistant that helps programmers develop apps with the Megabots library.
11
+ Use the following pieces of context to answer the question at the end.
12
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
13
+ If the question asks for python code you can provide it.
14
+
15
+ Context:
16
+ {context}
17
+
18
+ Conversation history:
19
+ {history}
20
+ Human: {question}
21
+ AI:
22
+ """
23
+
24
+ qnabot = bot(
25
+ "qna-over-docs",
26
+ index="./examples/files",
27
+ memory="conversation-buffer-window",
28
+ prompt=prompt,
29
+ )
30
+
31
+
32
+ text = """
33
+ You can ask this bot anything about πŸ€–Megabots. Here are some examples:
34
+ - What is Megabots?
35
+ - How can I create a bot?
36
+ - How can I change the prompt?
37
+ - How can I create a bot that has memory and can connect to a milvus vector database?
38
+ - How can I customise the bot function?
39
+ - How can I an API out of my bot?
40
+ - How can I an intrface out of my bot?
41
+ - Where can i find the megabots repo?
42
+ """
43
+
44
+ iface = create_interface(qnabot, text)
45
+ iface.launch()
examples/files/facts.txt CHANGED
@@ -1,20 +1,221 @@
1
- The Avengers first appeared in Marvel Comics in September 1963 with "The Avengers #1."
2
- The original Avengers lineup included Iron Man, Thor, Hulk, Ant-Man, and the Wasp.
3
- Captain America joined the team in "The Avengers #4" (March 1964) after being discovered frozen in ice.
4
- The Avengers were created by writer Stan Lee and artist Jack Kirby, two comic book legends.
5
- The team's battle cry, "Avengers Assemble!", was first used in "The Avengers #10" (November 1964).
6
- The Avengers have had numerous lineup changes over the years, with many Marvel characters joining and leaving the team.
7
- The Avengers' primary headquarters is the Avengers Mansion, located in New York City, but they have had other bases such as the Avengers Tower and the Hydrobase.
8
- Jarvis, the loyal butler, has been a supporting character in the comics, often assisting the team and maintaining the mansion.
9
- The Avengers have had various sub-teams and spin-offs, including the West Coast Avengers, Secret Avengers, and Young Avengers.
10
- The 2012 film "The Avengers," directed by Joss Whedon, was the first Marvel Cinematic Universe movie to feature the superhero team.
11
- In the MCU, the team was initially formed by Nick Fury, director of S.H.I.E.L.D., as part of his "Avengers Initiative."
12
- The MCU Avengers lineup included Iron Man, Captain America, Thor, Hulk, Black Widow, and Hawkeye.
13
- "The Avengers" (2012) was the first Marvel film to gross over $1 billion at the box office.
14
- The MCU Avengers have appeared in four main films: "The Avengers" (2012), "Avengers: Age of Ultron" (2015), "Avengers: Infinity War" (2018), and "Avengers: Endgame" (2019).
15
- "Avengers: Endgame" (2019) became the highest-grossing film of all time, overtaking "Avatar" (2009).
16
- The Avengers often face world-threatening villains, such as Loki, Ultron, and Thanos.
17
- The Vision, an android superhero, was created by Ultron but ultimately joined the Avengers and became an important member of the team.
18
- In the comics, Scarlet Witch and Quicksilver, who are siblings, initially were members of the villainous Brotherhood of Mutants before joining the Avengers.
19
- The Avengers have crossed over with other superhero teams, such as the X-Men and the Fantastic Four, in various comic book storylines.
20
- The Avengers have appeared in numerous animated TV series, including "The Avengers: Earth's Mightiest Heroes" (2010-2012) and "Avengers Assemble" (2013-2019).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸ€– Megabots
2
+
3
+ author: Megaklis Vasilakis
4
+ author_email: megaklis.vasilakis@gmail.com
5
+ repo: https://github.com/momegas/megabots
6
+
7
+ πŸ€– Megabots provides State-of-the-art, production ready LLM apps made mega-easy, so you don't have to build them from scratch 🀯 Create a bot, now 🫡
8
+
9
+ - πŸ‘‰ Join us on Discord: https://discord.gg/zkqDWk5S7P
10
+ - ✈️ Work is managed in this project: https://github.com/users/momegas/projects/5/views/2
11
+
12
+ **The Megabots library can be used to create bots that:**
13
+
14
+ - ⌚️ are production ready, in minutes
15
+ - πŸ—‚οΈ can answer questions over documents
16
+ - πŸ’Ύ can connect to vector databases
17
+ - πŸŽ–οΈ automatically expose the bot as a rebust API using FastAPI (early release)
18
+ - πŸ“ automatically expose the bot as a UI using Gradio
19
+
20
+ **Coming soon:**
21
+
22
+ - πŸ—£οΈ accept voice as an input using [whisper](https://github.com/openai/whisper)
23
+ - πŸ‘ validate and correct the outputs of LLMs using [guardrails](https://github.com/ShreyaR/guardrails)
24
+ - πŸ’° semanticly cache LLM Queries and reduce Costs by 10x using [GPTCache](https://github.com/zilliztech/GPTCache)
25
+ - πŸ‹οΈ mega-easy LLM training
26
+ - πŸš€ mega-easy deployment
27
+
28
+ πŸ€– Megabots is backed by some of the most famous tools for productionalising AI. It uses [LangChain](https://docs.langchain.com/docs/) for managing LLM chains, [FastAPI](https://fastapi.tiangolo.com/) to create a production ready API, [Gradio](https://gradio.app/) to create a UI. At the moment it uses [OpenAI](https://openai.com/) to generate answers, but we plan to support other LLMs in the future.
29
+
30
+ ## Getting started
31
+
32
+ Note: This is a work in progress. The API might change.
33
+
34
+ ```bash
35
+ pip install megabots
36
+ ```
37
+
38
+ ```python
39
+ from megabots import bot
40
+ import os
41
+
42
+ os.environ["OPENAI_API_KEY"] = "my key"
43
+
44
+ # Create a bot πŸ‘‰ with one line of code. Automatically loads your data from ./index or index.pkl.
45
+ # Keep in mind that you need to have one or another.
46
+ qnabot = bot("qna-over-docs")
47
+
48
+ # Ask a question
49
+ answer = bot.ask("How do I use this bot?")
50
+
51
+ # Save the index to save costs (GPT is used to create the index)
52
+ bot.save_index("index.pkl")
53
+
54
+ # Load the index from a previous run
55
+ qnabot = bot("qna-over-docs", index="./index.pkl")
56
+
57
+ # Or create the index from a directory of documents
58
+ qnabot = bot("qna-over-docs", index="./index")
59
+
60
+ # Change the model
61
+ qnabot = bot("qna-over-docs", model="text-davinci-003")
62
+ ```
63
+
64
+ ## Changing the bot's prompt
65
+
66
+ You can change the bots promnpt to customize it to your needs. In the `qna-over-docs` type of bot you will need to pass 2 variables for the `context` (knwoledge searched from the index) and the `question` (the human question).
67
+
68
+ ```python
69
+ from megabots import bot
70
+
71
+ prompt = """
72
+ Use the following pieces of context to answer the question at the end.
73
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
74
+ Answer in the style of Tony Stark.
75
+
76
+ {context}
77
+
78
+ Question: {question}
79
+ Helpful humorous answer:"""
80
+
81
+ qnabot = bot("qna-over-docs", index="./index.pkl", prompt=prompt)
82
+
83
+ qnabot.ask("what was the first roster of the avengers?")
84
+ ```
85
+
86
+ ## Working with memory
87
+
88
+ You can easily add memory to your `bot` using the `memory` parameter. It accepts a string with the type of the memory to be used. This defaults to some sane dafaults.
89
+ Should you need more configuration, you can use the `memory` function and pass the type of memory and the configuration you need.
90
+
91
+ ```python
92
+ from megabots import bot
93
+
94
+ qnabot = bot("qna-over-docs", index="./index.pkl", memory="conversation-buffer")
95
+
96
+ print(qnabot.ask("who is iron man?"))
97
+ print(qnabot.ask("was he in the first roster?"))
98
+ # Bot should understand who "he" refers to.
99
+ ```
100
+
101
+ Or using the `memory`factory function
102
+
103
+ ```python
104
+ from megabots import bot, memory
105
+
106
+ mem("conversation-buffer-window", k=5)
107
+
108
+ qnabot = bot("qna-over-docs", index="./index.pkl", memory=mem)
109
+
110
+ print(qnabot.ask("who is iron man?"))
111
+ print(qnabot.ask("was he in the first roster?"))
112
+ ```
113
+
114
+ NOTE: For the `qna-over-docs` bot, when using memory and passing your custom prompt, it is important to remember to pass one more variable to your custom prompt to facilitate for chat history. The variable name is `history`.
115
+
116
+ ```python
117
+ from megabots import bot
118
+
119
+ prompt = """
120
+ Use the following pieces of context to answer the question at the end.
121
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
122
+
123
+ {context}
124
+
125
+ {history}
126
+ Human: {question}
127
+ AI:"""
128
+
129
+ qnabot = bot("qna-over-docs", prompt=prompt, index="./index.pkl", memory="conversation-buffer")
130
+
131
+ print(qnabot.ask("who is iron man?"))
132
+ print(qnabot.ask("was he in the first roster?"))
133
+ ```
134
+
135
+ ## Using Megabots with Milvus (more DBs comming soon)
136
+
137
+ Megabots `bot` can also use Milvus as a backend for its search engine. You can find an example of how to do it below.
138
+
139
+ In order to run Milvus you need to follow [this guide](https://milvus.io/docs/example_code.md) to download a docker compose file and run it.
140
+ The command is:
141
+
142
+ ```bash
143
+ wget https://raw.githubusercontent.com/milvus-io/pymilvus/v2.2.7/examples/hello_milvus.py
144
+ ```
145
+
146
+ You can then [install Attu](https://milvus.io/docs/attu_install-docker.md) as a management tool for Milvus
147
+
148
+ ```python
149
+ from megabots import bot
150
+
151
+ # Attach a vectorstore by passing the name of the database. Default port for milvus is 19530 and default host is localhost
152
+ # Point it to your files directory so that it can index the files and add them to the vectorstore
153
+ bot = bot("qna-over-docs", index="./examples/files/", vectorstore="milvus")
154
+
155
+ bot.ask("what was the first roster of the avengers?")
156
+ ```
157
+
158
+ Or use the `vectorstore` factory function for more customisation
159
+
160
+ ```python
161
+
162
+ from megabots import bot, vectorstore
163
+
164
+ milvus = vectorstore("milvus", host="localhost", port=19530)
165
+
166
+ bot = bot("qna-over-docs", index="./examples/files/", vectorstore=milvus)
167
+ ```
168
+
169
+ ## Exposing an API with FastAPI
170
+
171
+ You can also create a FastAPI app that will expose the bot as an API using the create_app function.
172
+ Assuming you file is called `main.py` run `uvicorn main:app --reload` to run the API locally.
173
+ You should then be able to visit `http://localhost:8000/docs` to see the API documentation.
174
+
175
+ ```python
176
+ from megabots import bot, create_api
177
+
178
+ app = create_app(bot("qna-over-docs"))
179
+ ```
180
+
181
+ ## Exposing a Gradio chat-like interface
182
+
183
+ You can expose a gradio UI for the bot using `create_interface` function.
184
+ Assuming your file is called `ui.py` run `gradio qnabot/ui.py` to run the UI locally.
185
+ You should then be able to visit `http://127.0.0.1:7860` to see the API documentation.
186
+
187
+ ```python
188
+ from megabots import bot, create_interface
189
+
190
+ demo = create_interface(bot("qna-over-docs"))
191
+ ```
192
+
193
+ ## Customising bot
194
+
195
+ The `bot` function should serve as the starting point for creating and customising your bot. Below is a list of the available arguments in `bot`.
196
+
197
+ | Argument | Description |
198
+ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
199
+ | task | The type of bot to create. Available options: `qna-over-docs`. More comming soon |
200
+ | index | Specifies the index to use for the bot. It can either be a saved index file (e.g., `index.pkl`) or a directory of documents (e.g., `./index`). In the case of the directory the index will be automatically created. If no index is specified `bot` will look for `index.pkl` or `./index` |
201
+ | model | The name of the model to use for the bot. You can specify a different model by providing its name, like "text-davinci-003". Supported models: `gpt-3.5-turbo` (default),`text-davinci-003` More comming soon. |
202
+ | prompt | A string template for the prompt, which defines the format of the question and context passed to the model. The template should include placeholder variables like so: `context`, `{question}` and in the case of using memory `history`. |
203
+ | memory | The type of memory to be used by the bot. Can be a string with the type of the memory or you can use `memory` factory function. Supported memories: `conversation-buffer`, `conversation-buffer-window` |
204
+ | vectorstore | The vectorstore to be used for the index. Can be a string with the name of the databse or you can use `vectorstore` factory function. Supported DBs: `milvus`. |
205
+
206
+ | sources | When `sources` is `True` the bot will also include sources in the response. A known [issue](https://github.com/hwchase17/langchain/issues/2858) exists, where if you pass a custom prompt with sources the code breaks. |
207
+
208
+ ## How QnA bot works
209
+
210
+ Large language models (LLMs) are powerful, but they can't answer questions about documents they haven't seen. If you want to use an LLM to answer questions about documents it was not trained on, you have to give it information about those documents. To solve this, we use "retrieval augmented generation."
211
+
212
+ In simple terms, when you have a question, you first search for relevant documents. Then, you give the documents and the question to the language model to generate an answer. To make this work, you need your documents in a searchable format (an index). This process involves two main steps: (1) preparing your documents for easy querying, and (2) using the retrieval augmented generation method.
213
+
214
+ `qna-over-docs` uses FAISS to create an index of documents and GPT to generate answers.
215
+
216
+ ## How to contribute?
217
+
218
+ We welcome any suggestions, problem reports, and contributions!
219
+ For any changes you would like to make to this project, we invite you to submit an [issue](https://github.com/momegas/megabots/issues).
220
+
221
+ For more information, see [`CONTRIBUTING`](https://github.com/momegas/megabots/blob/main/CONTRIBUTING.md) instructions.
megabots/memory.py CHANGED
@@ -40,6 +40,6 @@ def memory(
40
  cl = SUPPORTED_MEMORY[name]["impl"]
41
 
42
  if name == "conversation-buffer-window":
43
- return cl(k=k)
44
 
45
  return SUPPORTED_MEMORY[name]["impl"]()
 
40
  cl = SUPPORTED_MEMORY[name]["impl"]
41
 
42
  if name == "conversation-buffer-window":
43
+ return cl(k=k or SUPPORTED_MEMORY[name]["default"]["k"])
44
 
45
  return SUPPORTED_MEMORY[name]["impl"]()
megabots/utils.py CHANGED
@@ -14,19 +14,20 @@ def create_api(bot: Bot):
14
  return app
15
 
16
 
17
- def create_interface(bot_instance: Bot, examples: list[list[str]] = []):
18
  with gr.Blocks() as interface:
19
- chatbot = gr.Chatbot([], elem_id="chatbot").style(height=750)
 
20
  msg = gr.Textbox(
21
  show_label=False,
22
- placeholder="Enter text and press enter, or upload an image",
23
  ).style(container=False)
24
- clear = gr.Button("Clear")
25
 
26
  def user(user_message, history):
27
  return "", history + [[user_message, None]]
28
 
29
  def bot(history):
 
30
  response = bot_instance.ask(history[-1][0])
31
  history[-1][1] = response
32
  return history
@@ -34,6 +35,5 @@ def create_interface(bot_instance: Bot, examples: list[list[str]] = []):
34
  msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
35
  bot, chatbot, chatbot
36
  )
37
- clear.click(lambda: None, None, chatbot, queue=False)
38
 
39
  return interface
 
14
  return app
15
 
16
 
17
+ def create_interface(bot_instance: Bot, markdown: str = ""):
18
  with gr.Blocks() as interface:
19
+ gr.Markdown(markdown)
20
+ chatbot = gr.Chatbot([], elem_id="chatbot").style(height=450)
21
  msg = gr.Textbox(
22
  show_label=False,
23
+ placeholder="Enter text and press enter",
24
  ).style(container=False)
 
25
 
26
  def user(user_message, history):
27
  return "", history + [[user_message, None]]
28
 
29
  def bot(history):
30
+ print("im here")
31
  response = bot_instance.ask(history[-1][0])
32
  history[-1][1] = response
33
  return history
 
35
  msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
36
  bot, chatbot, chatbot
37
  )
 
38
 
39
  return interface