Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f7dd65a3de | |||
| d8cdbe0041 | |||
| 2b8b6d3ea9 | |||
| 936c7e389f | |||
| 6864b4207b | |||
| 98eb5b54be | |||
| 3332e6e236 | |||
| 0533da72d7 | |||
| a1de238716 | |||
| f0d112254b | |||
| 830a7397ef | |||
| 5428765329 | |||
| 23c912f2b7 | |||
| 9c4b023297 | |||
| 53037b5ed8 | |||
| e2546a653d | |||
| 4b8cada873 | |||
| fa3ca1d08a | |||
| 8dd5cb9602 | |||
| a054f7be9c | |||
| df314dc6d1 | |||
| 930280f4ce | |||
| 5022c1ae29 | |||
| 6ced756a6b | |||
| b17268db50 | |||
| 476da37009 | |||
| 455f059c6f | |||
| 5255a37c93 | |||
| 68dc274f72 | |||
| 30228f7f8e | |||
| e15ef79ca9 | |||
| bc012a7518 | |||
| 3b4409cfad | |||
| d3726134b2 | |||
| 5acb7f1c55 | |||
| 81336668b3 | |||
| 35c2b83015 | |||
| cc1ee1deaa |
@@ -76,7 +76,6 @@ docs/_build/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
*.yaml
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
|
||||
@@ -1,70 +1,68 @@
|
||||
# embedchain
|
||||
<p align="center">
|
||||
<img src="docs/logo/dark.svg" width="400px" alt="Embedchain Logo">
|
||||
</p>
|
||||
|
||||
<a href="https://runacap.com/ross-index/q3-2023/" target="_blank" rel="noopener"><img style="width: 260px; height: 56px" src="https://runacap.com/wp-content/uploads/2023/10/ROSS_badge_black_Q3_2023.svg" alt="ROSS Index - Fastest Growing Open-Source Startups in Q3 2023 | Runa Capital" width="260" height="56"/></a>
|
||||
<p align="center">
|
||||
<a href="https://runacap.com/ross-index/q3-2023/" target="_blank" rel="noopener"><img style="width: 260px; height: 56px" src="https://runacap.com/wp-content/uploads/2023/10/ROSS_badge_black_Q3_2023.svg" alt="ROSS Index - Fastest Growing Open-Source Startups in Q3 2023 | Runa Capital" width="260" height="56"/></a>
|
||||
</p>
|
||||
|
||||
[](https://pypi.org/project/embedchain/)
|
||||
[](https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw)
|
||||
[](https://discord.gg/CUU9FPhRNt)
|
||||
[](https://twitter.com/embedchain)
|
||||
[](https://embedchain.substack.com/)
|
||||
[](https://colab.research.google.com/drive/138lMWhENGeEu7Q1-6lNbNTHGLZXBBz_B?usp=sharing)
|
||||
[](https://codecov.io/gh/embedchain/embedchain)
|
||||
<p align="center">
|
||||
<a href="https://pypi.org/project/embedchain/">
|
||||
<img src="https://img.shields.io/pypi/v/embedchain" alt="PyPI">
|
||||
</a>
|
||||
<a href="https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw">
|
||||
<img src="https://img.shields.io/badge/slack-embedchain-brightgreen.svg?logo=slack" alt="Slack">
|
||||
</a>
|
||||
<a href="https://discord.gg/CUU9FPhRNt">
|
||||
<img src="https://dcbadge.vercel.app/api/server/6PzXDgEjG5?style=flat" alt="Discord">
|
||||
</a>
|
||||
<a href="https://twitter.com/embedchain">
|
||||
<img src="https://img.shields.io/twitter/follow/embedchain" alt="Twitter">
|
||||
</a>
|
||||
<a href="https://embedchain.substack.com/">
|
||||
<img src="https://img.shields.io/badge/Substack-%23006f5c.svg?logo=substack" alt="Substack">
|
||||
</a>
|
||||
<a href="https://colab.research.google.com/drive/138lMWhENGeEu7Q1-6lNbNTHGLZXBBz_B?usp=sharing">
|
||||
<img src="https://camo.githubusercontent.com/84f0493939e0c4de4e6dbe113251b4bfb5353e57134ffd9fcab6b8714514d4d1/68747470733a2f2f636f6c61622e72657365617263682e676f6f676c652e636f6d2f6173736574732f636f6c61622d62616467652e737667" alt="Open in Colab">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/embedchain/embedchain">
|
||||
<img src="https://codecov.io/gh/embedchain/embedchain/graph/badge.svg?token=EMRRHZXW1Q" alt="codecov">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
Embedchain is a Data Platform for LLMs - load, index, retrieve, and sync any unstructured data. Using embedchain, you can easily create LLM powered apps over any data. If you want a javascript version, check out [embedchain-js](https://github.com/embedchain/embedchain/tree/main/embedchain-js)
|
||||
<hr />
|
||||
|
||||
## Community
|
||||
|
||||
* Join embedchain community on slack by accepting [this invite](https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw)
|
||||
|
||||
## 🤝 Schedule a 1-on-1 Session
|
||||
|
||||
Book a [1-on-1 Session](https://cal.com/taranjeetio/ec) with Taranjeet, the founder, to discuss any issues, provide feedback, or explore how we can improve Embedchain for you.
|
||||
## What is Embedchain?
|
||||
Embedchain is a Data Platform for Large Language Models (LLMs). Seamlessly load, index, retrieve, and sync unstructured data to build dynamic, LLM-powered applications. Check out [embedchain-js](https://github.com/embedchain/embedchain/tree/main/embedchain-js) for a JavaScript implementation.
|
||||
|
||||
## 🔧 Quick install
|
||||
|
||||
### Python API
|
||||
```bash
|
||||
pip install --upgrade embedchain
|
||||
```
|
||||
|
||||
## 🔍 Demo
|
||||
### REST API
|
||||
You can also run Embedchain as a REST API server using the following command:
|
||||
|
||||
Try out embedchain in your browser:
|
||||
```bash
|
||||
docker run --name embedchain -p 8080:8080 embedchain/rest-api:latest
|
||||
```
|
||||
|
||||
[](https://colab.research.google.com/drive/17ON1LPonnXAtLaZEebnOktstB_1cJJmh?usp=sharing)
|
||||
Then, navigate to http://0.0.0.0:8080/docs to interact with the API.
|
||||
|
||||
## 📖 Documentation
|
||||
## 🔍 Usage and Demo
|
||||
|
||||
The documentation for embedchain can be found at [docs.embedchain.ai](https://docs.embedchain.ai).
|
||||
<!-- Demo GIF or Image -->
|
||||
<p align="center">
|
||||
<img src="docs/images/cover.gif" width="900px" alt="Embedchain Demo">
|
||||
</p>
|
||||
|
||||
## 💻 Usage
|
||||
|
||||
Embedchain empowers you to create ChatGPT like apps, on your own dynamic dataset.
|
||||
|
||||
### Data types supported
|
||||
|
||||
* Youtube video
|
||||
* PDF file
|
||||
* CSV file
|
||||
* Web page
|
||||
* MDX file
|
||||
* XML file
|
||||
* Sitemap
|
||||
* Doc file
|
||||
* Notion
|
||||
* JSON file
|
||||
* OpenAPI specs
|
||||
* Code docs website
|
||||
* Unstructured file loader and many more
|
||||
|
||||
You can find the full list of data types on [our documentation](https://docs.embedchain.ai/data-sources/).
|
||||
|
||||
### Queries
|
||||
|
||||
For example, you can use Embedchain to create an Elon Musk bot using the following code:
|
||||
For example, you can create an Elon Musk bot using the following code:
|
||||
|
||||
```python
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# Create a bot instance
|
||||
os.environ["OPENAI_API_KEY"] = "YOUR API KEY"
|
||||
@@ -78,37 +76,40 @@ elon_bot.add("https://www.youtube.com/watch?v=RcYjXbSJBN8")
|
||||
# Query the bot
|
||||
elon_bot.query("How many companies does Elon Musk run and name those?")
|
||||
# Answer: Elon Musk currently runs several companies. As of my knowledge, he is the CEO and lead designer of SpaceX, the CEO and product architect of Tesla, Inc., the CEO and founder of Neuralink, and the CEO and founder of The Boring Company. However, please note that this information may change over time, so it's always good to verify the latest updates.
|
||||
|
||||
# (Optional): Deploy app to Embedchain Platform
|
||||
app.deploy()
|
||||
# 🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/
|
||||
# ec-xxxxxx
|
||||
|
||||
# 🛠️ Creating pipeline on the platform...
|
||||
# 🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/xxxxx
|
||||
|
||||
# 🛠️ Adding data to your pipeline...
|
||||
# ✅ Data of type: web_page, value: https://www.forbes.com/profile/elon-musk added successfully.
|
||||
```
|
||||
|
||||
## Examples
|
||||
You can also try it in your browser with Google Colab:
|
||||
|
||||
| LLM | Google Colab | Replit |
|
||||
|--------------|---------------|----------|
|
||||
| OpenAI | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/openai.ipynb) | [](https://replit.com/@taranjeetio/openai#main.py) |
|
||||
| Anthropic | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/anthropic.ipynb) | [](https://replit.com/@taranjeetio/anthropic#main.py) |
|
||||
| Azure OpenAI | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/azure-openai.ipynb) | [](https://replit.com/@taranjeetio/azureopenai#main.py) |
|
||||
| VertexAI | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/vertex_ai.ipynb) | [](https://replit.com/@taranjeetio/vertexai#main.py) |
|
||||
| Cohere | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/cohere.ipynb) | [](https://replit.com/@taranjeetio/cohere#main.py) |
|
||||
| Hugging Face | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/hugging_face_hub.ipynb) | [](https://replit.com/@taranjeetio/huggingface#main.py) |
|
||||
| JinaChat | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/jina.ipynb) | [](https://replit.com/@taranjeetio/jina#main.py) |
|
||||
| GPT4All | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/gpt4all.ipynb) | [](https://replit.com/@taranjeetio/gpt4all#main.py) |
|
||||
| Llama2 | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/llama2.ipynb) | [](https://replit.com/@taranjeetio/llama2#main.py) |
|
||||
[](https://colab.research.google.com/drive/17ON1LPonnXAtLaZEebnOktstB_1cJJmh?usp=sharing)
|
||||
|
||||
| Embedding model | Google Colab | Replit |
|
||||
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||||
| OpenAI | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/openai.ipynb) | [](https://replit.com/@taranjeetio/openai#main.py) |
|
||||
| VertexAI | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/vertex_ai.ipynb) | [](https://replit.com/@taranjeetio/vertexai#main.py) |
|
||||
| GPT4All | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/gpt4all.ipynb) | [](https://replit.com/@taranjeetio/gpt4all#main.py) |
|
||||
| Hugging Face | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/hugging_face_hub.ipynb) | [](https://replit.com/@taranjeetio/huggingface#main.py) |
|
||||
## 📖 Documentation
|
||||
Comprehensive guides and API documentation are available to help you get the most out of Embedchain:
|
||||
|
||||
| Vector DB | Google Colab | Replit |
|
||||
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| ChromaDB | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/chromadb.ipynb) | [](https://replit.com/@taranjeetio/chromadb#main.py) |
|
||||
| Elasticsearch | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/elasticsearch.ipynb) | [](https://replit.com/@taranjeetio/elasticsearchdb#main.py) |
|
||||
| Opensearch | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/opensearch.ipynb) | [](https://replit.com/@taranjeetio/opensearchdb#main.py) |
|
||||
| Pinecone | [](https://colab.research.google.com/github/embedchain/embedchain/blob/main/notebooks/pinecone.ipynb) | [](https://replit.com/@taranjeetio/pineconedb#main.py) |
|
||||
- [Getting Started](https://docs.embedchain.ai/get-started/quickstart)
|
||||
- [Introduction](https://docs.embedchain.ai/get-started/introduction#what-is-embedchain)
|
||||
- [Examples](https://docs.embedchain.ai/get-started/examples)
|
||||
- [Supported data types](https://docs.embedchain.ai/data-sources/)
|
||||
|
||||
## 🤝 Contributing
|
||||
## 🔗 Join the Community
|
||||
|
||||
Connect with fellow developers and users by joining our [Slack Workspace](https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw). Dive into discussions, ask questions, and share your experiences.
|
||||
|
||||
## 🤝 Schedule a 1-on-1 Session
|
||||
|
||||
Book a [1-on-1 Session](https://cal.com/taranjeetio/ec) with Taranjeet, the founder, to discuss any issues, provide feedback, or explore how we can improve Embedchain for you.
|
||||
|
||||
## 🌐 Contributing
|
||||
|
||||
Contributions are welcome! Please check out the issues on the repository, and feel free to open a pull request.
|
||||
For more information, please see the [contributing guidelines](CONTRIBUTING.md).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
llm:
|
||||
provider: anthropic
|
||||
model: 'claude-instant-1'
|
||||
config:
|
||||
model: 'claude-instant-1'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -4,8 +4,8 @@ app:
|
||||
|
||||
llm:
|
||||
provider: azure_openai
|
||||
model: gpt-35-turbo
|
||||
config:
|
||||
model: gpt-35-turbo
|
||||
deployment_name: your_llm_deployment_name
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
|
||||
@@ -5,8 +5,8 @@ app:
|
||||
|
||||
llm:
|
||||
provider: openai
|
||||
model: 'gpt-3.5-turbo'
|
||||
config:
|
||||
model: 'gpt-3.5-turbo'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
@@ -23,4 +23,4 @@ embedder:
|
||||
provider: openai
|
||||
config:
|
||||
model: 'text-embedding-ada-002'
|
||||
deployment_name: null
|
||||
deployment_name: 'test-deployment'
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
chunker:
|
||||
chunk_size: 100
|
||||
chunk_overlap: 20
|
||||
length_function: 'len'
|
||||
@@ -1,7 +1,7 @@
|
||||
llm:
|
||||
provider: cohere
|
||||
model: large
|
||||
config:
|
||||
model: large
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -2,10 +2,15 @@ app:
|
||||
config:
|
||||
id: 'full-stack-app'
|
||||
|
||||
chunker:
|
||||
chunk_size: 100
|
||||
chunk_overlap: 20
|
||||
length_function: 'len'
|
||||
|
||||
llm:
|
||||
provider: openai
|
||||
model: 'gpt-3.5-turbo'
|
||||
config:
|
||||
model: 'gpt-3.5-turbo'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
llm:
|
||||
provider: gpt4all
|
||||
config:
|
||||
model: 'orca-mini-3b.ggmlv3.q4_0.bin'
|
||||
model: 'orca-mini-3b-gguf2-q4_0.gguf'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
llm:
|
||||
provider: huggingface
|
||||
model: 'google/flan-t5-xxl'
|
||||
config:
|
||||
model: 'google/flan-t5-xxl'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 0.5
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
llm:
|
||||
provider: llama2
|
||||
model: 'a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5'
|
||||
config:
|
||||
model: 'a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 0.5
|
||||
|
||||
@@ -7,8 +7,8 @@ app:
|
||||
|
||||
llm:
|
||||
provider: openai
|
||||
model: 'gpt-3.5-turbo'
|
||||
config:
|
||||
model: 'gpt-3.5-turbo'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -7,7 +7,7 @@ app:
|
||||
llm:
|
||||
provider: gpt4all
|
||||
config:
|
||||
model: 'orca-mini-3b.ggmlv3.q4_0.bin'
|
||||
model: 'orca-mini-3b-gguf2-q4_0.gguf'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
@@ -23,4 +23,4 @@ vectordb:
|
||||
embedder:
|
||||
provider: gpt4all
|
||||
config:
|
||||
deployment_name: null
|
||||
deployment_name: 'test-deployment'
|
||||
|
||||
@@ -13,7 +13,7 @@ vectordb:
|
||||
llm:
|
||||
provider: gpt4all
|
||||
config:
|
||||
model: 'orca-mini-3b.ggmlv3.q4_0.bin'
|
||||
model: 'orca-mini-3b-gguf2-q4_0.gguf'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
llm:
|
||||
provider: vertexai
|
||||
model: 'chat-bison'
|
||||
config:
|
||||
model: 'chat-bison'
|
||||
temperature: 0.5
|
||||
top_p: 0.5
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<Tip>
|
||||
If you can't find the specific data source, please feel free to request through one of the following channels and help us prioritize.
|
||||
<p>If you can't find the specific data source, please feel free to request through one of the following channels and help us prioritize.</p>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Slack" icon="slack" href="https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw" color="#4A154B">
|
||||
@@ -15,4 +14,3 @@ If you can't find the specific data source, please feel free to request through
|
||||
Schedule a call with Embedchain founder
|
||||
</Card>
|
||||
</CardGroup>
|
||||
</Tip>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<Tip>
|
||||
If you can't find the specific LLM you need, no need to fret. We're continuously expanding our support for additional LLMs, and you can help us prioritize by opening an issue on our GitHub or simply reaching out to us on our Slack or Discord community.
|
||||
<p>If you can't find the specific LLM you need, no need to fret. We're continuously expanding our support for additional LLMs, and you can help us prioritize by opening an issue on our GitHub or simply reaching out to us on our Slack or Discord community.</p>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Slack" icon="slack" href="https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw" color="#4A154B">
|
||||
@@ -15,4 +14,3 @@ If you can't find the specific LLM you need, no need to fret. We're continuously
|
||||
Schedule a call with Embedchain founder
|
||||
</Card>
|
||||
</CardGroup>
|
||||
</Tip>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<Tip>
|
||||
If you can't find the specific vector database, please feel free to request through one of the following channels and help us prioritize.
|
||||
|
||||
|
||||
<p>If you can't find the specific vector database, please feel free to request through one of the following channels and help us prioritize.</p>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Slack" icon="slack" href="https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw" color="#4A154B">
|
||||
@@ -15,4 +16,3 @@ If you can't find the specific vector database, please feel free to request thro
|
||||
Schedule a call with Embedchain founder
|
||||
</Card>
|
||||
</CardGroup>
|
||||
</Tip>
|
||||
|
||||
@@ -11,6 +11,11 @@ app:
|
||||
config:
|
||||
id: 'full-stack-app'
|
||||
|
||||
chunker:
|
||||
chunk_size: 100
|
||||
chunk_overlap: 20
|
||||
length_function: 'len'
|
||||
|
||||
llm:
|
||||
provider: openai
|
||||
config:
|
||||
@@ -49,7 +54,11 @@ Alright, let's dive into what each key means in the yaml config above:
|
||||
1. `app` Section:
|
||||
- `config`:
|
||||
- `id` (String): The ID or name of your full-stack application.
|
||||
2. `llm` Section:
|
||||
2. `chunker` Section:
|
||||
- `chunk_size` (Integer): The size of each chunk of text that is sent to the language model.
|
||||
- `chunk_overlap` (Integer): The amount of overlap between each chunk of text.
|
||||
- `length_function` (String): The function used to calculate the length of each chunk of text. In this case, it's set to 'len'. You can also use any function import directly as a string here.
|
||||
3. `llm` Section:
|
||||
- `provider` (String): The provider for the language model, which is set to 'openai'. You can find the full list of llm providers in [our docs](/components/llms).
|
||||
- `model` (String): The specific model being used, 'gpt-3.5-turbo'.
|
||||
- `config`:
|
||||
@@ -59,13 +68,13 @@ Alright, let's dive into what each key means in the yaml config above:
|
||||
- `stream` (Boolean): Controls if the response is streamed back to the user (set to false).
|
||||
- `template` (String): A custom template for the prompt that the model uses to generate responses.
|
||||
- `system_prompt` (String): A system prompt for the model to follow when generating responses, in this case, it's set to the style of William Shakespeare.
|
||||
3. `vectordb` Section:
|
||||
4. `vectordb` Section:
|
||||
- `provider` (String): The provider for the vector database, set to 'chroma'. You can find the full list of vector database providers in [our docs](/components/vector-databases).
|
||||
- `config`:
|
||||
- `collection_name` (String): The initial collection name for the database, set to 'full-stack-app'.
|
||||
- `dir` (String): The directory for the database, set to 'db'.
|
||||
- `allow_reset` (Boolean): Indicates whether resetting the database is allowed, set to true.
|
||||
4. `embedder` Section:
|
||||
5. `embedder` Section:
|
||||
- `provider` (String): The provider for the embedder, set to 'openai'. You can find the full list of embedding model providers in [our docs](/components/embedding-models).
|
||||
- `config`:
|
||||
- `model` (String): The specific model used for text embedding, 'text-embedding-ada-002'.
|
||||
|
||||
@@ -24,7 +24,7 @@ Once you have obtained the key, you can use it like this:
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['OPENAI_API_KEY'] = 'xxx'
|
||||
|
||||
@@ -52,7 +52,7 @@ To use Azure OpenAI embedding model, you have to set some of the azure openai re
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["OPENAI_API_TYPE"] = "azure"
|
||||
os.environ["OPENAI_API_BASE"] = "https://xxx.openai.azure.com/"
|
||||
@@ -90,7 +90,7 @@ GPT4All supports generating high quality embeddings of arbitrary length document
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load embedding model configuration from config.yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -100,7 +100,7 @@ app = App.from_config(yaml_path="config.yaml")
|
||||
llm:
|
||||
provider: gpt4all
|
||||
config:
|
||||
model: 'orca-mini-3b.ggmlv3.q4_0.bin'
|
||||
model: 'orca-mini-3b-gguf2-q4_0.gguf'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
@@ -119,7 +119,7 @@ Hugging Face supports generating embeddings of arbitrary length documents of tex
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load embedding model configuration from config.yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -150,7 +150,7 @@ Embedchain supports Google's VertexAI embeddings model through a simple interfac
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load embedding model configuration from config.yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
|
||||
@@ -26,7 +26,7 @@ Once you have obtained the key, you can use it like this:
|
||||
|
||||
```python
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['OPENAI_API_KEY'] = 'xxx'
|
||||
|
||||
@@ -41,7 +41,7 @@ If you are looking to configure the different parameters of the LLM, you can do
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['OPENAI_API_KEY'] = 'xxx'
|
||||
|
||||
@@ -71,7 +71,7 @@ To use Azure OpenAI model, you have to set some of the azure openai related envi
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["OPENAI_API_TYPE"] = "azure"
|
||||
os.environ["OPENAI_API_BASE"] = "https://xxx.openai.azure.com/"
|
||||
@@ -110,7 +110,7 @@ To use anthropic's model, please set the `ANTHROPIC_API_KEY` which you find on t
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["ANTHROPIC_API_KEY"] = "xxx"
|
||||
|
||||
@@ -147,7 +147,7 @@ Once you have the API key, you are all set to use it with Embedchain.
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["COHERE_API_KEY"] = "xxx"
|
||||
|
||||
@@ -180,7 +180,7 @@ GPT4all is a free-to-use, locally running, privacy-aware chatbot. No GPU or inte
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load llm configuration from config.yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -190,7 +190,7 @@ app = App.from_config(yaml_path="config.yaml")
|
||||
llm:
|
||||
provider: gpt4all
|
||||
config:
|
||||
model: 'orca-mini-3b.ggmlv3.q4_0.bin'
|
||||
model: 'orca-mini-3b-gguf2-q4_0.gguf'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
@@ -212,7 +212,7 @@ Once you have the key, load the app using the config yaml file:
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["JINACHAT_API_KEY"] = "xxx"
|
||||
# load llm configuration from config.yaml file
|
||||
@@ -248,7 +248,7 @@ Once you have the token, load the app using the config yaml file:
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["HUGGINGFACE_ACCESS_TOKEN"] = "xxx"
|
||||
|
||||
@@ -278,7 +278,7 @@ Once you have the token, load the app using the config yaml file:
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["REPLICATE_API_TOKEN"] = "xxx"
|
||||
|
||||
@@ -305,7 +305,7 @@ Setup Google Cloud Platform application credentials by following the instruction
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load llm configuration from config.yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
|
||||
@@ -22,7 +22,7 @@ Utilizing a vector database alongside Embedchain is a seamless process. All you
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load chroma configuration from yaml file
|
||||
app = App.from_config(yaml_path="config1.yaml")
|
||||
@@ -61,7 +61,7 @@ pip install --upgrade 'embedchain[elasticsearch]'
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load elasticsearch configuration from yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -89,7 +89,7 @@ pip install --upgrade 'embedchain[opensearch]'
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load opensearch configuration from yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -125,7 +125,7 @@ Set the Zilliz environment variables `ZILLIZ_CLOUD_URI` and `ZILLIZ_CLOUD_TOKEN`
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['ZILLIZ_CLOUD_URI'] = 'https://xxx.zillizcloud.com'
|
||||
os.environ['ZILLIZ_CLOUD_TOKEN'] = 'xxx'
|
||||
@@ -138,7 +138,7 @@ app = App.from_config(yaml_path="config.yaml")
|
||||
vectordb:
|
||||
provider: zilliz
|
||||
config:
|
||||
collection_name: 'zilliz-app'
|
||||
collection_name: 'zilliz_app'
|
||||
uri: https://xxxx.api.gcp-region.zillizcloud.com
|
||||
token: xxx
|
||||
vector_dim: 1536
|
||||
@@ -164,7 +164,7 @@ In order to use Pinecone as vector database, set the environment variables `PINE
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load pinecone configuration from yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -187,7 +187,7 @@ In order to use Qdrant as a vector database, set the environment variables `QDRA
|
||||
|
||||
<CodeGroup>
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load qdrant configuration from yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
@@ -207,7 +207,7 @@ In order to use Weaviate as a vector database, set the environment variables `WE
|
||||
|
||||
<CodeGroup>
|
||||
```python main.py
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# load weaviate configuration from yaml file
|
||||
app = App.from_config(yaml_path="config.yaml")
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '📊 CSV'
|
||||
To add any csv file, use the data_type as `csv`. `csv` allows remote urls and conventional file paths. Headers are included for each line, so if you have an `age` column, `18` will be added as `age: 18`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
app.add('https://people.sc.fsu.edu/~jburkardt/data/csv/airtravel.csv', data_type="csv")
|
||||
|
||||
@@ -35,7 +35,7 @@ Default behavior is to create a persistent vector db in the directory **./db**.
|
||||
Create a local index:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
naval_chat_bot = App()
|
||||
naval_chat_bot.add("https://www.youtube.com/watch?v=3qHkcs3kG44")
|
||||
@@ -45,7 +45,7 @@ naval_chat_bot.add("https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Alma
|
||||
You can reuse the local index with the same code, but without adding new documents:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
naval_chat_bot = App()
|
||||
print(naval_chat_bot.query("What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?"))
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '📚🌐 Code documentation'
|
||||
To add any code documentation website as a loader, use the data_type as `docs_site`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
app.add("https://docs.embedchain.ai/", data_type="docs_site")
|
||||
|
||||
@@ -7,7 +7,7 @@ title: '📄 Docx file'
|
||||
To add any doc/docx file, use the data_type as `docx`. `docx` allows remote urls and conventional file paths. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
app.add('https://example.com/content/intro.docx', data_type="docx")
|
||||
|
||||
@@ -2,8 +2,25 @@
|
||||
title: '📃 JSON'
|
||||
---
|
||||
|
||||
To add any json file, use the data_type as `json`. `json` allows remote urls and conventional file paths. Headers are included for each line, so if you have an `age` column, `18` will be added as `age: 18`. Eg:
|
||||
To add any json file, use the data_type as `json`. Headers are included for each line, so if you have an `age` column, `18` will be added as `age: 18`. Eg:
|
||||
|
||||
Here are the supported sources for loading `json`:
|
||||
```
|
||||
1. URL - valid url to json file that ends with ".json" extension.
|
||||
2. Local file - valid url to local json file that ends with ".json" extension.
|
||||
3. String - valid json string (e.g. - app.add('{"foo": "bar"}'))
|
||||
```
|
||||
|
||||
If you would like to add other data structures (e.x. list, dict etc.), do:
|
||||
```python
|
||||
import json
|
||||
a = {"foo": "bar"}
|
||||
valid_json_string_data = json.dumps(a, indent=0)
|
||||
|
||||
b = [{"foo": "bar"}]
|
||||
valid_json_string_data = json.dumps(b, indent=0)
|
||||
```
|
||||
Example:
|
||||
```python
|
||||
import os
|
||||
|
||||
@@ -25,8 +42,8 @@ response = app.query("What is the net worth of Elon Musk as of October 2023?")
|
||||
print(response)
|
||||
"As of October 2023, Elon Musk's net worth is $255.2 billion."
|
||||
```
|
||||
|
||||
```temp.json
|
||||
temp.json
|
||||
```json
|
||||
{
|
||||
"question": "What is your net worth, Elon Musk?",
|
||||
"answer": "As of October 2023, Elon Musk's net worth is $255.2 billion, making him one of the wealthiest individuals in the world."
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '📝 Mdx file'
|
||||
To add any `.mdx` file to your app, use the data_type (first argument to `.add()` method) as `mdx`. Note that this supports support mdx file present on machine, so this should be a file path. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
app.add('path/to/file.mdx', data_type='mdx')
|
||||
|
||||
@@ -8,7 +8,7 @@ To load a notion page, use the data_type as `notion`. Since it is hard to automa
|
||||
The next argument must **end** with the `notion page id`. The id is a 32-character string. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '📰 PDF file'
|
||||
To add any pdf file, use the data_type as `pdf_file`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '❓💬 Queston and answer pair'
|
||||
QnA pair is a local data type. To supply your own QnA pair, use the data_type as `qna_pair` and enter a tuple. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '🗺️ Sitemap'
|
||||
Add all web pages from an xml-sitemap. Filters non-text files. Use the data_type as `sitemap`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ title: '📝 Text'
|
||||
Text is a local data type. To supply your own text, use the data_type as `text` and enter a string. The text is not processed, this can be very versatile. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ title: '🌐📄 Web page'
|
||||
To add any web page, use the data_type as `web_page`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ title: '🧾 XML file'
|
||||
To add any xml file, use the data_type as `xml`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ title: '🎥📺 Youtube video'
|
||||
To add any youtube video to your app, use the data_type (first argument to `.add()` method) as `youtube_video`. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
app.add('a_valid_youtube_url_here', data_type='youtube_video')
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
---
|
||||
title: '🌍 API Server'
|
||||
---
|
||||
|
||||
The API server example can be found [here](https://github.com/embedchain/embedchain/tree/main/examples/api_server).
|
||||
|
||||
It is a Flask based server that integrates the `embedchain` package, offering endpoints to add, query, and chat to engage in conversations with a chatbot using JSON requests.
|
||||
|
||||
### 🐳 Docker Setup
|
||||
|
||||
- Open variables.env, and edit it to add your 🔑 `OPENAI_API_KEY`.
|
||||
- To setup your api server using docker, run the following command inside this folder using your terminal.
|
||||
|
||||
```bash
|
||||
docker-compose up --build
|
||||
```
|
||||
|
||||
📝 Note: The build command might take a while to install all the packages depending on your system resources.
|
||||
|
||||
### 🚀 Usage Instructions
|
||||
|
||||
- Your api server is running on [http://localhost:5000/](http://localhost:5000/)
|
||||
- To use the api server, make an api call to the endpoints `/add`, `/query` and `/chat` using the json formats discussed below.
|
||||
- To add data sources to the bot (/add):
|
||||
```json
|
||||
// Request
|
||||
{
|
||||
"data_type": "your_data_type_here",
|
||||
"url_or_text": "your_url_or_text_here"
|
||||
}
|
||||
|
||||
// Response
|
||||
{
|
||||
"data": "Added data_type: url_or_text"
|
||||
}
|
||||
```
|
||||
- To ask queries from the bot (/query):
|
||||
```json
|
||||
// Request
|
||||
{
|
||||
"question": "your_question_here"
|
||||
}
|
||||
|
||||
// Response
|
||||
{
|
||||
"data": "your_answer_here"
|
||||
}
|
||||
```
|
||||
- To chat with the bot (/chat):
|
||||
```json
|
||||
// Request
|
||||
{
|
||||
"question": "your_question_here"
|
||||
}
|
||||
|
||||
// Response
|
||||
{
|
||||
"data": "your_answer_here"
|
||||
}
|
||||
```
|
||||
|
||||
### 📡 Curl Call Formats
|
||||
|
||||
- To add data sources to the bot (/add):
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"data_type": "your_data_type_here",
|
||||
"url_or_text": "your_url_or_text_here"
|
||||
}' \
|
||||
http://localhost:5000/add
|
||||
```
|
||||
- To ask queries from the bot (/query):
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"question": "your_question_here"
|
||||
}' \
|
||||
http://localhost:5000/query
|
||||
```
|
||||
- To chat with the bot (/chat):
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"question": "your_question_here"
|
||||
}' \
|
||||
http://localhost:5000/chat
|
||||
```
|
||||
|
||||
🎉 Happy Chatting! 🎉
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: '🤖 Discord Bot'
|
||||
title: "🤖 Discord Bot"
|
||||
---
|
||||
|
||||
### 🔑 Keys Setup
|
||||
@@ -12,9 +12,11 @@ title: '🤖 Discord Bot'
|
||||
- On the left sidebar, click on `OAuth2` and go to `General`.
|
||||
- Set `Authorization Method` to `In-app Authorization`. Under `Scopes` select `bot`.
|
||||
- Under `Bot Permissions` allow the following and then click on `Save Changes`.
|
||||
|
||||
```text
|
||||
Send Messages (under Text Permissions)
|
||||
```
|
||||
|
||||
- Now under `OAuth2` and go to `URL Generator`. Under `Scopes` select `bot`.
|
||||
- Under `Bot Permissions` set the same permissions as above.
|
||||
- Now scroll down and copy the `Generated URL`. Paste it in a browser window and select the Server where you want to add the bot.
|
||||
@@ -23,40 +25,46 @@ Send Messages (under Text Permissions)
|
||||
|
||||
### Take the bot online
|
||||
|
||||
1. Install embedchain python package:
|
||||
<Tabs>
|
||||
<Tab title="docker">
|
||||
```bash
|
||||
docker run --name discord-bot -e OPENAI_API_KEY=sk-xxx -e DISCORD_BOT_TOKEN=xxx -p 8080:8080 embedchain/discord-bot:latest
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="python">
|
||||
```bash
|
||||
pip install --upgrade "embedchain[discord]"
|
||||
|
||||
```bash
|
||||
pip install --upgrade "embedchain[discord]"
|
||||
```
|
||||
python -m embedchain.bots.discord
|
||||
|
||||
2. Launch your Discord bot:
|
||||
|
||||
|
||||
```bash
|
||||
python -m embedchain.bots.discord
|
||||
```
|
||||
|
||||
If you prefer to see the question and not only the answer, run it with
|
||||
|
||||
```bash
|
||||
python -m embedchain.bots.discord --include-question
|
||||
```
|
||||
# or if you prefer to see the question and not only the answer, run it with
|
||||
python -m embedchain.bots.discord --include-question
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### 🚀 Usage Instructions
|
||||
|
||||
- Go to the server where you have added your bot.
|
||||

|
||||
- You can add data sources to the bot using the slash command:
|
||||
|
||||
```text
|
||||
/add <data_type> <url_or_text>
|
||||
/ec add <data_type> <url_or_text>
|
||||
```
|
||||
|
||||
- You can ask your queries from the bot using the slash command:
|
||||
|
||||
```text
|
||||
/query <question>
|
||||
/ec query <question>
|
||||
```
|
||||
|
||||
- You can chat with the bot using the slash command:
|
||||
|
||||
```text
|
||||
/chat <question>
|
||||
/ec chat <question>
|
||||
```
|
||||
|
||||
📝 Note: To use the bot privately, you can message the bot directly by right clicking the bot and selecting `Message`.
|
||||
|
||||
🎉 Happy Chatting! 🎉
|
||||
|
||||
@@ -8,14 +8,45 @@ This guide will help you setup the full stack app on your local machine.
|
||||
|
||||
### 🐳 Docker Setup
|
||||
|
||||
- To setup full stack app using docker, run the following command inside this folder using your terminal.
|
||||
- Create a `docker-compose.yml` file and paste the following code in it.
|
||||
|
||||
```yaml
|
||||
version: "3.9"
|
||||
|
||||
services:
|
||||
backend:
|
||||
container_name: embedchain-backend
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: backend
|
||||
dockerfile: Dockerfile
|
||||
image: embedchain/backend
|
||||
ports:
|
||||
- "8000:8000"
|
||||
|
||||
frontend:
|
||||
container_name: embedchain-frontend
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: frontend
|
||||
dockerfile: Dockerfile
|
||||
image: embedchain/frontend
|
||||
ports:
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
- "backend"
|
||||
```
|
||||
|
||||
- Run the following command,
|
||||
|
||||
```bash
|
||||
docker-compose up --build
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
📝 Note: The build command might take a while to install all the packages depending on your system resources.
|
||||
|
||||

|
||||
|
||||
### 🚀 Usage Instructions
|
||||
|
||||
- Go to [http://localhost:3000/](http://localhost:3000/) in your browser to view the dashboard.
|
||||
|
||||
|
Before Width: | Height: | Size: 70 KiB After Width: | Height: | Size: 5.0 KiB |
@@ -3,13 +3,45 @@ title: ❓ FAQs
|
||||
description: 'Collections of all the frequently asked questions'
|
||||
---
|
||||
|
||||
#### Does Embedchain support OpenAI's Assistant APIs?
|
||||
|
||||
Yes, it does. Please refer to the [OpenAI Assistant docs page](/get-started/openai-assistant).
|
||||
|
||||
#### How to use `gpt-4-turbo` model released on OpenAI DevDay?
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['OPENAI_API_KEY'] = 'xxx'
|
||||
|
||||
# load llm configuration from gpt4_turbo.yaml file
|
||||
app = App.from_config(yaml_path="gpt4_turbo.yaml")
|
||||
```
|
||||
|
||||
```yaml gpt4_turbo.yaml
|
||||
llm:
|
||||
provider: openai
|
||||
config:
|
||||
model: 'gpt-4-turbo'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
stream: false
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
#### How to use GPT-4 as the LLM model?
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['OPENAI_API_KEY'] = 'xxx'
|
||||
|
||||
@@ -36,7 +68,7 @@ llm:
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ['OPENAI_API_KEY'] = 'xxx'
|
||||
|
||||
@@ -48,7 +80,7 @@ app = App.from_config(yaml_path="opensource.yaml")
|
||||
llm:
|
||||
provider: gpt4all
|
||||
config:
|
||||
model: 'orca-mini-3b.ggmlv3.q4_0.bin'
|
||||
model: 'orca-mini-3b-gguf2-q4_0.gguf'
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
|
||||
@@ -3,30 +3,106 @@ title: 📚 Introduction
|
||||
description: '📝 Embedchain is a Data Platform for LLMs - load, index, retrieve, and sync any unstructured data'
|
||||
---
|
||||
|
||||
## 🤔 What is Embedchain?
|
||||
## 🌐 What is Embedchain?
|
||||
|
||||
Embedchain abstracts the entire process of loading data, chunking it, creating embeddings, and storing it in a vector database.
|
||||
Embedchain simplifies data handling by automatically processing unstructured data, breaking it into chunks, generating embeddings, and storing it in a vector database.
|
||||
|
||||
You can add data from different data sources using the `.add()` method. Then, simply use the `.query()` method to find answers from the added datasets.
|
||||
Through various APIs, you can obtain contextual information for queries, find answers to specific questions, and engage in chat conversations using your data.
|
||||
## 🔍 Search
|
||||
|
||||
If you want to create a Naval Ravikant bot with a YouTube video, a book in PDF format, two blog posts, and a question and answer pair, all you need to do is add the respective links. Embedchain will take care of the rest, creating a bot for you.
|
||||
Embedchain lets you get most relevant context by doing semantic search over your data sources for a provided query. See the example below:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
naval_bot = App()
|
||||
# Add online data
|
||||
naval_bot.add("https://www.youtube.com/watch?v=3qHkcs3kG44")
|
||||
naval_bot.add("https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Almanack-of-Naval-Ravikant_Final.pdf")
|
||||
naval_bot.add("https://nav.al/feedback")
|
||||
naval_bot.add("https://nav.al/agi")
|
||||
naval_bot.add("The Meanings of Life", 'text', metadata={'chapter': 'philosphy'})
|
||||
# Initialize app
|
||||
app = App()
|
||||
|
||||
# Add local resources
|
||||
naval_bot.add(("Who is Naval Ravikant?", "Naval Ravikant is an Indian-American entrepreneur and investor."))
|
||||
# Add data source
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
|
||||
naval_bot.query("What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?")
|
||||
# Answer: Naval argues that humans possess the unique capacity to understand explanations or concepts to the maximum extent possible in this physical reality.
|
||||
# Get relevant context using semantic search
|
||||
context = app.search("What is the net worth of Elon?", num_documents=2)
|
||||
print(context)
|
||||
# Context:
|
||||
# [
|
||||
# {
|
||||
# 'context': 'Elon Musk PROFILEElon MuskCEO, Tesla$221.9BReal Time Net Worthas of 10/29/23Reflects change since 5 pm ET of prior trading day. 1 in the world todayPhoto by Martin Schoeller for ForbesAbout Elon MuskElon Musk cofounded six companies, including electric car maker Tesla, rocket producer SpaceX and tunneling startup Boring Company.He owns about 21% of Tesla between stock and options, but has pledged more than half his shares as collateral for personal loans of up to $3.5 billion.SpaceX, founded in',
|
||||
# 'source': 'https://www.forbes.com/profile/elon-musk',
|
||||
# 'document_id': 'some_document_id'
|
||||
# },
|
||||
# {
|
||||
# 'context': 'company, which is now called X.Wealth HistoryHOVER TO REVEAL NET WORTH BY YEARForbes Lists 1Forbes 400 (2023)The Richest Person In Every State (2023) 2Billionaires (2023) 1Innovative Leaders (2019) 25Powerful People (2018) 12Richest In Tech (2017)Global Game Changers (2016)More ListsPersonal StatsAge52Source of WealthTesla, SpaceX, Self MadeSelf-Made Score8Philanthropy Score1ResidenceAustin, TexasCitizenshipUnited StatesMarital StatusSingleChildren11EducationBachelor of Arts/Science, University',
|
||||
# 'source': 'https://www.forbes.com/profile/elon-musk',
|
||||
# 'document_id': 'some_document_id'
|
||||
# }
|
||||
# ]
|
||||
```
|
||||
|
||||
## ❓Query
|
||||
|
||||
Embedchain empowers developers to ask questions and receive relevant answers through a user-friendly query API. Refer to the following example to learn how to utilize the query API:
|
||||
|
||||
```python
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# Initialize app
|
||||
app = App()
|
||||
|
||||
# Add data source
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
|
||||
# Get relevant answer for your query
|
||||
answer = app.query("What is the net worth of Elon?")
|
||||
print(answer)
|
||||
# Answer: The net worth of Elon Musk is $221.9 billion.
|
||||
```
|
||||
|
||||
## 💬 Chat
|
||||
|
||||
Embedchain allows easy chatting over your data sources using a user-friendly chat API. Check out the example below to understand how to use the chat API:
|
||||
|
||||
```python
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# Initialize app
|
||||
app = App()
|
||||
|
||||
# Add data source
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
|
||||
# Chat on your data using `.chat()`
|
||||
answer = app.chat("How much did Elon pay for Twitter?")
|
||||
print(answer)
|
||||
# Answer: Elon Musk paid $44 billion for Twitter.
|
||||
```
|
||||
|
||||
## 🚀 Deploy
|
||||
|
||||
Embedchain enables developers to deploy their LLM-powered apps in production using the Embedchain platform. The platform offers free access to context on your data through its REST API. Once the pipeline is deployed, you can update your data sources anytime after deployment.
|
||||
|
||||
See the example below on how to use the deploy API:
|
||||
|
||||
```python
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
# Initialize app
|
||||
app = App()
|
||||
|
||||
# Add data source
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
|
||||
# Deploy your pipeline to Embedchain Platform
|
||||
app.deploy()
|
||||
|
||||
# 🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/
|
||||
# ec-xxxxxx
|
||||
|
||||
# 🛠️ Creating pipeline on the platform...
|
||||
# 🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/xxxxx
|
||||
|
||||
# 🛠️ Adding data to your pipeline...
|
||||
# ✅ Data of type: web_page, value: https://www.forbes.com/profile/elon-musk added successfully.
|
||||
```
|
||||
|
||||
## 🚀 How it works?
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: '🤖 OpenAI Assistant'
|
||||
---
|
||||
|
||||
<img src="https://blogs.swarthmore.edu/its/wp-content/uploads/2022/05/openai.jpg" align="center" width="500" alt="OpenAI Logo"/>
|
||||
|
||||
Embedchain now supports [OpenAI Assistants API](https://platform.openai.com/docs/assistants/overview) which allows you to build AI assistants within your own applications. An Assistant has instructions and can leverage models, tools, and knowledge to respond to user queries.
|
||||
|
||||
At a high level, an integration of the Assistants API has the following flow:
|
||||
|
||||
1. Create an Assistant in the API by defining it custom instructions and picking a model
|
||||
2. Create a Thread when a user starts a conversation
|
||||
3. Add Messages to the Thread as the user ask questions
|
||||
4. Run the Assistant on the Thread to trigger responses. This automatically calls the relevant tools.
|
||||
|
||||
Creating an OpenAI Assistant using Embedchain is very simple 3 step process.
|
||||
|
||||
## Step 1: Create OpenAI Assistant
|
||||
|
||||
Make sure that you have `OPENAI_API_KEY` set in the environment variable.
|
||||
|
||||
```python
|
||||
from embedchain.store.assistants import OpenAIAssistant
|
||||
|
||||
assistant = OpenAIAssistant(
|
||||
name="OpenAI DevDay Assistant",
|
||||
instructions="You are an organizer of OpenAI DevDay",
|
||||
)
|
||||
```
|
||||
|
||||
### Arguments
|
||||
|
||||
<ResponseField name="assistant_id" type="string" required>
|
||||
Load existing OpenAI Assistant. If you pass this, you don't have to pass other arguments
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="thread_id" type="string">
|
||||
Existing OpenAI thread id if exists
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="model" type="str" default="gpt-4-1106-preview">
|
||||
OpenAI model to use
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="tools" type="list">
|
||||
OpenAI tools to use. Default set to `[{"type": "retrieval"}]`
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="data_sources" type="list" default="[]">
|
||||
Add data sources to your assistant. You can add in the following format: `[{"source": "https://example.com", "data_type": "web_page"}]`
|
||||
</ResponseField>
|
||||
|
||||
## Step-2: Add data to thread
|
||||
|
||||
You can add any custom data source that is supported by Embedchain. Else, you can directly pass the file path on your local system and Embedchain propagates it to OpenAI Assistant.
|
||||
```python
|
||||
assistant.add("/path/to/file.pdf")
|
||||
assistant.add("https://www.youtube.com/watch?v=U9mJuUkhUzk", data_type="youtube_video")
|
||||
assistant.add("https://openai.com/blog/new-models-and-developer-products-announced-at-devday")
|
||||
```
|
||||
|
||||
## Step-3: Chat with your Assistant
|
||||
```python
|
||||
assistant.chat("How much OpenAI credits were offered to attendees during OpenAI DevDay?")
|
||||
# Response: 'Every attendee of OpenAI DevDay 2023 was offered $500 in OpenAI credits.'
|
||||
```
|
||||
|
||||
You can try it out yourself using the following Google Colab notebook:
|
||||
|
||||
<a href="https://colab.research.google.com/drive/1BKlXZYSl6AFRgiHZ5XIzXrXC_24kDYHQ?usp=sharing">
|
||||
<img src="https://camo.githubusercontent.com/84f0493939e0c4de4e6dbe113251b4bfb5353e57134ffd9fcab6b8714514d4d1/68747470733a2f2f636f6c61622e72657365617263682e676f6f676c652e636f6d2f6173736574732f636f6c61622d62616467652e737667" alt="Open in Colab" />
|
||||
</a>
|
||||
|
||||
@@ -11,28 +11,45 @@ Install embedchain python package:
|
||||
pip install embedchain
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Embedchain now supports OpenAI's latest `gpt-4-turbo` model. Checkout the [docs here](/get-started/faq#how-to-use-gpt-4-turbo-model-released-on-openai-devday) on how to use it.
|
||||
</Tip>
|
||||
|
||||
Creating an app involves 3 steps:
|
||||
|
||||
<Steps>
|
||||
<Step title="⚙️ Import app instance">
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
app = App()
|
||||
```
|
||||
</Step>
|
||||
<Step title="🗃️ Add data sources">
|
||||
```python
|
||||
# Add different data sources
|
||||
elon_bot.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
elon_bot.add("https://www.forbes.com/profile/elon-musk")
|
||||
app.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
# You can also add local data sources such as pdf, csv files etc.
|
||||
# elon_bot.add("/path/to/file.pdf")
|
||||
# app.add("/path/to/file.pdf")
|
||||
```
|
||||
</Step>
|
||||
<Step title="💬 Query or chat on your data and get answers">
|
||||
<Step title="💬 Query or chat or search context on your data">
|
||||
```python
|
||||
elon_bot.query("What is the net worth of Elon Musk today?")
|
||||
app.query("What is the net worth of Elon Musk today?")
|
||||
# Answer: The net worth of Elon Musk today is $258.7 billion.
|
||||
```
|
||||
</Step>
|
||||
<Step title="🚀 (Optional) Deploy your pipeline to Embedchain Platform">
|
||||
```python
|
||||
app.deploy()
|
||||
# 🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/
|
||||
# ec-xxxxxx
|
||||
|
||||
# 🛠️ Creating pipeline on the platform...
|
||||
# 🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/xxxxx
|
||||
|
||||
# 🛠️ Adding data to your pipeline...
|
||||
# ✅ Data of type: web_page, value: https://www.forbes.com/profile/elon-musk added successfully.
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
@@ -41,18 +58,28 @@ Putting it together, you can run your first app using the following code. Make s
|
||||
|
||||
```python
|
||||
import os
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "xxx"
|
||||
elon_bot = App()
|
||||
app = App()
|
||||
|
||||
# Add different data sources
|
||||
elon_bot.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
elon_bot.add("https://www.forbes.com/profile/elon-musk")
|
||||
app.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
# You can also add local data sources such as pdf, csv files etc.
|
||||
# elon_bot.add("/path/to/file.pdf")
|
||||
# app.add("/path/to/file.pdf")
|
||||
|
||||
response = elon_bot.query("What is the net worth of Elon Musk today?")
|
||||
response = app.query("What is the net worth of Elon Musk today?")
|
||||
print(response)
|
||||
# Answer: The net worth of Elon Musk today is $258.7 billion.
|
||||
|
||||
app.deploy()
|
||||
# 🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/
|
||||
# ec-xxxxxx
|
||||
|
||||
# 🛠️ Creating pipeline on the platform...
|
||||
# 🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/xxxxx
|
||||
|
||||
# 🛠️ Adding data to your pipeline...
|
||||
# ✅ Data of type: web_page, value: https://www.forbes.com/profile/elon-musk added successfully.
|
||||
```
|
||||
|
||||
|
Before Width: | Height: | Size: 256 KiB |
|
After Width: | Height: | Size: 8.2 MiB |
|
After Width: | Height: | Size: 83 KiB |
@@ -39,7 +39,7 @@ os.environ['LANGCHAIN_PROJECT] = <your-project>
|
||||
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
from embedchain import Pipeline as App
|
||||
|
||||
app = App()
|
||||
app.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
|
||||
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 3.1 KiB |
@@ -3,40 +3,70 @@
|
||||
"name": "Embedchain",
|
||||
"logo": {
|
||||
"dark": "/logo/dark.svg",
|
||||
"light": "/logo/light.svg"
|
||||
"light": "/logo/light.svg",
|
||||
"href": "https://embedchain.ai/"
|
||||
},
|
||||
"favicon": "/favicon.png",
|
||||
"colors": {
|
||||
"primary": "#12A7D3",
|
||||
"light": "#81D7F7",
|
||||
"dark": "#004E7A"
|
||||
"primary": "#3B2FC9",
|
||||
"light": "#6673FF",
|
||||
"dark": "#3B2FC9",
|
||||
"background": {
|
||||
"dark": "#0f1117",
|
||||
"light": "#fff"
|
||||
}
|
||||
},
|
||||
"modeToggle": {
|
||||
"default": "dark"
|
||||
},
|
||||
"openapi": ["/rest-api.json"],
|
||||
"metadata": {
|
||||
"og:image": "/images/og.png",
|
||||
"twitter:site": "@embedchain"
|
||||
},
|
||||
"anchors": [
|
||||
{
|
||||
"name": "Embedchain Platform",
|
||||
"icon": "tv",
|
||||
"url": "https://app.embedchain.ai/"
|
||||
},
|
||||
{
|
||||
"name": "Join our slack",
|
||||
"icon": "slack",
|
||||
"url": "https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw"
|
||||
}
|
||||
],
|
||||
"topbarLinks": [
|
||||
{
|
||||
"name": "Twitter",
|
||||
"url": "https://twitter.com/embedchain"
|
||||
},
|
||||
{
|
||||
"name":"Slack",
|
||||
"url":"https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw"
|
||||
},
|
||||
{
|
||||
"name": "Discord",
|
||||
"url": "https://discord.gg/6PzXDgEjG5"
|
||||
"name": "Create account",
|
||||
"url": "https://app.embedchain.ai/login/"
|
||||
}
|
||||
],
|
||||
"topbarCtaButton": {
|
||||
"name": "GitHub",
|
||||
"url": "https://embedchain.ai"
|
||||
"name": "Get started",
|
||||
"url": "https://app.embedchain.ai"
|
||||
},
|
||||
"primaryTab": {
|
||||
"name": "Docs"
|
||||
},
|
||||
"navigation": [
|
||||
{
|
||||
"group": "Get started",
|
||||
"pages": ["get-started/quickstart", "get-started/introduction", "get-started/faq", "get-started/examples"]
|
||||
"pages": [
|
||||
"get-started/quickstart",
|
||||
"get-started/introduction",
|
||||
"get-started/openai-assistant",
|
||||
"get-started/faq",
|
||||
"get-started/examples"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Components",
|
||||
"pages": ["components/llms", "components/embedding-models", "components/vector-databases"]
|
||||
"pages": [
|
||||
"components/llms",
|
||||
"components/embedding-models",
|
||||
"components/vector-databases"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Data sources",
|
||||
@@ -68,19 +98,33 @@
|
||||
"pages": ["advanced/configuration"]
|
||||
},
|
||||
{
|
||||
"group": "Examples",
|
||||
"pages": ["examples/full_stack", "examples/api_server", "examples/discord_bot", "examples/slack_bot", "examples/telegram_bot", "examples/whatsapp_bot", "examples/poe_bot"]
|
||||
"group": "REST API",
|
||||
"pages": [
|
||||
"rest-api/getting-started",
|
||||
"rest-api/create",
|
||||
"rest-api/get-all-apps",
|
||||
"rest-api/add-data",
|
||||
"rest-api/get-data",
|
||||
"rest-api/query",
|
||||
"rest-api/deploy",
|
||||
"rest-api/delete",
|
||||
"rest-api/check-status"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Pipelines",
|
||||
"pages": ["pipelines/quickstart"]
|
||||
"group": "Use Cases",
|
||||
"pages": [
|
||||
"examples/full_stack",
|
||||
"examples/discord_bot",
|
||||
"examples/slack_bot",
|
||||
"examples/telegram_bot",
|
||||
"examples/whatsapp_bot",
|
||||
"examples/poe_bot"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Community",
|
||||
"pages": [
|
||||
"community/connect-with-us",
|
||||
"community/showcase"
|
||||
]
|
||||
"pages": ["community/connect-with-us", "community/showcase"]
|
||||
},
|
||||
{
|
||||
"group": "Integrations",
|
||||
@@ -98,22 +142,33 @@
|
||||
},
|
||||
{
|
||||
"group": "Product",
|
||||
"pages": [
|
||||
"product/release-notes"
|
||||
]
|
||||
"pages": ["product/release-notes"]
|
||||
}
|
||||
|
||||
],
|
||||
|
||||
"footerSocials": {
|
||||
"website": "https://embedchain.ai",
|
||||
"github": "https://github.com/embedchain/embedchain",
|
||||
"slack":"https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw",
|
||||
"slack": "https://join.slack.com/t/embedchain/shared_invite/zt-22uwz3c46-Zg7cIh5rOBteT_xe1jwLDw",
|
||||
"discord": "https://discord.gg/6PzXDgEjG5",
|
||||
"twitter": "https://twitter.com/embedchain",
|
||||
"linkedin": "https://www.linkedin.com/company/embedchain"
|
||||
},
|
||||
"backgroundImage": "/background.png",
|
||||
"isWhiteLabeled": true,
|
||||
"feedback.thumbsRating": true
|
||||
"analytics": {
|
||||
"posthog": {
|
||||
"apiKey": "phc_PHQDA5KwztijnSojsxJ2c1DuJd52QCzJzT2xnSGvjN2",
|
||||
"apiHost": "https://app.embedchain.ai/ingest"
|
||||
}
|
||||
},
|
||||
"feedback": {
|
||||
"suggestEdit": true,
|
||||
"raiseIssue": true,
|
||||
"thumbsRating": true
|
||||
},
|
||||
"search": {
|
||||
"prompt": "✨ Search embedchain docs..."
|
||||
},
|
||||
"api": {
|
||||
"baseUrl": "http://localhost:8080"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
title: '🚀 Pipelines'
|
||||
description: '💡 Start building LLM powered data pipelines in 1 minute'
|
||||
---
|
||||
|
||||
Embedchain lets you build data pipelines on your own data sources and deploy it in production in less than a minute. It can load, index, retrieve, and sync any unstructured data.
|
||||
|
||||
Install embedchain python package:
|
||||
|
||||
```bash
|
||||
pip install embedchain
|
||||
```
|
||||
|
||||
Creating a pipeline involves 3 steps:
|
||||
|
||||
<Steps>
|
||||
<Step title="⚙️ Import pipeline instance">
|
||||
```python
|
||||
from embedchain import Pipeline
|
||||
p = Pipeline(name="Elon Musk")
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="🗃️ Add data sources">
|
||||
```python
|
||||
# Add different data sources
|
||||
p.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
p.add("https://www.forbes.com/profile/elon-musk")
|
||||
# You can also add local data sources such as pdf, csv files etc.
|
||||
# p.add("/path/to/file.pdf")
|
||||
```
|
||||
</Step>
|
||||
<Step title="💬 Deploy your pipeline to Embedchain platform">
|
||||
```python
|
||||
p.deploy()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
That's it. Now, head to the [Embedchain platform](https://app.embedchain.ai) and your pipeline is available there. Make sure to set the `OPENAI_API_KEY` 🔑 environment variable in the code.
|
||||
|
||||
After you deploy your pipeline to Embedchain platform, you can still add more data sources and update the pipeline multiple times.
|
||||
|
||||
Here is a Google Colab notebook for you to get started: [](https://colab.research.google.com/drive/1YVXaBO4yqlHZY4ho67GCJ6aD4CHNiScD?usp=sharing)
|
||||
@@ -0,0 +1,427 @@
|
||||
{
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "Embedchain REST API",
|
||||
"description": "This is the REST API for Embedchain.",
|
||||
"license": {
|
||||
"name": "Apache 2.0",
|
||||
"url": "https://github.com/embedchain/embedchain/blob/main/LICENSE"
|
||||
},
|
||||
"version": "0.0.1"
|
||||
},
|
||||
"paths": {
|
||||
"/ping": {
|
||||
"get": {
|
||||
"tags": ["Utility"],
|
||||
"summary": "Check status",
|
||||
"description": "Endpoint to check the status of the API",
|
||||
"operationId": "check_status_ping_get",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": { "application/json": { "schema": {} } }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/apps": {
|
||||
"get": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Get all apps",
|
||||
"description": "Get all applications",
|
||||
"operationId": "get_all_apps_apps_get",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": { "application/json": { "schema": {} } }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/create": {
|
||||
"post": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Create app",
|
||||
"description": "Create a new app using App ID",
|
||||
"operationId": "create_app_using_default_config_create_post",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"multipart/form-data": {
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/Body_create_app_using_default_config_create_post"
|
||||
}
|
||||
],
|
||||
"title": "Body"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DefaultResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/{app_id}/data": {
|
||||
"get": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Get data",
|
||||
"description": "Get all data sources for an app",
|
||||
"operationId": "get_datasources_associated_with_app_id__app_id__data_get",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": { "application/json": { "schema": {} } }
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/{app_id}/add": {
|
||||
"post": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Add data",
|
||||
"description": "Add a data source to an app.",
|
||||
"operationId": "add_datasource_to_an_app__app_id__add_post",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/SourceApp" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DefaultResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/{app_id}/query": {
|
||||
"post": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Query app",
|
||||
"description": "Query an app",
|
||||
"operationId": "query_an_app__app_id__query_post",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/QueryApp" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DefaultResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/{app_id}/chat": {
|
||||
"post": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Chat",
|
||||
"description": "Chat with an app.\n\napp_id: The ID of the app. Use \"default\" for the default app.\n\nmessage: The message that you want to send to the app.",
|
||||
"operationId": "chat_with_an_app__app_id__chat_post",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/MessageApp" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DefaultResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/{app_id}/deploy": {
|
||||
"post": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Deploy App",
|
||||
"description": "Deploy an existing app.",
|
||||
"operationId": "deploy_app__app_id__deploy_post",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DeployAppRequest" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DefaultResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/{app_id}/delete": {
|
||||
"delete": {
|
||||
"tags": ["Apps"],
|
||||
"summary": "Delete app",
|
||||
"description": "Delete an existing app",
|
||||
"operationId": "delete_app__app_id__delete_delete",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "app_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "title": "App Id" }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/DefaultResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/HTTPValidationError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"schemas": {
|
||||
"Body_create_app_using_default_config_create_post": {
|
||||
"properties": {
|
||||
"config": { "type": "string", "format": "binary", "title": "Config" }
|
||||
},
|
||||
"type": "object",
|
||||
"title": "Body_create_app_using_default_config_create_post"
|
||||
},
|
||||
"DefaultResponse": {
|
||||
"properties": { "response": { "type": "string", "title": "Response" } },
|
||||
"type": "object",
|
||||
"required": ["response"],
|
||||
"title": "DefaultResponse"
|
||||
},
|
||||
"DeployAppRequest": {
|
||||
"properties": {
|
||||
"api_key": {
|
||||
"type": "string",
|
||||
"title": "Api Key",
|
||||
"description": "The Embedchain API key for app deployments. You get the api key on the Embedchain platform by visiting [https://app.embedchain.ai](https://app.embedchain.ai)",
|
||||
"default": ""
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"title": "DeployAppRequest",
|
||||
"example":{
|
||||
"api_key":"ec-xxx"
|
||||
}
|
||||
},
|
||||
"HTTPValidationError": {
|
||||
"properties": {
|
||||
"detail": {
|
||||
"items": { "$ref": "#/components/schemas/ValidationError" },
|
||||
"type": "array",
|
||||
"title": "Detail"
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"title": "HTTPValidationError"
|
||||
},
|
||||
"MessageApp": {
|
||||
"properties": {
|
||||
"message": {
|
||||
"type": "string",
|
||||
"title": "Message",
|
||||
"description": "The message that you want to send to the App.",
|
||||
"default": ""
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"title": "MessageApp"
|
||||
},
|
||||
"QueryApp": {
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"title": "Query",
|
||||
"description": "The query that you want to ask the App.",
|
||||
"default": ""
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"title": "QueryApp",
|
||||
"example":{
|
||||
"query":"Who is Elon Musk?"
|
||||
}
|
||||
},
|
||||
"SourceApp": {
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"title": "Source",
|
||||
"description": "The source that you want to add to the App.",
|
||||
"default": ""
|
||||
},
|
||||
"data_type": {
|
||||
"anyOf": [{ "type": "string" }, { "type": "null" }],
|
||||
"title": "Data Type",
|
||||
"description": "The type of data to add, remove it if you want Embedchain to detect it automatically.",
|
||||
"default": ""
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"title": "SourceApp",
|
||||
"example":{
|
||||
"source":"https://en.wikipedia.org/wiki/Elon_Musk"
|
||||
}
|
||||
},
|
||||
"ValidationError": {
|
||||
"properties": {
|
||||
"loc": {
|
||||
"items": { "anyOf": [{ "type": "string" }, { "type": "integer" }] },
|
||||
"type": "array",
|
||||
"title": "Location"
|
||||
},
|
||||
"msg": { "type": "string", "title": "Message" },
|
||||
"type": { "type": "string", "title": "Error Type" }
|
||||
},
|
||||
"type": "object",
|
||||
"required": ["loc", "msg", "type"],
|
||||
"title": "ValidationError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
openapi: post /{app_id}/add
|
||||
---
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/{app_id}/add \
|
||||
-d "source=https://www.forbes.com/profile/elon-musk" \
|
||||
-d "data_type=web_page"
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{ "response": "fec7fe91e6b2d732938a2ec2e32bfe3f" }
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /{app_id}/chat
|
||||
---
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
openapi: get /ping
|
||||
---
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request GET \
|
||||
--url http://localhost:8080/ping
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{ "ping": "pong" }
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
openapi: post /create
|
||||
---
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/create?app_id=app1 \
|
||||
-F "config=@/path/to/config.yaml"
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{ "response": "App created successfully. App ID: app1" }
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
|
||||
By default we will use the opensource **gpt4all** model to get started. You can also specify your own config by uploading a config YAML file.
|
||||
|
||||
For example, create a `config.yaml` file (adjust according to your requirements):
|
||||
|
||||
```yaml
|
||||
app:
|
||||
config:
|
||||
id: "default-app"
|
||||
|
||||
llm:
|
||||
provider: openai
|
||||
config:
|
||||
model: "gpt-3.5-turbo"
|
||||
temperature: 0.5
|
||||
max_tokens: 1000
|
||||
top_p: 1
|
||||
stream: false
|
||||
template: |
|
||||
Use the following pieces of context to answer the query at the end.
|
||||
If you don't know the answer, just say that you don't know, don't try to make up an answer.
|
||||
|
||||
$context
|
||||
|
||||
Query: $query
|
||||
|
||||
Helpful Answer:
|
||||
|
||||
vectordb:
|
||||
provider: chroma
|
||||
config:
|
||||
collection_name: "rest-api-app"
|
||||
dir: db
|
||||
allow_reset: true
|
||||
|
||||
embedder:
|
||||
provider: openai
|
||||
config:
|
||||
model: "text-embedding-ada-002"
|
||||
```
|
||||
|
||||
To learn more about custom configurations, check out the [custom configurations docs](https://docs.embedchain.ai/advanced/configuration). To explore more examples of config yamls for embedchain, visit [embedchain/configs](https://github.com/embedchain/embedchain/tree/main/configs).
|
||||
|
||||
Now, you can upload this config file in the request body.
|
||||
|
||||
For example,
|
||||
|
||||
```bash Request
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/create?app_id=my-app \
|
||||
-F "config=@/path/to/config.yaml"
|
||||
```
|
||||
|
||||
**Note:** To use custom models, an **API key** might be required. Refer to the table below to determine the necessary API key for your provider.
|
||||
|
||||
| Keys | Providers |
|
||||
| -------------------------- | ------------------------------ |
|
||||
| `OPENAI_API_KEY ` | OpenAI, Azure OpenAI, Jina etc |
|
||||
| `OPENAI_API_TYPE` | Azure OpenAI |
|
||||
| `OPENAI_API_BASE` | Azure OpenAI |
|
||||
| `OPENAI_API_VERSION` | Azure OpenAI |
|
||||
| `COHERE_API_KEY` | Cohere |
|
||||
| `ANTHROPIC_API_KEY` | Anthropic |
|
||||
| `JINACHAT_API_KEY` | Jina |
|
||||
| `HUGGINGFACE_ACCESS_TOKEN` | Huggingface |
|
||||
| `REPLICATE_API_TOKEN` | LLAMA2 |
|
||||
|
||||
To add env variables, you can simply run the docker command with the `-e` flag.
|
||||
|
||||
For example,
|
||||
|
||||
```bash
|
||||
docker run --name embedchain -p 8080:8080 -e OPENAI_API_KEY=<YOUR_OPENAI_API_KEY> embedchain/rest-api:latest
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
openapi: delete /{app_id}/delete
|
||||
---
|
||||
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request DELETE \
|
||||
--url http://localhost:8080/{app_id}/delete
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{ "response": "App with id {app_id} deleted successfully." }
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
openapi: post /{app_id}/deploy
|
||||
---
|
||||
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/{app_id}/deploy \
|
||||
-d "api_key=ec-xxxx"
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{ "response": "App deployed successfully." }
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
openapi: get /apps
|
||||
---
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request GET \
|
||||
--url http://localhost:8080/apps
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"config": "config1.yaml",
|
||||
"id": 1,
|
||||
"app_id": "app1"
|
||||
},
|
||||
{
|
||||
"config": "config2.yaml",
|
||||
"id": 2,
|
||||
"app_id": "app2"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
openapi: get /{app_id}/data
|
||||
---
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request GET \
|
||||
--url http://localhost:8080/{app_id}/data
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"data_type": "web_page",
|
||||
"data_value": "https://www.forbes.com/profile/elon-musk/",
|
||||
"metadata": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -0,0 +1,294 @@
|
||||
---
|
||||
title: "🌍 Getting Started"
|
||||
---
|
||||
|
||||
## Quickstart
|
||||
|
||||
To use Embedchain as a REST API service, run the following command:
|
||||
|
||||
```bash
|
||||
docker run --name embedchain -p 8080:8080 embedchain/rest-api:latest
|
||||
```
|
||||
|
||||
Navigate to [http://localhost:8080/docs](http://localhost:8080/docs) to interact with the API. There is a full-fledged Swagger docs playground with all the information about the API endpoints.
|
||||
|
||||

|
||||
|
||||
## ⚡ Steps to get started
|
||||
|
||||
<Steps>
|
||||
<Step title="⚙️ Create an app">
|
||||
<Tabs>
|
||||
<Tab title="cURL">
|
||||
```bash
|
||||
curl --request POST "http://localhost:8080/create?app_id=my-app" \
|
||||
-H "accept: application/json"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
url = "http://localhost:8080/create?app_id=my-app"
|
||||
|
||||
payload={}
|
||||
|
||||
response = requests.request("POST", url, data=payload)
|
||||
|
||||
print(response)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="javascript">
|
||||
```javascript
|
||||
const data = fetch("http://localhost:8080/create?app_id=my-app", {
|
||||
method: "POST",
|
||||
}).then((res) => res.json());
|
||||
|
||||
console.log(data);
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="go">
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
url := "http://localhost:8080/create?app_id=my-app"
|
||||
|
||||
payload := strings.NewReader("")
|
||||
|
||||
req, _ := http.NewRequest("POST", url, payload)
|
||||
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
defer res.Body.Close()
|
||||
body, _ := ioutil.ReadAll(res.Body)
|
||||
|
||||
fmt.Println(res)
|
||||
fmt.Println(string(body))
|
||||
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
</Step>
|
||||
<Step title="🗃️ Add data sources">
|
||||
<Tabs>
|
||||
<Tab title="cURL">
|
||||
```bash
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/my-app/add \
|
||||
-d "source=https://www.forbes.com/profile/elon-musk" \
|
||||
-d "data_type=web_page"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
url = "http://localhost:8080/my-app/add"
|
||||
|
||||
payload = "source=https://www.forbes.com/profile/elon-musk&data_type=web_page"
|
||||
headers = {}
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
print(response)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="javascript">
|
||||
```javascript
|
||||
const data = fetch("http://localhost:8080/my-app/add", {
|
||||
method: "POST",
|
||||
body: "source=https://www.forbes.com/profile/elon-musk&data_type=web_page",
|
||||
}).then((res) => res.json());
|
||||
|
||||
console.log(data);
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="go">
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
url := "http://localhost:8080/my-app/add"
|
||||
|
||||
payload := strings.NewReader("source=https://www.forbes.com/profile/elon-musk&data_type=web_page")
|
||||
|
||||
req, _ := http.NewRequest("POST", url, payload)
|
||||
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
defer res.Body.Close()
|
||||
body, _ := ioutil.ReadAll(res.Body)
|
||||
|
||||
fmt.Println(res)
|
||||
fmt.Println(string(body))
|
||||
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
</Step>
|
||||
<Step title="💬 Query on your data">
|
||||
<Tabs>
|
||||
<Tab title="cURL">
|
||||
```bash
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/my-app/query \
|
||||
-d "query=Who is Elon Musk?"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
url = "http://localhost:8080/my-app/query"
|
||||
|
||||
payload = "query=Who is Elon Musk?"
|
||||
headers = {}
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
print(response)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="javascript">
|
||||
```javascript
|
||||
const data = fetch("http://localhost:8080/my-app/query", {
|
||||
method: "POST",
|
||||
body: "query=Who is Elon Musk?",
|
||||
}).then((res) => res.json());
|
||||
|
||||
console.log(data);
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="go">
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
url := "http://localhost:8080/my-app/query"
|
||||
|
||||
payload := strings.NewReader("query=Who is Elon Musk?")
|
||||
|
||||
req, _ := http.NewRequest("POST", url, payload)
|
||||
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
defer res.Body.Close()
|
||||
body, _ := ioutil.ReadAll(res.Body)
|
||||
|
||||
fmt.Println(res)
|
||||
fmt.Println(string(body))
|
||||
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
</Step>
|
||||
<Step title="🚀 (Optional) Deploy your app to Embedchain Platform">
|
||||
<Tabs>
|
||||
<Tab title="cURL">
|
||||
```bash
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/my-app/deploy \
|
||||
-d "api_key=ec-xxxx"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
url = "http://localhost:8080/my-app/deploy"
|
||||
|
||||
payload = "api_key=ec-xxxx"
|
||||
|
||||
response = requests.request("POST", url, data=payload)
|
||||
|
||||
print(response)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="javascript">
|
||||
```javascript
|
||||
const data = fetch("http://localhost:8080/my-app/deploy", {
|
||||
method: "POST",
|
||||
body: "api_key=ec-xxxx",
|
||||
}).then((res) => res.json());
|
||||
|
||||
console.log(data);
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="go">
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
url := "http://localhost:8080/my-app/deploy"
|
||||
|
||||
payload := strings.NewReader("api_key=ec-xxxx")
|
||||
|
||||
req, _ := http.NewRequest("POST", url, payload)
|
||||
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
defer res.Body.Close()
|
||||
body, _ := ioutil.ReadAll(res.Body)
|
||||
|
||||
fmt.Println(res)
|
||||
fmt.Println(string(body))
|
||||
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
And you're ready! 🎉
|
||||
|
||||
If you run into issues, please feel free to contact us using below links:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
openapi: post /{app_id}/query
|
||||
---
|
||||
|
||||
<RequestExample>
|
||||
|
||||
```bash Request
|
||||
curl --request POST \
|
||||
--url http://localhost:8080/{app_id}/query \
|
||||
-d "query=who is Elon Musk?"
|
||||
```
|
||||
|
||||
</RequestExample>
|
||||
|
||||
<ResponseExample>
|
||||
|
||||
```json Response
|
||||
{ "response": "Net worth of Elon Musk is $218 Billion." }
|
||||
```
|
||||
|
||||
</ResponseExample>
|
||||
@@ -2,7 +2,8 @@ from typing import Optional
|
||||
|
||||
import yaml
|
||||
|
||||
from embedchain.config import AppConfig, BaseEmbedderConfig, BaseLlmConfig
|
||||
from embedchain.config import (AppConfig, BaseEmbedderConfig, BaseLlmConfig,
|
||||
ChunkerConfig)
|
||||
from embedchain.config.vectordb.base import BaseVectorDbConfig
|
||||
from embedchain.embedchain import EmbedChain
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
@@ -11,6 +12,7 @@ from embedchain.factory import EmbedderFactory, LlmFactory, VectorDBFactory
|
||||
from embedchain.helper.json_serializable import register_deserializable
|
||||
from embedchain.llm.base import BaseLlm
|
||||
from embedchain.llm.openai import OpenAILlm
|
||||
from embedchain.utils import validate_yaml_config
|
||||
from embedchain.vectordb.base import BaseVectorDB
|
||||
from embedchain.vectordb.chroma import ChromaDB
|
||||
|
||||
@@ -37,6 +39,7 @@ class App(EmbedChain):
|
||||
embedder: BaseEmbedder = None,
|
||||
embedder_config: Optional[BaseEmbedderConfig] = None,
|
||||
system_prompt: Optional[str] = None,
|
||||
chunker: Optional[ChunkerConfig] = None,
|
||||
):
|
||||
"""
|
||||
Initialize a new `App` instance.
|
||||
@@ -96,6 +99,9 @@ class App(EmbedChain):
|
||||
if embedder is None:
|
||||
embedder = OpenAIEmbedder(config=embedder_config)
|
||||
|
||||
self.chunker = None
|
||||
if chunker:
|
||||
self.chunker = ChunkerConfig(**chunker)
|
||||
# Type check assignments
|
||||
if not isinstance(llm, BaseLlm):
|
||||
raise TypeError(
|
||||
@@ -127,10 +133,16 @@ class App(EmbedChain):
|
||||
with open(yaml_path, "r") as file:
|
||||
config_data = yaml.safe_load(file)
|
||||
|
||||
try:
|
||||
validate_yaml_config(config_data)
|
||||
except Exception as e:
|
||||
raise Exception(f"❌ Error occurred while validating the YAML config. Error: {str(e)}")
|
||||
|
||||
app_config_data = config_data.get("app", {})
|
||||
llm_config_data = config_data.get("llm", {})
|
||||
db_config_data = config_data.get("vectordb", {})
|
||||
embedder_config_data = config_data.get("embedder", {})
|
||||
embedding_model_config_data = config_data.get("embedding_model", config_data.get("embedder", {}))
|
||||
chunker_config_data = config_data.get("chunker", {})
|
||||
|
||||
app_config = AppConfig(**app_config_data.get("config", {}))
|
||||
|
||||
@@ -140,6 +152,6 @@ class App(EmbedChain):
|
||||
db_provider = db_config_data.get("provider", "chroma")
|
||||
db = VectorDBFactory.create(db_provider, db_config_data.get("config", {}))
|
||||
|
||||
embedder_provider = embedder_config_data.get("provider", "openai")
|
||||
embedder = EmbedderFactory.create(embedder_provider, embedder_config_data.get("config", {}))
|
||||
return cls(config=app_config, llm=llm, db=db, embedder=embedder)
|
||||
embedder_provider = embedding_model_config_data.get("provider", "openai")
|
||||
embedder = EmbedderFactory.create(embedder_provider, embedding_model_config_data.get("config", {}))
|
||||
return cls(config=app_config, llm=llm, db=db, embedder=embedder, chunker=chunker_config_data)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import builtins
|
||||
from importlib import import_module
|
||||
from typing import Callable, Optional
|
||||
|
||||
from embedchain.config.base_config import BaseConfig
|
||||
@@ -18,7 +20,18 @@ class ChunkerConfig(BaseConfig):
|
||||
):
|
||||
self.chunk_size = chunk_size if chunk_size else 2000
|
||||
self.chunk_overlap = chunk_overlap if chunk_overlap else 0
|
||||
self.length_function = length_function if length_function else len
|
||||
if isinstance(length_function, str):
|
||||
self.length_function = self.load_func(length_function)
|
||||
else:
|
||||
self.length_function = length_function if length_function else len
|
||||
|
||||
def load_func(self, dotpath: str):
|
||||
if "." not in dotpath:
|
||||
return getattr(builtins, dotpath)
|
||||
else:
|
||||
module_, func = dotpath.rsplit(".", maxsplit=1)
|
||||
m = import_module(module_)
|
||||
return getattr(m, func)
|
||||
|
||||
|
||||
@register_deserializable
|
||||
|
||||
@@ -15,7 +15,7 @@ class AppConfig(BaseAppConfig):
|
||||
self,
|
||||
log_level: str = "WARNING",
|
||||
id: Optional[str] = None,
|
||||
collect_metrics: Optional[bool] = None,
|
||||
collect_metrics: Optional[bool] = True,
|
||||
collection_name: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
|
||||
@@ -16,7 +16,7 @@ class PipelineConfig(BaseAppConfig):
|
||||
log_level: str = "WARNING",
|
||||
id: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
collect_metrics: Optional[bool] = False,
|
||||
collect_metrics: Optional[bool] = True,
|
||||
):
|
||||
"""
|
||||
Initializes a configuration class instance for an App. This is the simplest form of an embedchain app.
|
||||
|
||||
@@ -1,41 +1,10 @@
|
||||
from importlib import import_module
|
||||
|
||||
from embedchain.chunkers.base_chunker import BaseChunker
|
||||
from embedchain.chunkers.docs_site import DocsSiteChunker
|
||||
from embedchain.chunkers.docx_file import DocxFileChunker
|
||||
from embedchain.chunkers.gmail import GmailChunker
|
||||
from embedchain.chunkers.images import ImagesChunker
|
||||
from embedchain.chunkers.json import JSONChunker
|
||||
from embedchain.chunkers.mdx import MdxChunker
|
||||
from embedchain.chunkers.notion import NotionChunker
|
||||
from embedchain.chunkers.openapi import OpenAPIChunker
|
||||
from embedchain.chunkers.pdf_file import PdfFileChunker
|
||||
from embedchain.chunkers.qna_pair import QnaPairChunker
|
||||
from embedchain.chunkers.sitemap import SitemapChunker
|
||||
from embedchain.chunkers.table import TableChunker
|
||||
from embedchain.chunkers.text import TextChunker
|
||||
from embedchain.chunkers.unstructured_file import UnstructuredFileChunker
|
||||
from embedchain.chunkers.web_page import WebPageChunker
|
||||
from embedchain.chunkers.xml import XmlChunker
|
||||
from embedchain.chunkers.youtube_video import YoutubeVideoChunker
|
||||
from embedchain.config import AddConfig
|
||||
from embedchain.config.add_config import ChunkerConfig, LoaderConfig
|
||||
from embedchain.helper.json_serializable import JSONSerializable
|
||||
from embedchain.loaders.base_loader import BaseLoader
|
||||
from embedchain.loaders.csv import CsvLoader
|
||||
from embedchain.loaders.docs_site_loader import DocsSiteLoader
|
||||
from embedchain.loaders.docx_file import DocxFileLoader
|
||||
from embedchain.loaders.gmail import GmailLoader
|
||||
from embedchain.loaders.images import ImagesLoader
|
||||
from embedchain.loaders.json import JSONLoader
|
||||
from embedchain.loaders.local_qna_pair import LocalQnaPairLoader
|
||||
from embedchain.loaders.local_text import LocalTextLoader
|
||||
from embedchain.loaders.mdx import MdxLoader
|
||||
from embedchain.loaders.openapi import OpenAPILoader
|
||||
from embedchain.loaders.pdf_file import PdfFileLoader
|
||||
from embedchain.loaders.sitemap import SitemapLoader
|
||||
from embedchain.loaders.unstructured_file import UnstructuredLoader
|
||||
from embedchain.loaders.web_page import WebPageLoader
|
||||
from embedchain.loaders.xml import XmlLoader
|
||||
from embedchain.loaders.youtube_video import YoutubeVideoLoader
|
||||
from embedchain.models.data_type import DataType
|
||||
|
||||
|
||||
@@ -58,6 +27,11 @@ class DataFormatter(JSONSerializable):
|
||||
self.loader = self._get_loader(data_type=data_type, config=config.loader)
|
||||
self.chunker = self._get_chunker(data_type=data_type, config=config.chunker)
|
||||
|
||||
def _lazy_load(self, module_path: str):
|
||||
module_path, class_name = module_path.rsplit(".", 1)
|
||||
module = import_module(module_path)
|
||||
return getattr(module, class_name)
|
||||
|
||||
def _get_loader(self, data_type: DataType, config: LoaderConfig) -> BaseLoader:
|
||||
"""
|
||||
Returns the appropriate data loader for the given data type.
|
||||
@@ -71,71 +45,55 @@ class DataFormatter(JSONSerializable):
|
||||
:rtype: BaseLoader
|
||||
"""
|
||||
loaders = {
|
||||
DataType.YOUTUBE_VIDEO: YoutubeVideoLoader,
|
||||
DataType.PDF_FILE: PdfFileLoader,
|
||||
DataType.WEB_PAGE: WebPageLoader,
|
||||
DataType.QNA_PAIR: LocalQnaPairLoader,
|
||||
DataType.TEXT: LocalTextLoader,
|
||||
DataType.DOCX: DocxFileLoader,
|
||||
DataType.SITEMAP: SitemapLoader,
|
||||
DataType.XML: XmlLoader,
|
||||
DataType.DOCS_SITE: DocsSiteLoader,
|
||||
DataType.CSV: CsvLoader,
|
||||
DataType.MDX: MdxLoader,
|
||||
DataType.IMAGES: ImagesLoader,
|
||||
DataType.UNSTRUCTURED: UnstructuredLoader,
|
||||
DataType.JSON: JSONLoader,
|
||||
DataType.OPENAPI: OpenAPILoader,
|
||||
DataType.GMAIL: GmailLoader,
|
||||
DataType.YOUTUBE_VIDEO: "embedchain.loaders.youtube_video.YoutubeVideoLoader",
|
||||
DataType.PDF_FILE: "embedchain.loaders.pdf_file.PdfFileLoader",
|
||||
DataType.WEB_PAGE: "embedchain.loaders.web_page.WebPageLoader",
|
||||
DataType.QNA_PAIR: "embedchain.loaders.local_qna_pair.LocalQnaPairLoader",
|
||||
DataType.TEXT: "embedchain.loaders.local_text.LocalTextLoader",
|
||||
DataType.DOCX: "embedchain.loaders.docx_file.DocxFileLoader",
|
||||
DataType.SITEMAP: "embedchain.loaders.sitemap.SitemapLoader",
|
||||
DataType.XML: "embedchain.loaders.xml.XmlLoader",
|
||||
DataType.DOCS_SITE: "embedchain.loaders.docs_site_loader.DocsSiteLoader",
|
||||
DataType.CSV: "embedchain.loaders.csv.CsvLoader",
|
||||
DataType.MDX: "embedchain.loaders.mdx.MdxLoader",
|
||||
DataType.IMAGES: "embedchain.loaders.images.ImagesLoader",
|
||||
DataType.UNSTRUCTURED: "embedchain.loaders.unstructured_file.UnstructuredLoader",
|
||||
DataType.JSON: "embedchain.loaders.json.JSONLoader",
|
||||
DataType.OPENAPI: "embedchain.loaders.openapi.OpenAPILoader",
|
||||
DataType.GMAIL: "embedchain.loaders.gmail.GmailLoader",
|
||||
DataType.NOTION: "embedchain.loaders.notion.NotionLoader",
|
||||
}
|
||||
lazy_loaders = {DataType.NOTION}
|
||||
if data_type in loaders:
|
||||
loader_class: type = loaders[data_type]
|
||||
loader: BaseLoader = loader_class()
|
||||
return loader
|
||||
elif data_type in lazy_loaders:
|
||||
if data_type == DataType.NOTION:
|
||||
from embedchain.loaders.notion import NotionLoader
|
||||
|
||||
return NotionLoader()
|
||||
else:
|
||||
raise ValueError(f"Unsupported data type: {data_type}")
|
||||
loader_class: type = self._lazy_load(loaders[data_type])
|
||||
return loader_class()
|
||||
else:
|
||||
raise ValueError(f"Unsupported data type: {data_type}")
|
||||
|
||||
def _get_chunker(self, data_type: DataType, config: ChunkerConfig) -> BaseChunker:
|
||||
"""Returns the appropriate chunker for the given data type.
|
||||
|
||||
:param data_type: The type of the data to chunk.
|
||||
:type data_type: DataType
|
||||
:param config: Config to initialize the chunker with.
|
||||
:type config: ChunkerConfig
|
||||
:raises ValueError: If an unsupported data type is provided.
|
||||
:return: The chunker for the given data type.
|
||||
:rtype: BaseChunker
|
||||
"""
|
||||
"""Returns the appropriate chunker for the given data type (updated for lazy loading)."""
|
||||
chunker_classes = {
|
||||
DataType.YOUTUBE_VIDEO: YoutubeVideoChunker,
|
||||
DataType.PDF_FILE: PdfFileChunker,
|
||||
DataType.WEB_PAGE: WebPageChunker,
|
||||
DataType.QNA_PAIR: QnaPairChunker,
|
||||
DataType.TEXT: TextChunker,
|
||||
DataType.DOCX: DocxFileChunker,
|
||||
DataType.DOCS_SITE: DocsSiteChunker,
|
||||
DataType.SITEMAP: SitemapChunker,
|
||||
DataType.NOTION: NotionChunker,
|
||||
DataType.CSV: TableChunker,
|
||||
DataType.MDX: MdxChunker,
|
||||
DataType.IMAGES: ImagesChunker,
|
||||
DataType.XML: XmlChunker,
|
||||
DataType.UNSTRUCTURED: UnstructuredFileChunker,
|
||||
DataType.JSON: JSONChunker,
|
||||
DataType.OPENAPI: OpenAPIChunker,
|
||||
DataType.GMAIL: GmailChunker,
|
||||
DataType.YOUTUBE_VIDEO: "embedchain.chunkers.youtube_video.YoutubeVideoChunker",
|
||||
DataType.PDF_FILE: "embedchain.chunkers.pdf_file.PdfFileChunker",
|
||||
DataType.WEB_PAGE: "embedchain.chunkers.web_page.WebPageChunker",
|
||||
DataType.QNA_PAIR: "embedchain.chunkers.qna_pair.QnaPairChunker",
|
||||
DataType.TEXT: "embedchain.chunkers.text.TextChunker",
|
||||
DataType.DOCX: "embedchain.chunkers.docx_file.DocxFileChunker",
|
||||
DataType.SITEMAP: "embedchain.chunkers.sitemap.SitemapChunker",
|
||||
DataType.XML: "embedchain.chunkers.xml.XmlChunker",
|
||||
DataType.DOCS_SITE: "embedchain.chunkers.docs_site.DocsSiteChunker",
|
||||
DataType.CSV: "embedchain.chunkers.table.TableChunker",
|
||||
DataType.MDX: "embedchain.chunkers.mdx.MdxChunker",
|
||||
DataType.IMAGES: "embedchain.chunkers.images.ImagesChunker",
|
||||
DataType.UNSTRUCTURED: "embedchain.chunkers.unstructured_file.UnstructuredFileChunker",
|
||||
DataType.JSON: "embedchain.chunkers.json.JSONChunker",
|
||||
DataType.OPENAPI: "embedchain.chunkers.openapi.OpenAPIChunker",
|
||||
DataType.GMAIL: "embedchain.chunkers.gmail.GmailChunker",
|
||||
DataType.NOTION: "embedchain.chunkers.notion.NotionChunker",
|
||||
}
|
||||
|
||||
if data_type in chunker_classes:
|
||||
chunker_class: type = chunker_classes[data_type]
|
||||
chunker: BaseChunker = chunker_class(config)
|
||||
chunker_class = self._lazy_load(chunker_classes[data_type])
|
||||
chunker = chunker_class(config)
|
||||
chunker.set_data_type(data_type)
|
||||
return chunker
|
||||
else:
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
import hashlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
from langchain.docstore.document import Document
|
||||
from tenacity import retry, stop_after_attempt, wait_fixed
|
||||
|
||||
from embedchain.chunkers.base_chunker import BaseChunker
|
||||
from embedchain.config import AddConfig, BaseLlmConfig
|
||||
from embedchain.config import AddConfig, BaseLlmConfig, ChunkerConfig
|
||||
from embedchain.config.apps.base_app_config import BaseAppConfig
|
||||
from embedchain.data_formatter import DataFormatter
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
@@ -24,7 +19,8 @@ from embedchain.llm.base import BaseLlm
|
||||
from embedchain.loaders.base_loader import BaseLoader
|
||||
from embedchain.models.data_type import (DataType, DirectDataType,
|
||||
IndirectDataType, SpecialDataType)
|
||||
from embedchain.utils import detect_datatype
|
||||
from embedchain.telemetry.posthog import AnonymousTelemetry
|
||||
from embedchain.utils import detect_datatype, is_valid_json_string
|
||||
from embedchain.vectordb.base import BaseVectorDB
|
||||
|
||||
load_dotenv()
|
||||
@@ -88,12 +84,12 @@ class EmbedChain(JSONSerializable):
|
||||
# Attributes that aren't subclass related.
|
||||
self.user_asks = []
|
||||
|
||||
self.chunker: ChunkerConfig = None
|
||||
# Send anonymous telemetry
|
||||
self.s_id = self.config.id if self.config.id else str(uuid.uuid4())
|
||||
self.u_id = self._load_or_generate_user_id()
|
||||
|
||||
self._telemetry_props = {"class": self.__class__.__name__}
|
||||
self.telemetry = AnonymousTelemetry(enabled=self.config.collect_metrics)
|
||||
# Establish a connection to the SQLite database
|
||||
self.connection = sqlite3.connect(SQLITE_PATH)
|
||||
self.connection = sqlite3.connect(SQLITE_PATH, check_same_thread=False)
|
||||
self.cursor = self.connection.cursor()
|
||||
|
||||
# Create the 'data_sources' table if it doesn't exist
|
||||
@@ -111,12 +107,8 @@ class EmbedChain(JSONSerializable):
|
||||
"""
|
||||
)
|
||||
self.connection.commit()
|
||||
|
||||
# NOTE: Uncomment the next two lines when running tests to see if any test fires a telemetry event.
|
||||
# if (self.config.collect_metrics):
|
||||
# raise ConnectionRefusedError("Collection of metrics should not be allowed.")
|
||||
thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("init",))
|
||||
thread_telemetry.start()
|
||||
# Send anonymous telemetry
|
||||
self.telemetry.capture(event_name="init", properties=self._telemetry_props)
|
||||
|
||||
@property
|
||||
def collect_metrics(self):
|
||||
@@ -138,29 +130,6 @@ class EmbedChain(JSONSerializable):
|
||||
raise ValueError(f"Boolean value expected but got {type(value)}.")
|
||||
self.llm.online = value
|
||||
|
||||
def _load_or_generate_user_id(self) -> str:
|
||||
"""
|
||||
Loads the user id from the config file if it exists, otherwise generates a new
|
||||
one and saves it to the config file.
|
||||
|
||||
:return: user id
|
||||
:rtype: str
|
||||
"""
|
||||
if not os.path.exists(CONFIG_DIR):
|
||||
os.makedirs(CONFIG_DIR)
|
||||
|
||||
if os.path.exists(CONFIG_FILE):
|
||||
with open(CONFIG_FILE, "r") as f:
|
||||
data = json.load(f)
|
||||
if "user_id" in data:
|
||||
return data["user_id"]
|
||||
|
||||
u_id = str(uuid.uuid4())
|
||||
with open(CONFIG_FILE, "w") as f:
|
||||
json.dump({"user_id": u_id}, f)
|
||||
|
||||
return u_id
|
||||
|
||||
def add(
|
||||
self,
|
||||
source: Any,
|
||||
@@ -189,7 +158,11 @@ class EmbedChain(JSONSerializable):
|
||||
:return: source_hash, a md5-hash of the source, in hexadecimal representation.
|
||||
:rtype: str
|
||||
"""
|
||||
if config is None:
|
||||
if config is not None:
|
||||
pass
|
||||
elif self.chunker is not None:
|
||||
config = AddConfig(chunker=self.chunker)
|
||||
else:
|
||||
config = AddConfig()
|
||||
|
||||
try:
|
||||
@@ -207,11 +180,27 @@ class EmbedChain(JSONSerializable):
|
||||
if data_type:
|
||||
try:
|
||||
data_type = DataType(data_type)
|
||||
if data_type == DataType.JSON:
|
||||
if isinstance(source, str):
|
||||
if not is_valid_json_string(source):
|
||||
raise ValueError(
|
||||
f"Invalid json input: {source}",
|
||||
"Provide the correct JSON formatted source, \
|
||||
refer `https://docs.embedchain.ai/data-sources/json`",
|
||||
)
|
||||
elif not isinstance(source, str):
|
||||
raise ValueError(
|
||||
"Invaid content input. \
|
||||
If you want to upload (list, dict, etc.), do \
|
||||
`json.dump(data, indent=0)` and add the stringified JSON. \
|
||||
Check - `https://docs.embedchain.ai/data-sources/json`"
|
||||
)
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"Invalid data_type: '{data_type}'.",
|
||||
f"Please use one of the following: {[data_type.value for data_type in DataType]}",
|
||||
) from None
|
||||
|
||||
if not data_type:
|
||||
data_type = detect_datatype(source)
|
||||
|
||||
@@ -259,9 +248,14 @@ class EmbedChain(JSONSerializable):
|
||||
# it's quicker to check the variable twice than to count words when they won't be submitted.
|
||||
word_count = data_formatter.chunker.get_word_count(documents)
|
||||
|
||||
extra_metadata = {"data_type": data_type.value, "word_count": word_count, "chunks_count": new_chunks}
|
||||
thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("add", extra_metadata))
|
||||
thread_telemetry.start()
|
||||
# Send anonymous telemetry
|
||||
event_properties = {
|
||||
**self._telemetry_props,
|
||||
"data_type": data_type.value,
|
||||
"word_count": word_count,
|
||||
"chunks_count": new_chunks,
|
||||
}
|
||||
self.telemetry.capture(event_name="add", properties=event_properties)
|
||||
|
||||
return source_hash
|
||||
|
||||
@@ -314,6 +308,10 @@ class EmbedChain(JSONSerializable):
|
||||
# These types have a indirect source reference
|
||||
# As long as the reference is the same, they can be updated.
|
||||
where = {"url": src}
|
||||
if chunker.data_type == DataType.JSON and is_valid_json_string(src):
|
||||
url = hashlib.sha256((src).encode("utf-8")).hexdigest()
|
||||
where = {"url": url}
|
||||
|
||||
if self.config.id is not None:
|
||||
where.update({"app_id": self.config.id})
|
||||
|
||||
@@ -395,6 +393,10 @@ class EmbedChain(JSONSerializable):
|
||||
|
||||
# get existing ids, and discard doc if any common id exist.
|
||||
where = {"url": src}
|
||||
if chunker.data_type == DataType.JSON and is_valid_json_string(src):
|
||||
url = hashlib.sha256((src).encode("utf-8")).hexdigest()
|
||||
where = {"url": url}
|
||||
|
||||
# if data type is qna_pair, we check for question
|
||||
if chunker.data_type == DataType.QNA_PAIR:
|
||||
where = {"question": src[0]}
|
||||
@@ -465,7 +467,9 @@ class EmbedChain(JSONSerializable):
|
||||
)
|
||||
]
|
||||
|
||||
def retrieve_from_database(self, input_query: str, config: Optional[BaseLlmConfig] = None, where=None) -> List[str]:
|
||||
def retrieve_from_database(
|
||||
self, input_query: str, config: Optional[BaseLlmConfig] = None, where=None, citations: bool = False
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
Queries the vector database based on the given input query.
|
||||
Gets relevant doc based on the query
|
||||
@@ -476,6 +480,8 @@ class EmbedChain(JSONSerializable):
|
||||
:type config: Optional[BaseLlmConfig], optional
|
||||
:param where: A dictionary of key-value pairs to filter the database results, defaults to None
|
||||
:type where: _type_, optional
|
||||
:param citations: A boolean to indicate if db should fetch citation source
|
||||
:type citations: bool
|
||||
:return: List of contents of the document that matched your query
|
||||
:rtype: List[str]
|
||||
"""
|
||||
@@ -505,14 +511,19 @@ class EmbedChain(JSONSerializable):
|
||||
n_results=query_config.number_documents,
|
||||
where=where,
|
||||
skip_embedding=(hasattr(config, "query_type") and config.query_type == "Images"),
|
||||
citations=citations,
|
||||
)
|
||||
|
||||
if len(contexts) > 0 and isinstance(contexts[0], tuple):
|
||||
contexts = list(map(lambda x: x[0], contexts))
|
||||
|
||||
return contexts
|
||||
|
||||
def query(self, input_query: str, config: BaseLlmConfig = None, dry_run=False, where: Optional[Dict] = None) -> str:
|
||||
def query(
|
||||
self,
|
||||
input_query: str,
|
||||
config: BaseLlmConfig = None,
|
||||
dry_run=False,
|
||||
where: Optional[Dict] = None,
|
||||
**kwargs: Dict[str, Any],
|
||||
) -> Union[Tuple[str, List[Tuple[str, str, str]]], str]:
|
||||
"""
|
||||
Queries the vector database based on the given input query.
|
||||
Gets relevant doc based on the query and then passes it to an
|
||||
@@ -528,17 +539,31 @@ class EmbedChain(JSONSerializable):
|
||||
:type dry_run: bool, optional
|
||||
:param where: A dictionary of key-value pairs to filter the database results., defaults to None
|
||||
:type where: Optional[Dict[str, str]], optional
|
||||
:return: The answer to the query or the dry run result
|
||||
:rtype: str
|
||||
:param kwargs: To read more params for the query function. Ex. we use citations boolean
|
||||
param to return context along with the answer
|
||||
:type kwargs: Dict[str, Any]
|
||||
:return: The answer to the query, with citations if the citation flag is True
|
||||
or the dry run result
|
||||
:rtype: str, if citations is False, otherwise Tuple[str,List[Tuple[str,str,str]]]
|
||||
"""
|
||||
contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
|
||||
answer = self.llm.query(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
|
||||
citations = kwargs.get("citations", False)
|
||||
contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where, citations=citations)
|
||||
if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
|
||||
contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
|
||||
else:
|
||||
contexts_data_for_llm_query = contexts
|
||||
|
||||
answer = self.llm.query(
|
||||
input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
|
||||
)
|
||||
|
||||
# Send anonymous telemetry
|
||||
thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("query",))
|
||||
thread_telemetry.start()
|
||||
self.telemetry.capture(event_name="query", properties=self._telemetry_props)
|
||||
|
||||
return answer
|
||||
if citations:
|
||||
return answer, contexts
|
||||
else:
|
||||
return answer
|
||||
|
||||
def chat(
|
||||
self,
|
||||
@@ -546,6 +571,7 @@ class EmbedChain(JSONSerializable):
|
||||
config: Optional[BaseLlmConfig] = None,
|
||||
dry_run=False,
|
||||
where: Optional[Dict[str, str]] = None,
|
||||
**kwargs: Dict[str, Any],
|
||||
) -> str:
|
||||
"""
|
||||
Queries the vector database on the given input query.
|
||||
@@ -564,17 +590,31 @@ class EmbedChain(JSONSerializable):
|
||||
:type dry_run: bool, optional
|
||||
:param where: A dictionary of key-value pairs to filter the database results., defaults to None
|
||||
:type where: Optional[Dict[str, str]], optional
|
||||
:return: The answer to the query or the dry run result
|
||||
:rtype: str
|
||||
:param kwargs: To read more params for the query function. Ex. we use citations boolean
|
||||
param to return context along with the answer
|
||||
:type kwargs: Dict[str, Any]
|
||||
:return: The answer to the query, with citations if the citation flag is True
|
||||
or the dry run result
|
||||
:rtype: str, if citations is False, otherwise Tuple[str,List[Tuple[str,str,str]]]
|
||||
"""
|
||||
contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where)
|
||||
answer = self.llm.chat(input_query=input_query, contexts=contexts, config=config, dry_run=dry_run)
|
||||
citations = kwargs.get("citations", False)
|
||||
contexts = self.retrieve_from_database(input_query=input_query, config=config, where=where, citations=citations)
|
||||
if citations and len(contexts) > 0 and isinstance(contexts[0], tuple):
|
||||
contexts_data_for_llm_query = list(map(lambda x: x[0], contexts))
|
||||
else:
|
||||
contexts_data_for_llm_query = contexts
|
||||
|
||||
answer = self.llm.chat(
|
||||
input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
|
||||
)
|
||||
|
||||
# Send anonymous telemetry
|
||||
thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("chat",))
|
||||
thread_telemetry.start()
|
||||
self.telemetry.capture(event_name="chat", properties=self._telemetry_props)
|
||||
|
||||
return answer
|
||||
if citations:
|
||||
return answer, contexts
|
||||
else:
|
||||
return answer
|
||||
|
||||
def set_collection_name(self, name: str):
|
||||
"""
|
||||
@@ -608,34 +648,8 @@ class EmbedChain(JSONSerializable):
|
||||
Resets the database. Deletes all embeddings irreversibly.
|
||||
`App` does not have to be reinitialized after using this method.
|
||||
"""
|
||||
# Send anonymous telemetry
|
||||
thread_telemetry = threading.Thread(target=self._send_telemetry_event, args=("reset",))
|
||||
thread_telemetry.start()
|
||||
|
||||
self.db.reset()
|
||||
self.cursor.execute("DELETE FROM data_sources WHERE pipeline_id = ?", (self.config.id,))
|
||||
self.connection.commit()
|
||||
|
||||
@retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
|
||||
def _send_telemetry_event(self, method: str, extra_metadata: Optional[dict] = None):
|
||||
"""
|
||||
Send telemetry event to the embedchain server. This is anonymous. It can be toggled off in `AppConfig`.
|
||||
"""
|
||||
if not self.config.collect_metrics:
|
||||
return
|
||||
|
||||
with threading.Lock():
|
||||
url = "https://api.embedchain.ai/api/v1/telemetry/"
|
||||
metadata = {
|
||||
"s_id": self.s_id,
|
||||
"version": importlib.metadata.version(__package__ or __name__),
|
||||
"method": method,
|
||||
"language": "py",
|
||||
"u_id": self.u_id,
|
||||
}
|
||||
if extra_metadata:
|
||||
metadata.update(extra_metadata)
|
||||
|
||||
response = requests.post(url, json={"metadata": metadata})
|
||||
if response.status_code != 200:
|
||||
logging.warning(f"Telemetry event failed with status code {response.status_code}")
|
||||
# Send anonymous telemetry
|
||||
self.telemetry.capture(event_name="reset", properties=self._telemetry_props)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
Note that this file is copied from Chroma repository. We will remove this file once the fix in
|
||||
ChromaDB's repository.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from chromadb.api.types import Documents, Embeddings
|
||||
|
||||
|
||||
class OpenAIEmbeddingFunction:
|
||||
def __init__(
|
||||
self,
|
||||
api_key: Optional[str] = None,
|
||||
model_name: str = "text-embedding-ada-002",
|
||||
organization_id: Optional[str] = None,
|
||||
api_base: Optional[str] = None,
|
||||
api_type: Optional[str] = None,
|
||||
api_version: Optional[str] = None,
|
||||
deployment_id: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Initialize the OpenAIEmbeddingFunction.
|
||||
Args:
|
||||
api_key (str, optional): Your API key for the OpenAI API. If not
|
||||
provided, it will raise an error to provide an OpenAI API key.
|
||||
organization_id(str, optional): The OpenAI organization ID if applicable
|
||||
model_name (str, optional): The name of the model to use for text
|
||||
embeddings. Defaults to "text-embedding-ada-002".
|
||||
api_base (str, optional): The base path for the API. If not provided,
|
||||
it will use the base path for the OpenAI API. This can be used to
|
||||
point to a different deployment, such as an Azure deployment.
|
||||
api_type (str, optional): The type of the API deployment. This can be
|
||||
used to specify a different deployment, such as 'azure'. If not
|
||||
provided, it will use the default OpenAI deployment.
|
||||
api_version (str, optional): The api version for the API. If not provided,
|
||||
it will use the api version for the OpenAI API. This can be used to
|
||||
point to a different deployment, such as an Azure deployment.
|
||||
deployment_id (str, optional): Deployment ID for Azure OpenAI.
|
||||
|
||||
"""
|
||||
try:
|
||||
import openai
|
||||
except ImportError:
|
||||
raise ValueError("The openai python package is not installed. Please install it with `pip install openai`")
|
||||
|
||||
if api_key is not None:
|
||||
openai.api_key = api_key
|
||||
# If the api key is still not set, raise an error
|
||||
elif openai.api_key is None:
|
||||
raise ValueError(
|
||||
"Please provide an OpenAI API key. You can get one at https://platform.openai.com/account/api-keys"
|
||||
)
|
||||
|
||||
if api_base is not None:
|
||||
openai.api_base = api_base
|
||||
|
||||
if api_version is not None:
|
||||
openai.api_version = api_version
|
||||
|
||||
self._api_type = api_type
|
||||
if api_type is not None:
|
||||
openai.api_type = api_type
|
||||
|
||||
if organization_id is not None:
|
||||
openai.organization = organization_id
|
||||
|
||||
self._v1 = openai.__version__.startswith("1.")
|
||||
if self._v1:
|
||||
if api_type == "azure":
|
||||
self._client = openai.AzureOpenAI(
|
||||
api_key=api_key, api_version=api_version, azure_endpoint=api_base
|
||||
).embeddings
|
||||
else:
|
||||
self._client = openai.OpenAI(api_key=api_key, base_url=api_base).embeddings
|
||||
else:
|
||||
self._client = openai.Embedding
|
||||
self._model_name = model_name
|
||||
self._deployment_id = deployment_id
|
||||
|
||||
def __call__(self, input: Documents) -> Embeddings:
|
||||
# replace newlines, which can negatively affect performance.
|
||||
input = [t.replace("\n", " ") for t in input]
|
||||
|
||||
# Call the OpenAI Embedding API
|
||||
if self._v1:
|
||||
embeddings = self._client.create(input=input, model=self._deployment_id or self._model_name).data
|
||||
|
||||
# Sort resulting embeddings by index
|
||||
sorted_embeddings = sorted(embeddings, key=lambda e: e.index) # type: ignore
|
||||
|
||||
# Return just the embeddings
|
||||
return [result.embedding for result in sorted_embeddings]
|
||||
else:
|
||||
if self._api_type == "azure":
|
||||
embeddings = self._client.create(input=input, engine=self._deployment_id or self._model_name)["data"]
|
||||
else:
|
||||
embeddings = self._client.create(input=input, model=self._model_name)["data"]
|
||||
|
||||
# Sort resulting embeddings by index
|
||||
sorted_embeddings = sorted(embeddings, key=lambda e: e["index"]) # type: ignore
|
||||
|
||||
# Return just the embeddings
|
||||
return [result["embedding"] for result in sorted_embeddings]
|
||||
@@ -7,13 +7,7 @@ from embedchain.config import BaseEmbedderConfig
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
from embedchain.models import VectorDimensions
|
||||
|
||||
try:
|
||||
from chromadb.utils import embedding_functions
|
||||
except RuntimeError:
|
||||
from embedchain.utils import use_pysqlite3
|
||||
|
||||
use_pysqlite3()
|
||||
from chromadb.utils import embedding_functions
|
||||
from .chroma_embeddings import OpenAIEmbeddingFunction
|
||||
|
||||
|
||||
class OpenAIEmbedder(BaseEmbedder):
|
||||
@@ -30,11 +24,10 @@ class OpenAIEmbedder(BaseEmbedder):
|
||||
raise ValueError(
|
||||
"OPENAI_API_KEY or OPENAI_ORGANIZATION environment variables not provided"
|
||||
) # noqa:E501
|
||||
embedding_fn = embedding_functions.OpenAIEmbeddingFunction(
|
||||
embedding_fn = OpenAIEmbeddingFunction(
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
organization_id=os.getenv("OPENAI_ORGANIZATION"),
|
||||
model_name=self.config.model,
|
||||
)
|
||||
|
||||
self.set_embedding_fn(embedding_fn=embedding_fn)
|
||||
self.set_vector_dimension(vector_dimension=VectorDimensions.OPENAI.value)
|
||||
|
||||
@@ -13,7 +13,7 @@ class GPT4ALLLlm(BaseLlm):
|
||||
def __init__(self, config: Optional[BaseLlmConfig] = None):
|
||||
super().__init__(config=config)
|
||||
if self.config.model is None:
|
||||
self.config.model = "orca-mini-3b.ggmlv3.q4_0.bin"
|
||||
self.config.model = "orca-mini-3b-gguf2-q4_0.gguf"
|
||||
self.instance = GPT4ALLLlm._get_instance(self.config.model)
|
||||
self.instance.streaming = self.config.stream
|
||||
|
||||
|
||||
@@ -1,24 +1,65 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
from langchain.document_loaders.json_loader import \
|
||||
JSONLoader as LangchainJSONLoader
|
||||
import requests
|
||||
|
||||
from embedchain.loaders.base_loader import BaseLoader
|
||||
from embedchain.utils import clean_string, is_valid_json_string
|
||||
|
||||
langchain_json_jq_schema = 'to_entries | map("\(.key): \(.value|tostring)") | .[]'
|
||||
VALID_URL_PATTERN = "^https:\/\/[0-9A-z.]+.[0-9A-z.]+.[a-z]+\/.*\.json$"
|
||||
|
||||
|
||||
class JSONLoader(BaseLoader):
|
||||
@staticmethod
|
||||
def _get_llama_hub_loader():
|
||||
try:
|
||||
from llama_hub.jsondata.base import \
|
||||
JSONDataReader as LLHUBJSONLoader
|
||||
except ImportError as e:
|
||||
raise Exception(
|
||||
f"Failed to install required packages: {e}, \
|
||||
install them using `pip install --upgrade 'embedchain[json]`"
|
||||
)
|
||||
|
||||
return LLHUBJSONLoader()
|
||||
|
||||
@staticmethod
|
||||
def load_data(content):
|
||||
"""Load a json file. Each data point is a key value pair."""
|
||||
|
||||
loader = JSONLoader._get_llama_hub_loader()
|
||||
|
||||
data = []
|
||||
data_content = []
|
||||
loader = LangchainJSONLoader(content, text_content=False, jq_schema=langchain_json_jq_schema)
|
||||
docs = loader.load()
|
||||
|
||||
content_url_str = content
|
||||
|
||||
# Load json data from various sources.
|
||||
if os.path.isfile(content):
|
||||
with open(content, "r", encoding="utf-8") as json_file:
|
||||
json_data = json.load(json_file)
|
||||
elif re.match(VALID_URL_PATTERN, content):
|
||||
response = requests.get(content)
|
||||
if response.status_code == 200:
|
||||
json_data = response.json()
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Loading data from the given url: {content} failed. \
|
||||
Make sure the url is working."
|
||||
)
|
||||
elif is_valid_json_string(content):
|
||||
json_data = content
|
||||
content_url_str = hashlib.sha256((content).encode("utf-8")).hexdigest()
|
||||
else:
|
||||
raise ValueError(f"Invalid content to load json data from: {content}")
|
||||
|
||||
docs = loader.load_data(json_data)
|
||||
for doc in docs:
|
||||
meta_data = doc.metadata
|
||||
data.append({"content": doc.page_content, "meta_data": {"url": content, "row": meta_data["seq_num"]}})
|
||||
data_content.append(doc.page_content)
|
||||
doc_id = hashlib.sha256((content + ", ".join(data_content)).encode()).hexdigest()
|
||||
doc_content = clean_string(doc.text)
|
||||
data.append({"content": doc_content, "meta_data": {"url": content_url_str}})
|
||||
data_content.append(doc_content)
|
||||
|
||||
doc_id = hashlib.sha256((content_url_str + ", ".join(data_content)).encode()).hexdigest()
|
||||
return {"doc_id": doc_id, "data": data}
|
||||
|
||||
@@ -7,10 +7,9 @@ import uuid
|
||||
|
||||
import requests
|
||||
import yaml
|
||||
from fastapi import FastAPI, HTTPException
|
||||
|
||||
from embedchain import Client
|
||||
from embedchain.config import PipelineConfig
|
||||
from embedchain.config import ChunkerConfig, PipelineConfig
|
||||
from embedchain.embedchain import CONFIG_DIR, EmbedChain
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
from embedchain.embedder.openai import OpenAIEmbedder
|
||||
@@ -18,6 +17,8 @@ from embedchain.factory import EmbedderFactory, LlmFactory, VectorDBFactory
|
||||
from embedchain.helper.json_serializable import register_deserializable
|
||||
from embedchain.llm.base import BaseLlm
|
||||
from embedchain.llm.openai import OpenAILlm
|
||||
from embedchain.telemetry.posthog import AnonymousTelemetry
|
||||
from embedchain.utils import validate_yaml_config
|
||||
from embedchain.vectordb.base import BaseVectorDB
|
||||
from embedchain.vectordb.chroma import ChromaDB
|
||||
|
||||
@@ -41,8 +42,9 @@ class Pipeline(EmbedChain):
|
||||
embedding_model: BaseEmbedder = None,
|
||||
llm: BaseLlm = None,
|
||||
yaml_path: str = None,
|
||||
log_level=logging.INFO,
|
||||
log_level=logging.WARN,
|
||||
auto_deploy: bool = False,
|
||||
chunker: ChunkerConfig = None,
|
||||
):
|
||||
"""
|
||||
Initialize a new `App` instance.
|
||||
@@ -57,7 +59,7 @@ class Pipeline(EmbedChain):
|
||||
:type llm: BaseLlm, optional
|
||||
:param yaml_path: Path to the YAML configuration file, defaults to None
|
||||
:type yaml_path: str, optional
|
||||
:param log_level: Log level to use, defaults to logging.INFO
|
||||
:param log_level: Log level to use, defaults to logging.WARN
|
||||
:type log_level: int, optional
|
||||
:param auto_deploy: Whether to deploy the pipeline automatically, defaults to False
|
||||
:type auto_deploy: bool, optional
|
||||
@@ -83,6 +85,10 @@ class Pipeline(EmbedChain):
|
||||
# pipeline_id from the backend
|
||||
self.id = None
|
||||
|
||||
self.chunker = None
|
||||
if chunker:
|
||||
self.chunker = ChunkerConfig(**chunker)
|
||||
|
||||
self.config = config or PipelineConfig()
|
||||
self.name = self.config.name
|
||||
|
||||
@@ -109,11 +115,12 @@ class Pipeline(EmbedChain):
|
||||
self.llm = llm or OpenAILlm()
|
||||
self._init_db()
|
||||
|
||||
# setup user id and directory
|
||||
self.u_id = self._load_or_generate_user_id()
|
||||
# Send anonymous telemetry
|
||||
self._telemetry_props = {"class": self.__class__.__name__}
|
||||
self.telemetry = AnonymousTelemetry(enabled=self.config.collect_metrics)
|
||||
|
||||
# Establish a connection to the SQLite database
|
||||
self.connection = sqlite3.connect(SQLITE_PATH)
|
||||
self.connection = sqlite3.connect(SQLITE_PATH, check_same_thread=False)
|
||||
self.cursor = self.connection.cursor()
|
||||
|
||||
# Create the 'data_sources' table if it doesn't exist
|
||||
@@ -131,8 +138,10 @@ class Pipeline(EmbedChain):
|
||||
"""
|
||||
)
|
||||
self.connection.commit()
|
||||
# Send anonymous telemetry
|
||||
self.telemetry.capture(event_name="init", properties=self._telemetry_props)
|
||||
|
||||
self.user_asks = [] # legacy defaults
|
||||
self.user_asks = []
|
||||
if self.auto_deploy:
|
||||
self.deploy()
|
||||
|
||||
@@ -219,15 +228,29 @@ class Pipeline(EmbedChain):
|
||||
"""
|
||||
Search for similar documents related to the query in the vector database.
|
||||
"""
|
||||
# Send anonymous telemetry
|
||||
self.telemetry.capture(event_name="search", properties=self._telemetry_props)
|
||||
|
||||
# TODO: Search will call the endpoint rather than fetching the data from the db itself when deploy=True.
|
||||
if self.id is None:
|
||||
where = {"app_id": self.local_id}
|
||||
return self.db.query(
|
||||
context = self.db.query(
|
||||
query,
|
||||
n_results=num_documents,
|
||||
where=where,
|
||||
skip_embedding=False,
|
||||
citations=True,
|
||||
)
|
||||
result = []
|
||||
for c in context:
|
||||
result.append(
|
||||
{
|
||||
"context": c[0],
|
||||
"source": c[1],
|
||||
"document_id": c[2],
|
||||
}
|
||||
)
|
||||
return result
|
||||
else:
|
||||
# Make API call to the backend to get the results
|
||||
NotImplementedError("Search is not implemented yet for the prod mode.")
|
||||
@@ -295,6 +318,15 @@ class Pipeline(EmbedChain):
|
||||
)
|
||||
self.connection.commit()
|
||||
|
||||
def get_data_sources(self):
|
||||
db_data = self.cursor.execute("SELECT * FROM data_sources WHERE pipeline_id = ?", (self.local_id,)).fetchall()
|
||||
|
||||
data_sources = []
|
||||
for data in db_data:
|
||||
data_sources.append({"data_type": data[2], "data_value": data[3], "metadata": data[4]})
|
||||
|
||||
return data_sources
|
||||
|
||||
def deploy(self):
|
||||
if self.client is None:
|
||||
self._init_client()
|
||||
@@ -312,6 +344,9 @@ class Pipeline(EmbedChain):
|
||||
data_hash, data_type, data_value = result[1], result[2], result[3]
|
||||
self._process_and_upload_data(data_hash, data_type, data_value)
|
||||
|
||||
# Send anonymous telemetry
|
||||
self.telemetry.capture(event_name="deploy", properties=self._telemetry_props)
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, yaml_path: str, auto_deploy: bool = False):
|
||||
"""
|
||||
@@ -327,10 +362,16 @@ class Pipeline(EmbedChain):
|
||||
with open(yaml_path, "r") as file:
|
||||
config_data = yaml.safe_load(file)
|
||||
|
||||
pipeline_config_data = config_data.get("pipeline", {}).get("config", {})
|
||||
try:
|
||||
validate_yaml_config(config_data)
|
||||
except Exception as e:
|
||||
raise Exception(f"❌ Error occurred while validating the YAML config. Error: {str(e)}")
|
||||
|
||||
pipeline_config_data = config_data.get("app", {}).get("config", {})
|
||||
db_config_data = config_data.get("vectordb", {})
|
||||
embedding_model_config_data = config_data.get("embedding_model", {})
|
||||
embedding_model_config_data = config_data.get("embedding_model", config_data.get("embedder", {}))
|
||||
llm_config_data = config_data.get("llm", {})
|
||||
chunker_config_data = config_data.get("chunker", {})
|
||||
|
||||
pipeline_config = PipelineConfig(**pipeline_config_data)
|
||||
|
||||
@@ -347,6 +388,11 @@ class Pipeline(EmbedChain):
|
||||
embedding_model = EmbedderFactory.create(
|
||||
embedding_model_provider, embedding_model_config_data.get("config", {})
|
||||
)
|
||||
|
||||
# Send anonymous telemetry
|
||||
event_properties = {"init_type": "yaml_config"}
|
||||
AnonymousTelemetry().capture(event_name="init", properties=event_properties)
|
||||
|
||||
return cls(
|
||||
config=pipeline_config,
|
||||
llm=llm,
|
||||
@@ -354,34 +400,5 @@ class Pipeline(EmbedChain):
|
||||
embedding_model=embedding_model,
|
||||
yaml_path=yaml_path,
|
||||
auto_deploy=auto_deploy,
|
||||
chunker=chunker_config_data,
|
||||
)
|
||||
|
||||
def start(self, host="0.0.0.0", port=8000):
|
||||
app = FastAPI()
|
||||
|
||||
@app.post("/add")
|
||||
async def add_document(data_value: str, data_type: str = None):
|
||||
"""
|
||||
Add a document to the pipeline.
|
||||
"""
|
||||
try:
|
||||
document = {"data_value": data_value, "data_type": data_type}
|
||||
self.add(document)
|
||||
return {"message": "Document added successfully"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.post("/query")
|
||||
async def query_documents(query: str, num_documents: int = 3):
|
||||
"""
|
||||
Query for similar documents in the pipeline.
|
||||
"""
|
||||
try:
|
||||
results = self.search(query, num_documents)
|
||||
return results
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host=host, port=port)
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
from openai import OpenAI
|
||||
from openai.types.beta.threads import MessageContentText, ThreadMessage
|
||||
|
||||
from embedchain.config import AddConfig
|
||||
from embedchain.data_formatter import DataFormatter
|
||||
from embedchain.models.data_type import DataType
|
||||
from embedchain.utils import detect_datatype
|
||||
|
||||
logging.basicConfig(level=logging.WARN)
|
||||
|
||||
|
||||
class OpenAIAssistant:
|
||||
def __init__(
|
||||
self,
|
||||
name=None,
|
||||
instructions=None,
|
||||
tools=None,
|
||||
thread_id=None,
|
||||
model="gpt-4-1106-preview",
|
||||
data_sources=None,
|
||||
assistant_id=None,
|
||||
log_level=logging.WARN,
|
||||
):
|
||||
self.name = name or "OpenAI Assistant"
|
||||
self.instructions = instructions
|
||||
self.tools = tools or [{"type": "retrieval"}]
|
||||
self.model = model
|
||||
self.data_sources = data_sources or []
|
||||
self.log_level = log_level
|
||||
self._client = OpenAI()
|
||||
self._initialize_assistant(assistant_id)
|
||||
self.thread_id = thread_id or self._create_thread()
|
||||
|
||||
def add(self, source, data_type=None):
|
||||
file_path = self._prepare_source_path(source, data_type)
|
||||
self._add_file_to_assistant(file_path)
|
||||
logging.info("Data successfully added to the assistant.")
|
||||
|
||||
def chat(self, message):
|
||||
self._send_message(message)
|
||||
return self._get_latest_response()
|
||||
|
||||
def delete_thread(self):
|
||||
self._client.beta.threads.delete(self.thread_id)
|
||||
self.thread_id = self._create_thread()
|
||||
|
||||
# Internal methods
|
||||
def _initialize_assistant(self, assistant_id):
|
||||
file_ids = self._generate_file_ids(self.data_sources)
|
||||
self.assistant = (
|
||||
self._client.beta.assistants.retrieve(assistant_id)
|
||||
if assistant_id
|
||||
else self._client.beta.assistants.create(
|
||||
name=self.name, model=self.model, file_ids=file_ids, instructions=self.instructions, tools=self.tools
|
||||
)
|
||||
)
|
||||
|
||||
def _create_thread(self):
|
||||
thread = self._client.beta.threads.create()
|
||||
return thread.id
|
||||
|
||||
def _prepare_source_path(self, source, data_type=None):
|
||||
if Path(source).is_file():
|
||||
return source
|
||||
data_type = data_type or detect_datatype(source)
|
||||
formatter = DataFormatter(data_type=DataType(data_type), config=AddConfig())
|
||||
data = formatter.loader.load_data(source)["data"]
|
||||
return self._save_temp_data(data[0]["content"].encode())
|
||||
|
||||
def _add_file_to_assistant(self, file_path):
|
||||
file_obj = self._client.files.create(file=open(file_path, "rb"), purpose="assistants")
|
||||
self._client.beta.assistants.files.create(assistant_id=self.assistant.id, file_id=file_obj.id)
|
||||
|
||||
def _generate_file_ids(self, data_sources):
|
||||
return [
|
||||
self._add_file_to_assistant(self._prepare_source_path(ds["source"], ds.get("data_type")))
|
||||
for ds in data_sources
|
||||
]
|
||||
|
||||
def _send_message(self, message):
|
||||
self._client.beta.threads.messages.create(thread_id=self.thread_id, role="user", content=message)
|
||||
self._wait_for_completion()
|
||||
|
||||
def _wait_for_completion(self):
|
||||
run = self._client.beta.threads.runs.create(
|
||||
thread_id=self.thread_id,
|
||||
assistant_id=self.assistant.id,
|
||||
instructions=self.instructions,
|
||||
)
|
||||
run_id = run.id
|
||||
run_status = run.status
|
||||
|
||||
while run_status in ["queued", "in_progress", "requires_action"]:
|
||||
time.sleep(0.1) # Sleep before making the next API call to avoid hitting rate limits
|
||||
run = self._client.beta.threads.runs.retrieve(thread_id=self.thread_id, run_id=run_id)
|
||||
run_status = run.status
|
||||
if run_status == "failed":
|
||||
raise ValueError(f"Thread run failed with the following error: {run.last_error}")
|
||||
|
||||
def _get_latest_response(self):
|
||||
history = self._get_history()
|
||||
return self._format_message(history[0]) if history else None
|
||||
|
||||
def _get_history(self):
|
||||
messages = self._client.beta.threads.messages.list(thread_id=self.thread_id, order="desc")
|
||||
return list(messages)
|
||||
|
||||
def _format_message(self, thread_message):
|
||||
thread_message = cast(ThreadMessage, thread_message)
|
||||
content = [c.text.value for c in thread_message.content if isinstance(c, MessageContentText)]
|
||||
return " ".join(content)
|
||||
|
||||
def _save_temp_data(self, data):
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
file_path = os.path.join(temp_dir, "temp_data")
|
||||
with open(file_path, "wb") as file:
|
||||
file.write(data)
|
||||
return file_path
|
||||
@@ -0,0 +1,67 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from posthog import Posthog
|
||||
|
||||
import embedchain
|
||||
|
||||
HOME_DIR = str(Path.home())
|
||||
CONFIG_DIR = os.path.join(HOME_DIR, ".embedchain")
|
||||
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AnonymousTelemetry:
|
||||
def __init__(self, host="https://app.posthog.com", enabled=True):
|
||||
self.project_api_key = "phc_PHQDA5KwztijnSojsxJ2c1DuJd52QCzJzT2xnSGvjN2"
|
||||
self.host = host
|
||||
self.posthog = Posthog(project_api_key=self.project_api_key, host=self.host)
|
||||
self.user_id = self.get_user_id()
|
||||
self.enabled = enabled
|
||||
|
||||
# Check if telemetry tracking is disabled via environment variable
|
||||
if "EC_TELEMETRY" in os.environ and os.environ["EC_TELEMETRY"].lower() not in [
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
]:
|
||||
self.enabled = False
|
||||
|
||||
if not self.enabled:
|
||||
self.posthog.disabled = True
|
||||
|
||||
# Silence posthog logging
|
||||
posthog_logger = logging.getLogger("posthog")
|
||||
posthog_logger.disabled = True
|
||||
|
||||
def get_user_id(self):
|
||||
if not os.path.exists(CONFIG_DIR):
|
||||
os.makedirs(CONFIG_DIR)
|
||||
|
||||
if os.path.exists(CONFIG_FILE):
|
||||
with open(CONFIG_FILE, "r") as f:
|
||||
data = json.load(f)
|
||||
if "user_id" in data:
|
||||
return data["user_id"]
|
||||
|
||||
user_id = str(uuid.uuid4())
|
||||
with open(CONFIG_FILE, "w") as f:
|
||||
json.dump({"user_id": user_id}, f)
|
||||
return user_id
|
||||
|
||||
def capture(self, event_name, properties=None):
|
||||
default_properties = {
|
||||
"version": embedchain.__version__,
|
||||
"language": "python",
|
||||
"pid": os.getpid(),
|
||||
}
|
||||
properties.update(default_properties)
|
||||
|
||||
try:
|
||||
self.posthog.capture(self.user_id, event_name, properties)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send telemetry {event_name=}")
|
||||
@@ -1,9 +1,12 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import string
|
||||
from typing import Any
|
||||
|
||||
from schema import Optional, Or, Schema
|
||||
|
||||
from embedchain.models.data_type import DataType
|
||||
|
||||
|
||||
@@ -261,6 +264,99 @@ def detect_datatype(source: Any) -> DataType:
|
||||
|
||||
# TODO: check if source is gmail query
|
||||
|
||||
# check if the source is valid json string
|
||||
if is_valid_json_string(source):
|
||||
logging.debug(f"Source of `{formatted_source}` detected as `json`.")
|
||||
return DataType.JSON
|
||||
|
||||
# Use text as final fallback.
|
||||
logging.debug(f"Source of `{formatted_source}` detected as `text`.")
|
||||
return DataType.TEXT
|
||||
|
||||
|
||||
# check if the source is valid json string
|
||||
def is_valid_json_string(source: str):
|
||||
try:
|
||||
_ = json.loads(source)
|
||||
return True
|
||||
except json.JSONDecodeError:
|
||||
logging.error(
|
||||
"Insert valid string format of JSON. \
|
||||
Check the docs to see the supported formats - `https://docs.embedchain.ai/data-sources/json`"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def validate_yaml_config(config_data):
|
||||
schema = Schema(
|
||||
{
|
||||
Optional("app"): {
|
||||
Optional("config"): {
|
||||
Optional("id"): str,
|
||||
Optional("name"): str,
|
||||
Optional("log_level"): Or("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
|
||||
Optional("collect_metrics"): bool,
|
||||
Optional("collection_name"): str,
|
||||
}
|
||||
},
|
||||
Optional("llm"): {
|
||||
Optional("provider"): Or(
|
||||
"openai",
|
||||
"azure_openai",
|
||||
"anthropic",
|
||||
"huggingface",
|
||||
"cohere",
|
||||
"gpt4all",
|
||||
"jina",
|
||||
"llama2",
|
||||
"vertex_ai",
|
||||
),
|
||||
Optional("config"): {
|
||||
Optional("model"): str,
|
||||
Optional("number_documents"): int,
|
||||
Optional("temperature"): float,
|
||||
Optional("max_tokens"): int,
|
||||
Optional("top_p"): Or(float, int),
|
||||
Optional("stream"): bool,
|
||||
Optional("template"): str,
|
||||
Optional("system_prompt"): str,
|
||||
Optional("deployment_name"): str,
|
||||
Optional("where"): dict,
|
||||
Optional("query_type"): str,
|
||||
},
|
||||
},
|
||||
Optional("vectordb"): {
|
||||
Optional("provider"): Or(
|
||||
"chroma", "elasticsearch", "opensearch", "pinecone", "qdrant", "weaviate", "zilliz"
|
||||
),
|
||||
Optional("config"): {
|
||||
Optional("collection_name"): str,
|
||||
Optional("dir"): str,
|
||||
Optional("allow_reset"): bool,
|
||||
Optional("host"): str,
|
||||
Optional("port"): str,
|
||||
},
|
||||
},
|
||||
Optional("embedder"): {
|
||||
Optional("provider"): Or("openai", "gpt4all", "huggingface", "vertexai"),
|
||||
Optional("config"): {
|
||||
Optional("model"): Optional(str),
|
||||
Optional("deployment_name"): Optional(str),
|
||||
},
|
||||
},
|
||||
Optional("embedding_model"): {
|
||||
Optional("provider"): Or("openai", "gpt4all", "huggingface", "vertexai"),
|
||||
Optional("config"): {
|
||||
Optional("model"): str,
|
||||
Optional("deployment_name"): str,
|
||||
},
|
||||
},
|
||||
Optional("chunker"): {
|
||||
Optional("chunk_size"): int,
|
||||
Optional("chunk_overlap"): int,
|
||||
Optional("length_function"): str,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
return schema.validate(config_data)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
from chromadb import Collection, QueryResult
|
||||
from langchain.docstore.document import Document
|
||||
@@ -38,7 +38,7 @@ class ChromaDB(BaseVectorDB):
|
||||
else:
|
||||
self.config = ChromaDbConfig()
|
||||
|
||||
self.settings = Settings()
|
||||
self.settings = Settings(anonymized_telemetry=False)
|
||||
self.settings.allow_reset = self.config.allow_reset if hasattr(self.config, "allow_reset") else False
|
||||
if self.config.chroma_settings:
|
||||
for key, value in self.config.chroma_settings.items():
|
||||
@@ -192,8 +192,13 @@ class ChromaDB(BaseVectorDB):
|
||||
]
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
Query contents from vector database based on vector similarity
|
||||
|
||||
@@ -205,9 +210,12 @@ class ChromaDB(BaseVectorDB):
|
||||
:type where: Dict[str, Any]
|
||||
:param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
|
||||
:type skip_embedding: bool
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:raises InvalidDimensionException: Dimensions do not match.
|
||||
:return: The content of the document that matched your query, url of the source, doc_id
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
try:
|
||||
if skip_embedding:
|
||||
@@ -236,10 +244,13 @@ class ChromaDB(BaseVectorDB):
|
||||
contexts = []
|
||||
for result in results_formatted:
|
||||
context = result[0].page_content
|
||||
metadata = result[0].metadata
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contexts.append((context, source, doc_id))
|
||||
if citations:
|
||||
metadata = result[0].metadata
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contexts.append((context, source, doc_id))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def set_collection_name(self, name: str):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
try:
|
||||
from elasticsearch import Elasticsearch
|
||||
@@ -136,8 +136,13 @@ class ElasticsearchDB(BaseVectorDB):
|
||||
self.client.indices.refresh(index=self._get_index())
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
query contents from vector data base based on vector similarity
|
||||
|
||||
@@ -150,8 +155,11 @@ class ElasticsearchDB(BaseVectorDB):
|
||||
:param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
|
||||
:type skip_embedding: bool
|
||||
:return: The context of the document that matched your query, url of the source, doc_id
|
||||
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
if skip_embedding:
|
||||
query_vector = input_query
|
||||
@@ -175,14 +183,17 @@ class ElasticsearchDB(BaseVectorDB):
|
||||
_source = ["text", "metadata.url", "metadata.doc_id"]
|
||||
response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
|
||||
docs = response["hits"]["hits"]
|
||||
contents = []
|
||||
contexts = []
|
||||
for doc in docs:
|
||||
context = doc["_source"]["text"]
|
||||
metadata = doc["_source"]["metadata"]
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contents.append(tuple((context, source, doc_id)))
|
||||
return contents
|
||||
if citations:
|
||||
metadata = doc["_source"]["metadata"]
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contexts.append(tuple((context, source, doc_id)))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def set_collection_name(self, name: str):
|
||||
"""
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
from typing import Dict, List, Optional, Set, Tuple, Union
|
||||
|
||||
try:
|
||||
from opensearchpy import OpenSearch
|
||||
@@ -146,8 +146,13 @@ class OpenSearchDB(BaseVectorDB):
|
||||
self.client.indices.refresh(index=self._get_index())
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
query contents from vector data base based on vector similarity
|
||||
|
||||
@@ -159,8 +164,11 @@ class OpenSearchDB(BaseVectorDB):
|
||||
:type where: Dict[str, any]
|
||||
:param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
|
||||
:type skip_embedding: bool
|
||||
:return: The content of the document that matched your query, url of the source, doc_id
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
# TODO(rupeshbansal, deshraj): Add support for skip embeddings here if already exists
|
||||
embeddings = OpenAIEmbeddings()
|
||||
@@ -188,13 +196,16 @@ class OpenSearchDB(BaseVectorDB):
|
||||
k=n_results,
|
||||
)
|
||||
|
||||
contents = []
|
||||
contexts = []
|
||||
for doc in docs:
|
||||
context = doc.page_content
|
||||
source = doc.metadata["url"]
|
||||
doc_id = doc.metadata["doc_id"]
|
||||
contents.append(tuple((context, source, doc_id)))
|
||||
return contents
|
||||
if citations:
|
||||
source = doc.metadata["url"]
|
||||
doc_id = doc.metadata["doc_id"]
|
||||
contexts.append(tuple((context, source, doc_id)))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def set_collection_name(self, name: str):
|
||||
"""
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
try:
|
||||
import pinecone
|
||||
@@ -119,8 +119,13 @@ class PineconeDB(BaseVectorDB):
|
||||
self.client.upsert(docs[i : i + self.BATCH_SIZE])
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
query contents from vector database based on vector similarity
|
||||
:param input_query: list of query string
|
||||
@@ -131,22 +136,28 @@ class PineconeDB(BaseVectorDB):
|
||||
:type where: Dict[str, any]
|
||||
:param skip_embedding: Optional. if True, input_query is already embedded
|
||||
:type skip_embedding: bool
|
||||
:return: The content of the document that matched your query, url of the source, doc_id
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
if not skip_embedding:
|
||||
query_vector = self.embedder.embedding_fn([input_query])[0]
|
||||
else:
|
||||
query_vector = input_query
|
||||
data = self.client.query(vector=query_vector, filter=where, top_k=n_results, include_metadata=True)
|
||||
contents = []
|
||||
contexts = []
|
||||
for doc in data["matches"]:
|
||||
metadata = doc["metadata"]
|
||||
context = metadata["text"]
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contents.append(tuple((context, source, doc_id)))
|
||||
return contents
|
||||
if citations:
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contexts.append(tuple((context, source, doc_id)))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def set_collection_name(self, name: str):
|
||||
"""
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import copy
|
||||
import os
|
||||
import uuid
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
try:
|
||||
from qdrant_client import QdrantClient
|
||||
@@ -161,8 +161,13 @@ class QdrantDB(BaseVectorDB):
|
||||
)
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
query contents from vector database based on vector similarity
|
||||
:param input_query: list of query string
|
||||
@@ -174,8 +179,11 @@ class QdrantDB(BaseVectorDB):
|
||||
:param skip_embedding: A boolean flag indicating if the embedding for the documents to be added is to be
|
||||
generated or not
|
||||
:type skip_embedding: bool
|
||||
:return: The context of the document that matched your query, url of the source, doc_id
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
if not skip_embedding:
|
||||
query_vector = self.embedder.embedding_fn([input_query])[0]
|
||||
@@ -202,14 +210,17 @@ class QdrantDB(BaseVectorDB):
|
||||
limit=n_results,
|
||||
)
|
||||
|
||||
response = []
|
||||
contexts = []
|
||||
for result in results:
|
||||
context = result.payload["text"]
|
||||
metadata = result.payload["metadata"]
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
response.append(tuple((context, source, doc_id)))
|
||||
return response
|
||||
if citations:
|
||||
metadata = result.payload["metadata"]
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contexts.append(tuple((context, source, doc_id)))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def count(self) -> int:
|
||||
response = self.client.get_collection(collection_name=self.collection_name)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import copy
|
||||
import os
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
try:
|
||||
import weaviate
|
||||
@@ -58,10 +58,14 @@ class WeaviateDB(BaseVectorDB):
|
||||
raise ValueError("Embedder not set. Please set an embedder with `set_embedder` before initialization.")
|
||||
|
||||
self.index_name = self._get_index_name()
|
||||
self.metadata_keys = {"data_type", "doc_id", "url", "hash", "app_id", "text"}
|
||||
self.metadata_keys = {"data_type", "doc_id", "url", "hash", "app_id"}
|
||||
if not self.client.schema.exists(self.index_name):
|
||||
# id is a reserved field in Weaviate, hence we had to change the name of the id field to identifier
|
||||
# The none vectorizer is crucial as we have our own custom embedding function
|
||||
"""
|
||||
TODO: wait for weaviate to add indexing on `object[]` data-type so that we can add filter while querying.
|
||||
Once that is done, change `dataType` of "metadata" field to `object[]` and update the query below.
|
||||
"""
|
||||
class_obj = {
|
||||
"classes": [
|
||||
{
|
||||
@@ -106,10 +110,6 @@ class WeaviateDB(BaseVectorDB):
|
||||
"name": "app_id",
|
||||
"dataType": ["text"],
|
||||
},
|
||||
{
|
||||
"name": "text",
|
||||
"dataType": ["text"],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -195,8 +195,13 @@ class WeaviateDB(BaseVectorDB):
|
||||
batch.add_reference(obj_uuid, self.index_name, "metadata", metadata_uuid, self.index_name + "_metadata")
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
query contents from vector database based on vector similarity
|
||||
:param input_query: list of query string
|
||||
@@ -208,15 +213,23 @@ class WeaviateDB(BaseVectorDB):
|
||||
:param skip_embedding: A boolean flag indicating if the embedding for the documents to be added is to be
|
||||
generated or not
|
||||
:type skip_embedding: bool
|
||||
:return: The context of the document that matched your query, url of the source, doc_id
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
if not skip_embedding:
|
||||
query_vector = self.embedder.embedding_fn([input_query])[0]
|
||||
else:
|
||||
query_vector = input_query
|
||||
|
||||
keys = set(where.keys() if where is not None else set())
|
||||
data_fields = ["text"]
|
||||
|
||||
if citations:
|
||||
data_fields.append(weaviate.LinkTo("metadata", self.index_name + "_metadata", list(self.metadata_keys)))
|
||||
|
||||
if len(keys.intersection(self.metadata_keys)) != 0:
|
||||
weaviate_where_operands = []
|
||||
for key in keys:
|
||||
@@ -247,7 +260,18 @@ class WeaviateDB(BaseVectorDB):
|
||||
.with_limit(n_results)
|
||||
.do()
|
||||
)
|
||||
contexts = results["data"]["Get"].get(self.index_name)
|
||||
|
||||
docs = results["data"]["Get"].get(self.index_name)
|
||||
contexts = []
|
||||
for doc in docs:
|
||||
context = doc["text"]
|
||||
if citations:
|
||||
metadata = doc["metadata"][0]
|
||||
source = metadata["url"]
|
||||
doc_id = metadata["doc_id"]
|
||||
contexts.append((context, source, doc_id))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def set_collection_name(self, name: str):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
from embedchain.config import ZillizDBConfig
|
||||
from embedchain.helper.json_serializable import register_deserializable
|
||||
@@ -127,8 +127,13 @@ class ZillizVectorDB(BaseVectorDB):
|
||||
self.client.flush(self.config.collection_name)
|
||||
|
||||
def query(
|
||||
self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
self,
|
||||
input_query: List[str],
|
||||
n_results: int,
|
||||
where: Dict[str, any],
|
||||
skip_embedding: bool,
|
||||
citations: bool = False,
|
||||
) -> Union[List[Tuple[str, str, str]], List[str]]:
|
||||
"""
|
||||
Query contents from vector data base based on vector similarity
|
||||
|
||||
@@ -139,8 +144,11 @@ class ZillizVectorDB(BaseVectorDB):
|
||||
:param where: to filter data
|
||||
:type where: str
|
||||
:raises InvalidDimensionException: Dimensions do not match.
|
||||
:return: The context of the document that matched your query, url of the source, doc_id
|
||||
:rtype: List[Tuple[str,str,str]]
|
||||
:param citations: we use citations boolean param to return context along with the answer.
|
||||
:type citations: bool, default is False.
|
||||
:return: The content of the document that matched your query,
|
||||
along with url of the source and doc_id (if citations flag is true)
|
||||
:rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
|
||||
"""
|
||||
|
||||
if self.collection.is_empty:
|
||||
@@ -170,14 +178,17 @@ class ZillizVectorDB(BaseVectorDB):
|
||||
output_fields=output_fields,
|
||||
)
|
||||
|
||||
doc_list = []
|
||||
contexts = []
|
||||
for query in query_result:
|
||||
data = query[0]["entity"]
|
||||
context = data["text"]
|
||||
source = data["url"]
|
||||
doc_id = data["doc_id"]
|
||||
doc_list.append(tuple((context, source, doc_id)))
|
||||
return doc_list
|
||||
if citations:
|
||||
source = data["url"]
|
||||
doc_id = data["doc_id"]
|
||||
contexts.append(tuple((context, source, doc_id)))
|
||||
else:
|
||||
contexts.append(context)
|
||||
return contexts
|
||||
|
||||
def count(self) -> int:
|
||||
"""
|
||||
@@ -211,3 +222,16 @@ class ZillizVectorDB(BaseVectorDB):
|
||||
if not isinstance(name, str):
|
||||
raise TypeError("Collection name must be a string")
|
||||
self.config.collection_name = name
|
||||
|
||||
def delete(self, keys: Union[list, str, int]):
|
||||
"""
|
||||
Delete the embeddings from DB. Zilliz only support deleting with keys.
|
||||
|
||||
|
||||
:param keys: Primary keys of the table entries to delete.
|
||||
:type keys: Union[list, str, int]
|
||||
"""
|
||||
self.client.delete(
|
||||
collection_name=self.config.collection_name,
|
||||
pks=keys,
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM python:3.11 AS backend
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /usr/src/discord_bot
|
||||
COPY requirements.txt .
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
# Discord Bot
|
||||
|
||||
This is a docker template to create your own Discord bot using the embedchain package. To know more about the bot and how to use it, go [here](https://docs.embedchain.ai/examples/discord_bot).
|
||||
This is a docker template to create your own Discord bot using the embedchain package. To know more about the bot and how to use it, go [here](https://docs.embedchain.ai/examples/discord_bot).
|
||||
|
||||
To run this use the following command,
|
||||
|
||||
```bash
|
||||
docker run --name discord-bot -e OPENAI_API_KEY=sk-xxx -e DISCORD_BOT_TOKEN=xxx -p 8080:8080 embedchain/discord-bot:latest
|
||||
```
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM python:3.11 AS backend
|
||||
FROM python:3.11-slim AS backend
|
||||
|
||||
WORKDIR /usr/src/app/backend
|
||||
COPY requirements.txt .
|
||||
|
||||
@@ -2,20 +2,22 @@ version: "3.9"
|
||||
|
||||
services:
|
||||
backend:
|
||||
container_name: embedchain_backend
|
||||
container_name: embedchain-backend
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: backend
|
||||
dockerfile: Dockerfile
|
||||
image: embedchain/backend
|
||||
ports:
|
||||
- "8000:8000"
|
||||
|
||||
frontend:
|
||||
container_name: embedchain_frontend
|
||||
container_name: embedchain-frontend
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: frontend
|
||||
dockerfile: Dockerfile
|
||||
image: embedchain/frontend
|
||||
ports:
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM node:18 AS frontend
|
||||
FROM node:18-slim AS frontend
|
||||
|
||||
WORKDIR /usr/src/app/frontend
|
||||
COPY package.json .
|
||||
|
||||
@@ -1,24 +1,10 @@
|
||||
<svg
|
||||
fill="currentColor"
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
viewBox="0 0 512 512"
|
||||
xml:space="preserve"
|
||||
>
|
||||
<g id="SVGRepo_bgCarrier" stroke-width="0"></g>
|
||||
<g
|
||||
id="SVGRepo_tracerCarrier"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
></g>
|
||||
<g id="SVGRepo_iconCarrier">
|
||||
<g id="7935ec95c421cee6d86eb22ecd12f847">
|
||||
<path
|
||||
style="display: inline;"
|
||||
d="M459.186,151.787c0.203,4.501,0.305,9.023,0.305,13.565 c0,138.542-105.461,298.285-298.274,298.285c-59.209,0-114.322-17.357-160.716-47.104c8.212,0.973,16.546,1.47,25.012,1.47 c49.121,0,94.318-16.759,130.209-44.884c-45.887-0.841-84.596-31.154-97.938-72.804c6.408,1.227,12.968,1.886,19.73,1.886 c9.55,0,18.816-1.287,27.617-3.68c-47.955-9.633-84.1-52.001-84.1-102.795c0-0.446,0-0.882,0.011-1.318 c14.133,7.847,30.294,12.562,47.488,13.109c-28.134-18.796-46.637-50.885-46.637-87.262c0-19.212,5.16-37.218,14.193-52.7 c51.707,63.426,128.941,105.156,216.072,109.536c-1.784-7.675-2.718-15.674-2.718-23.896c0-57.891,46.941-104.832,104.832-104.832 c30.173,0,57.404,12.734,76.525,33.102c23.887-4.694,46.313-13.423,66.569-25.438c-7.827,24.485-24.434,45.025-46.089,58.002 c21.209-2.535,41.426-8.171,60.222-16.505C497.448,118.542,479.666,137.004,459.186,151.787z"
|
||||
>
|
||||
</path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 27.5.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="svg5" xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1668.56 1221.19"
|
||||
style="enable-background:new 0 0 1668.56 1221.19;" xml:space="preserve">
|
||||
<g id="layer1" transform="translate(52.390088,-25.058597)">
|
||||
<path id="path1009" d="M283.94,167.31l386.39,516.64L281.5,1104h87.51l340.42-367.76L984.48,1104h297.8L874.15,558.3l361.92-390.99
|
||||
h-87.51l-313.51,338.7l-253.31-338.7H283.94z M412.63,231.77h136.81l604.13,807.76h-136.81L412.63,231.77z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 722 B |
@@ -0,0 +1,4 @@
|
||||
.env
|
||||
app.db
|
||||
configs/**.yaml
|
||||
db
|
||||
@@ -0,0 +1,4 @@
|
||||
.env
|
||||
app.db
|
||||
configs/**.yaml
|
||||
db
|
||||
@@ -0,0 +1,15 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt /app/
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . /app
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENV NAME embedchain
|
||||
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||
@@ -0,0 +1,21 @@
|
||||
## Single command to rule them all,
|
||||
|
||||
```bash
|
||||
docker run -d --name embedchain -p 8080:8080 embedchain/rest-api:latest
|
||||
```
|
||||
|
||||
### To run the app locally,
|
||||
|
||||
```bash
|
||||
# will help reload on changes
|
||||
DEVELOPMENT=True && python -m main
|
||||
```
|
||||
|
||||
Using docker (locally),
|
||||
|
||||
```bash
|
||||
docker build -t embedchain/rest-api:latest .
|
||||
docker run -d --name embedchain -p 8080:8080 embedchain/rest-api:latest
|
||||
docker image push embedchain/rest-api:latest
|
||||
```
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"version": "1",
|
||||
"name": "ec-rest-api",
|
||||
"type": "collection"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
meta {
|
||||
name: default_add
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
post {
|
||||
url: http://localhost:8080/add
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"source": "source_url",
|
||||
"data_type": "data_type"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
meta {
|
||||
name: default_chat
|
||||
type: http
|
||||
seq: 4
|
||||
}
|
||||
|
||||
post {
|
||||
url: http://localhost:8080/chat
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"message": "message"
|
||||
}
|
||||
}
|
||||