Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1bddd46ed2 | |||
| 6ecdadfd97 | |||
| 4119040005 | |||
| 873eef6ef8 | |||
| 445fed4d3f | |||
| 52fd3e0dd4 | |||
| 8fd0e1f3b0 | |||
| 11fc4a8451 | |||
| e22293294e | |||
| 73e53aaff1 | |||
| 6fa946557f | |||
| fb0852f585 | |||
| 4070fc1bf0 | |||
| 00c1fa1ec7 | |||
| 04e77ef34e | |||
| 827d63d115 | |||
| e0d0f6e94c | |||
| fd07513004 | |||
| b0e436d9c4 | |||
| a4bfd9cfc6 | |||
| 8ca01918e5 | |||
| a5b2381458 | |||
| 26c771503b | |||
| 622ed4a7c9 | |||
| 940f0128d5 | |||
| 1354747ca8 | |||
| 9544c69c55 | |||
| 9ba445e623 | |||
| ebc5e25f98 | |||
| 78301ee63d | |||
| 797dea1dca | |||
| a0ff764f0a | |||
| a795798156 | |||
| 1a66f961f4 | |||
| 6fb2048af0 | |||
| ba9f186fc5 | |||
| 6c32d287b5 | |||
| 536f85b78a | |||
| f8619870ad | |||
| d00a2085d5 | |||
| 85ec61335a | |||
| 9b48a12c27 | |||
| c181ccbe42 | |||
| 8520033d44 | |||
| ebdce87fde | |||
| f2122ed696 | |||
| 3616eaadb4 | |||
| ef69c91b60 | |||
| 117824b32c | |||
| f77f5b996e | |||
| a4d32aec24 | |||
| 9111495fae | |||
| ee1e3f0957 | |||
| 4dc5c7348f | |||
| 4428768eaa | |||
| 11f4ce8fb6 | |||
| 6078738d34 | |||
| faacfeb891 | |||
| 8d7e8b6fb9 | |||
| 7e1d2ffdd7 | |||
| 91044ec591 | |||
| c77a75dfb5 | |||
| 6518c0c06b |
@@ -4,7 +4,7 @@ repos:
|
||||
hooks:
|
||||
- id: black
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: 'v0.0.220'
|
||||
rev: 'v0.0.252'
|
||||
hooks:
|
||||
- id: ruff
|
||||
name: ruff
|
||||
|
||||
@@ -67,6 +67,10 @@ We use `pytest` to test our code. You can run the tests by running the following
|
||||
poetry run pytest
|
||||
```
|
||||
|
||||
|
||||
Several packages have been removed from Poetry to make the package lighter. Therefore, it is recommended to run `make install_all` to install the remaining packages and ensure all tests pass.
|
||||
|
||||
|
||||
Make sure that all tests pass before submitting a pull request.
|
||||
|
||||
## 🚀 Release Process
|
||||
|
||||
@@ -11,7 +11,7 @@ install:
|
||||
|
||||
install_all:
|
||||
poetry install --all-extras
|
||||
poetry run pip install pinecone-text pinecone-client
|
||||
poetry run pip install pinecone-text pinecone-client langchain-anthropic "unstructured[local-inference, all-docs]" ollama
|
||||
|
||||
install_es:
|
||||
poetry install --extras elasticsearch
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
<img src="docs/logo/dark.svg" width="400px" alt="Embedchain Logo">
|
||||
</p>
|
||||
|
||||
<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>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://pypi.org/project/embedchain/">
|
||||
<img src="https://img.shields.io/pypi/v/embedchain" alt="PyPI">
|
||||
@@ -34,9 +30,9 @@
|
||||
|
||||
## What is Embedchain?
|
||||
|
||||
Embedchain is an Open Source RAG Framework that makes it easy to create and deploy AI apps. At its core, Embedchain follows the design principle of being *"Conventional but Configurable"* to serve both software engineers and machine learning engineers.
|
||||
Embedchain is an Open Source Framework for personalizing LLM responses. It makes it easy to create and deploy personalized AI apps. At its core, Embedchain follows the design principle of being *"Conventional but Configurable"* to serve both software engineers and machine learning engineers.
|
||||
|
||||
Embedchain streamlines the creation of Retrieval-Augmented Generation (RAG) applications, offering a seamless process for managing various types of unstructured data. It efficiently segments data into manageable chunks, generates relevant embeddings, and stores them in a vector database for optimized retrieval. With a suite of diverse APIs, it enables users to extract contextual information, find precise answers, or engage in interactive chat conversations, all tailored to their own data.
|
||||
Embedchain streamlines the creation of personalized LLM applications, offering a seamless process for managing various types of unstructured data. It efficiently segments data into manageable chunks, generates relevant embeddings, and stores them in a vector database for optimized retrieval. With a suite of diverse APIs, it enables users to extract contextual information, find precise answers, or engage in interactive chat conversations, all tailored to their own data.
|
||||
|
||||
## 🔧 Quick install
|
||||
|
||||
@@ -64,15 +60,15 @@ import os
|
||||
from embedchain import App
|
||||
|
||||
# Create a bot instance
|
||||
os.environ["OPENAI_API_KEY"] = "YOUR API KEY"
|
||||
elon_bot = App()
|
||||
os.environ["OPENAI_API_KEY"] = "<YOUR_API_KEY>"
|
||||
app = App()
|
||||
|
||||
# Embed online resources
|
||||
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")
|
||||
|
||||
# Query the bot
|
||||
elon_bot.query("How many companies does Elon Musk run and name those?")
|
||||
# Query the app
|
||||
app.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.
|
||||
```
|
||||
|
||||
|
||||
+4
-2
@@ -5,8 +5,10 @@ llm:
|
||||
temperature: 0.5
|
||||
top_p: 1
|
||||
stream: true
|
||||
base_url: http://localhost:11434
|
||||
|
||||
embedder:
|
||||
provider: huggingface
|
||||
provider: ollama
|
||||
config:
|
||||
model: 'BAAI/bge-small-en-v1.5'
|
||||
model: 'mxbai-embed-large:latest'
|
||||
base_url: http://localhost:11434
|
||||
|
||||
@@ -26,6 +26,9 @@ llm:
|
||||
top_p: 1
|
||||
stream: false
|
||||
api_key: sk-xxx
|
||||
model_kwargs:
|
||||
response_format:
|
||||
type: json_object
|
||||
prompt: |
|
||||
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.
|
||||
@@ -83,7 +86,8 @@ cache:
|
||||
"stream": false,
|
||||
"prompt": "Use the following pieces of context to answer the query at the end.\nIf you don't know the answer, just say that you don't know, don't try to make up an answer.\n$context\n\nQuery: $query\n\nHelpful Answer:",
|
||||
"system_prompt": "Act as William Shakespeare. Answer the following questions in the style of William Shakespeare.",
|
||||
"api_key": "sk-xxx"
|
||||
"api_key": "sk-xxx",
|
||||
"model_kwargs": {"response_format": {"type": "json_object"}}
|
||||
}
|
||||
},
|
||||
"vectordb": {
|
||||
@@ -143,7 +147,8 @@ config = {
|
||||
'system_prompt': (
|
||||
"Act as William Shakespeare. Answer the following questions in the style of William Shakespeare."
|
||||
),
|
||||
'api_key': 'sk-xxx'
|
||||
'api_key': 'sk-xxx',
|
||||
"model_kwargs": {"response_format": {"type": "json_object"}}
|
||||
}
|
||||
},
|
||||
'vectordb': {
|
||||
@@ -198,9 +203,9 @@ Alright, let's dive into what each key means in the yaml config above:
|
||||
- `max_tokens` (Integer): Controls how many tokens are used in the response.
|
||||
- `top_p` (Float): Controls the diversity of word selection. A higher value (closer to 1) makes word selection more diverse.
|
||||
- `stream` (Boolean): Controls if the response is streamed back to the user (set to false).
|
||||
- `online` (Boolean): Controls whether to use internet to get more context for answering query (set to false).
|
||||
- `prompt` (String): A prompt for the model to follow when generating responses, requires `$context` and `$query` variables.
|
||||
- `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.
|
||||
- `stream` (Boolean): Controls if the response is streamed back to the user (set to false).
|
||||
- `number_documents` (Integer): Number of documents to pull from the vectordb as context, defaults to 1
|
||||
- `api_key` (String): The API key for the language model.
|
||||
- `model_kwargs` (Dict): Keyword arguments to pass to the language model. Used for `aws_bedrock` provider, since it requires different arguments for each model.
|
||||
|
||||
@@ -37,7 +37,14 @@ Create a local index:
|
||||
```python
|
||||
from embedchain import App
|
||||
|
||||
naval_chat_bot = App()
|
||||
config = {
|
||||
"app": {
|
||||
"config": {
|
||||
"id": "app-1"
|
||||
}
|
||||
}
|
||||
}
|
||||
naval_chat_bot = App.from_config(config=config)
|
||||
naval_chat_bot.add("https://www.youtube.com/watch?v=3qHkcs3kG44")
|
||||
naval_chat_bot.add("https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Almanack-of-Naval-Ravikant_Final.pdf")
|
||||
```
|
||||
@@ -47,7 +54,14 @@ You can reuse the local index with the same code, but without adding new documen
|
||||
```python
|
||||
from embedchain import App
|
||||
|
||||
naval_chat_bot = App()
|
||||
config = {
|
||||
"app": {
|
||||
"config": {
|
||||
"id": "app-1"
|
||||
}
|
||||
}
|
||||
}
|
||||
naval_chat_bot = App.from_config(config=config)
|
||||
print(naval_chat_bot.query("What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?"))
|
||||
```
|
||||
|
||||
@@ -58,7 +72,14 @@ You can reset the app by simply calling the `reset` method. This will delete the
|
||||
```python
|
||||
from embedchain import App
|
||||
|
||||
app = App()
|
||||
app = App()config = {
|
||||
"app": {
|
||||
"config": {
|
||||
"id": "app-1"
|
||||
}
|
||||
}
|
||||
}
|
||||
naval_chat_bot = App.from_config(config=config)
|
||||
app.add("https://www.youtube.com/watch?v=3qHkcs3kG44")
|
||||
app.reset()
|
||||
```
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: '📄 Excel file'
|
||||
---
|
||||
|
||||
### Excel file
|
||||
|
||||
To add any xlsx/xls file, use the data_type as `excel_file`. `excel_file` allows remote urls and conventional file paths. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
|
||||
app = App()
|
||||
app.add('https://example.com/content/intro.xlsx', data_type="excel_file")
|
||||
# Or add file using the local file path on your system
|
||||
# app.add('content/intro.xls', data_type="excel_file")
|
||||
|
||||
app.query("Give brief information about data.")
|
||||
```
|
||||
@@ -29,11 +29,13 @@ response = app.query("What is Embedchain?")
|
||||
```
|
||||
The `add` function of the app will accept any valid github query with qualifiers. It only supports loading github code, repository, issues and pull-requests.
|
||||
<Note>
|
||||
You must provide qualifiers `type:` and `repo:` in the query. The `type:` qualifier can be a combination of `code`, `repo`, `pr`, `issue`. The `repo:` qualifier must be a valid github repository name.
|
||||
You must provide qualifiers `type:` and `repo:` in the query. The `type:` qualifier can be a combination of `code`, `repo`, `pr`, `issue`, `branch`, `file`. The `repo:` qualifier must be a valid github repository name.
|
||||
</Note>
|
||||
|
||||
<Card title="Valid queries" icon="lightbulb" iconType="duotone" color="#ca8b04">
|
||||
- `repo:embedchain/embedchain type:repo` - to load the repository
|
||||
- `repo:embedchain/embedchain type:branch name:feature_test` - to load the branch of the repository
|
||||
- `repo:embedchain/embedchain type:file path:README.md` - to load the specific file of the repository
|
||||
- `repo:embedchain/embedchain type:issue,pr` - to load the issues and pull-requests of the repository
|
||||
- `repo:embedchain/embedchain type:issue state:closed` - to load the closed issues of the repository
|
||||
</Card>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: '❓💬 Queston and answer pair'
|
||||
title: '❓💬 Question 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:
|
||||
@@ -10,4 +10,4 @@ from embedchain import App
|
||||
app = App()
|
||||
|
||||
app.add(("Question", "Answer"), data_type="qna_pair")
|
||||
```
|
||||
```
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: '📄 Text file'
|
||||
---
|
||||
|
||||
To add a .txt file, specify the data_type as `text_file`. The URL provided in the first parameter of the `add` function, should be a local path. Eg:
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
|
||||
app = App()
|
||||
app.add('path/to/file.txt', data_type="text_file")
|
||||
|
||||
app.query("Summarize the information of the text file")
|
||||
```
|
||||
@@ -13,6 +13,9 @@ Embedchain supports several embedding models from the following providers:
|
||||
<Card title="GPT4All" href="#gpt4all"></Card>
|
||||
<Card title="Hugging Face" href="#hugging-face"></Card>
|
||||
<Card title="Vertex AI" href="#vertex-ai"></Card>
|
||||
<Card title="NVIDIA AI" href="#nvidia-ai"></Card>
|
||||
<Card title="Cohere" href="#cohere"></Card>
|
||||
<Card title="Ollama" href="#ollama"></Card>
|
||||
</CardGroup>
|
||||
|
||||
## OpenAI
|
||||
@@ -220,3 +223,166 @@ embedder:
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## NVIDIA AI
|
||||
|
||||
[NVIDIA AI Foundation Endpoints](https://www.nvidia.com/en-us/ai-data-science/foundation-models/) let you quickly use NVIDIA's AI models, such as Mixtral 8x7B, Llama 2 etc, through our API. These models are available in the [NVIDIA NGC catalog](https://catalog.ngc.nvidia.com/ai-foundation-models), fully optimized and ready to use on NVIDIA's AI platform. They are designed for high speed and easy customization, ensuring smooth performance on any accelerated setup.
|
||||
|
||||
|
||||
### Usage
|
||||
|
||||
In order to use embedding models and LLMs from NVIDIA AI, create an account on [NVIDIA NGC Service](https://catalog.ngc.nvidia.com/).
|
||||
|
||||
Generate an API key from their dashboard. Set the API key as `NVIDIA_API_KEY` environment variable. Note that the `NVIDIA_API_KEY` will start with `nvapi-`.
|
||||
|
||||
Below is an example of how to use LLM model and embedding model from NVIDIA AI:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
|
||||
os.environ['NVIDIA_API_KEY'] = 'nvapi-xxxx'
|
||||
|
||||
config = {
|
||||
"app": {
|
||||
"config": {
|
||||
"id": "my-app",
|
||||
},
|
||||
},
|
||||
"llm": {
|
||||
"provider": "nvidia",
|
||||
"config": {
|
||||
"model": "nemotron_steerlm_8b",
|
||||
},
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "nvidia",
|
||||
"config": {
|
||||
"model": "nvolveqa_40k",
|
||||
"vector_dimension": 1024,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app = App.from_config(config=config)
|
||||
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
answer = app.query("What is the net worth of Elon Musk today?")
|
||||
# Answer: The net worth of Elon Musk is subject to fluctuations based on the market value of his holdings in various companies.
|
||||
# As of March 1, 2024, his net worth is estimated to be approximately $210 billion. However, this figure can change rapidly due to stock market fluctuations and other factors.
|
||||
# Additionally, his net worth may include other assets such as real estate and art, which are not reflected in his stock portfolio.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
## Cohere
|
||||
|
||||
To use embedding models and LLMs from COHERE, create an account on [COHERE](https://dashboard.cohere.com/welcome/login?redirect_uri=%2Fapi-keys).
|
||||
|
||||
Generate an API key from their dashboard. Set the API key as `COHERE_API_KEY` environment variable.
|
||||
|
||||
Once you have obtained the key, you can use it like this:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
|
||||
os.environ['COHERE_API_KEY'] = 'xxx'
|
||||
|
||||
# load embedding model configuration from config.yaml file
|
||||
app = App.from_config(config_path="config.yaml")
|
||||
```
|
||||
|
||||
```yaml config.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-english-light-v3.0'
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
* Cohere has few embedding models: `embed-english-v3.0`, `embed-multilingual-v3.0`, `embed-multilingual-light-v3.0`, `embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0`. Embedchain supports all these models. Below you can find YAML config for all:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```yaml embed-english-v3.0.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-english-v3.0'
|
||||
vector_dimension: 1024
|
||||
```
|
||||
|
||||
```yaml embed-multilingual-v3.0.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-multilingual-v3.0'
|
||||
vector_dimension: 1024
|
||||
```
|
||||
|
||||
```yaml embed-multilingual-light-v3.0.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-multilingual-light-v3.0'
|
||||
vector_dimension: 384
|
||||
```
|
||||
|
||||
```yaml embed-english-v2.0.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-english-v2.0'
|
||||
vector_dimension: 4096
|
||||
```
|
||||
|
||||
```yaml embed-english-light-v2.0.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-english-light-v2.0'
|
||||
vector_dimension: 1024
|
||||
```
|
||||
|
||||
```yaml embed-multilingual-v2.0.yaml
|
||||
embedder:
|
||||
provider: cohere
|
||||
config:
|
||||
model: 'embed-multilingual-v2.0'
|
||||
vector_dimension: 768
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Ollama
|
||||
|
||||
Ollama enables the use of embedding models, allowing you to generate high-quality embeddings directly on your local machine. Make sure to install [Ollama](https://ollama.com/download) and keep it running before using the embedding model.
|
||||
|
||||
You can find the list of models at [Ollama Embedding Models](https://ollama.com/blog/embedding-models).
|
||||
|
||||
Below is an example of how to use embedding model Ollama:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
|
||||
# load embedding model configuration from config.yaml file
|
||||
app = App.from_config(config_path="config.yaml")
|
||||
```
|
||||
|
||||
```yaml config.yaml
|
||||
embedder:
|
||||
provider: ollama
|
||||
config:
|
||||
model: 'all-minilm:latest'
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
@@ -23,6 +23,7 @@ Embedchain comes with built-in support for various popular large language models
|
||||
<Card title="Mistral AI" href="#mistral-ai"></Card>
|
||||
<Card title="AWS Bedrock" href="#aws-bedrock"></Card>
|
||||
<Card title="Groq" href="#groq"></Card>
|
||||
<Card title="NVIDIA AI" href="#nvidia-ai"></Card>
|
||||
</CardGroup>
|
||||
|
||||
## OpenAI
|
||||
@@ -82,7 +83,7 @@ Embedchain supports OpenAI [Function calling](https://platform.openai.com/docs/g
|
||||
b: int = Field(..., description="Second integer")
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
|
||||
<Accordion title="Python function">
|
||||
```python
|
||||
def multiply(a: int, b: int) -> int:
|
||||
@@ -329,6 +330,7 @@ Setup Ollama using https://github.com/jmorganca/ollama
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
os.environ["OLLAMA_HOST"] = "http://127.0.0.1:11434"
|
||||
from embedchain import App
|
||||
|
||||
# load llm configuration from config.yaml file
|
||||
@@ -343,6 +345,13 @@ llm:
|
||||
temperature: 0.5
|
||||
top_p: 1
|
||||
stream: true
|
||||
base_url: 'http://localhost:11434'
|
||||
embedder:
|
||||
provider: ollama
|
||||
config:
|
||||
model: znbang/bge:small-en-v1.5-q8_0
|
||||
base_url: http://localhost:11434
|
||||
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
@@ -730,6 +739,58 @@ app.query("Write a poem about Embedchain")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## NVIDIA AI
|
||||
|
||||
[NVIDIA AI Foundation Endpoints](https://www.nvidia.com/en-us/ai-data-science/foundation-models/) let you quickly use NVIDIA's AI models, such as Mixtral 8x7B, Llama 2 etc, through our API. These models are available in the [NVIDIA NGC catalog](https://catalog.ngc.nvidia.com/ai-foundation-models), fully optimized and ready to use on NVIDIA's AI platform. They are designed for high speed and easy customization, ensuring smooth performance on any accelerated setup.
|
||||
|
||||
|
||||
### Usage
|
||||
|
||||
In order to use LLMs from NVIDIA AI, create an account on [NVIDIA NGC Service](https://catalog.ngc.nvidia.com/).
|
||||
|
||||
Generate an API key from their dashboard. Set the API key as `NVIDIA_API_KEY` environment variable. Note that the `NVIDIA_API_KEY` will start with `nvapi-`.
|
||||
|
||||
Below is an example of how to use LLM model and embedding model from NVIDIA AI:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python main.py
|
||||
import os
|
||||
from embedchain import App
|
||||
|
||||
os.environ['NVIDIA_API_KEY'] = 'nvapi-xxxx'
|
||||
|
||||
config = {
|
||||
"app": {
|
||||
"config": {
|
||||
"id": "my-app",
|
||||
},
|
||||
},
|
||||
"llm": {
|
||||
"provider": "nvidia",
|
||||
"config": {
|
||||
"model": "nemotron_steerlm_8b",
|
||||
},
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "nvidia",
|
||||
"config": {
|
||||
"model": "nvolveqa_40k",
|
||||
"vector_dimension": 1024,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
app = App.from_config(config=config)
|
||||
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
answer = app.query("What is the net worth of Elon Musk today?")
|
||||
# Answer: The net worth of Elon Musk is subject to fluctuations based on the market value of his holdings in various companies.
|
||||
# As of March 1, 2024, his net worth is estimated to be approximately $210 billion. However, this figure can change rapidly due to stock market fluctuations and other factors.
|
||||
# Additionally, his net worth may include other assets such as real estate and art, which are not reflected in his stock portfolio.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<br/ >
|
||||
|
||||
<Snippet file="missing-llm-tip.mdx" />
|
||||
|
||||
@@ -98,6 +98,9 @@ app.add("/path/to/file.pdf", data_type="pdf_file", namespace="my-namespace")
|
||||
|
||||
# Query
|
||||
app.query("<YOUR QUESTION HERE>", namespace="my-namespace")
|
||||
|
||||
# Chat
|
||||
app.chat("<YOUR QUESTION HERE>", namespace="my-namespace")
|
||||
```
|
||||
|
||||
Under the hood, Embedchain fetches the relevant chunks from the documents you added by doing hybrid search on the pinecone index.
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
---
|
||||
title: ' 🟨 Javascript'
|
||||
url: https://github.com/embedchain/embedchain/tree/main/embedchain-js
|
||||
---
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
title: 'Embedchain.ai'
|
||||
description: 'Deploy your RAG application to embedchain.ai platform'
|
||||
---
|
||||
|
||||
## Deploy on Embedchain Platform
|
||||
|
||||
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.
|
||||
|
||||
Deployment to Embedchain Platform is currently available on an invitation-only basis. To request access, please submit your information via the provided [Google Form](https://forms.gle/vigN11h7b4Ywat668). We will review your request and respond promptly.
|
||||
|
||||
|
||||
## Seeking help?
|
||||
|
||||
If you run into issues with deployment, please feel free to reach out to us via any of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -13,7 +13,6 @@ After successfully setting up and testing your RAG app locally, the next step is
|
||||
<Card title="Streamlit.io" href="/deployment/streamlit_io"></Card>
|
||||
<Card title="Gradio.app" href="/deployment/gradio_app"></Card>
|
||||
<Card title="Huggingface.co" href="/deployment/huggingface_spaces"></Card>
|
||||
<Card title="Embedchain.ai" href="/deployment/embedchain_ai"></Card>
|
||||
</CardGroup>
|
||||
|
||||
## Seeking help?
|
||||
|
||||
@@ -4,21 +4,21 @@ title: 📚 Introduction
|
||||
|
||||
## What is Embedchain?
|
||||
|
||||
Embedchain is an Open Source RAG Framework that makes it easy to create and deploy AI apps. At its core, Embedchain follows the design principle of being *"Conventional but Configurable"* to serve both software engineers and machine learning engineers.
|
||||
Embedchain is an Open Source Framework that makes it easy to create and deploy personalized AI apps. At its core, Embedchain follows the design principle of being *"Conventional but Configurable"* to serve both software engineers and machine learning engineers.
|
||||
|
||||
Embedchain streamlines the creation of RAG applications, offering a seamless process for managing various types of unstructured data. It efficiently segments data into manageable chunks, generates relevant embeddings, and stores them in a vector database for optimized retrieval. With a suite of diverse APIs, it enables users to extract contextual information, find precise answers, or engage in interactive chat conversations, all tailored to their own data.
|
||||
Embedchain streamlines the creation of personalized LLM applications, offering a seamless process for managing various types of unstructured data. It efficiently segments data into manageable chunks, generates relevant embeddings, and stores them in a vector database for optimized retrieval. With a suite of diverse APIs, it enables users to extract contextual information, find precise answers, or engage in interactive chat conversations, all tailored to their own data.
|
||||
|
||||
## Who is Embedchain for?
|
||||
|
||||
Embedchain is designed for a diverse range of users, from AI professionals like Data Scientists and Machine Learning Engineers to those just starting their AI journey, including college students, independent developers, and hobbyists. Essentially, it's for anyone with an interest in AI, regardless of their expertise level.
|
||||
|
||||
Our APIs are user-friendly yet adaptable, enabling beginners to effortlessly create LLM-powered applications with as few as 4 lines of code. At the same time, we offer extensive customization options for every aspect of the RAG pipeline. This includes the choice of LLMs, vector databases, loaders and chunkers, retrieval strategies, re-ranking, and more.
|
||||
Our APIs are user-friendly yet adaptable, enabling beginners to effortlessly create LLM-powered applications with as few as 4 lines of code. At the same time, we offer extensive customization options for every aspect of building a personalized AI application. This includes the choice of LLMs, vector databases, loaders and chunkers, retrieval strategies, re-ranking, and more.
|
||||
|
||||
Our platform's clear and well-structured abstraction layers ensure that users can tailor the system to meet their specific needs, whether they're crafting a simple project or a complex, nuanced AI application.
|
||||
|
||||
## Why Use Embedchain?
|
||||
|
||||
Developing a robust and efficient RAG (Retrieval-Augmented Generation) pipeline for production use presents numerous complexities, such as:
|
||||
Developing a personalized AI application for production use presents numerous complexities, such as:
|
||||
|
||||
- Integrating and indexing data from diverse sources.
|
||||
- Determining optimal data chunking methods for each source.
|
||||
@@ -48,11 +48,11 @@ When a user asks a question, whether for chatting, searching, or querying, Embed
|
||||
2. **Document Retrieval**: These embeddings are then used to find related documents in the database.
|
||||
3. **Answer Generation**: The related documents are used by the LLM to craft a precise answer.
|
||||
|
||||
With Embedchain, you don’t have to worry about the complexities of building a RAG pipeline. It offers an easy-to-use interface for developing applications with any kind of data.
|
||||
With Embedchain, you don’t have to worry about the complexities of building a personalized AI application. It offers an easy-to-use interface for developing applications with any kind of data.
|
||||
|
||||
## Getting started
|
||||
|
||||
Checkout our [quickstart guide](/get-started/quickstart) to start your first RAG application.
|
||||
Checkout our [quickstart guide](/get-started/quickstart) to start your first AI application.
|
||||
|
||||
## Support
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: '⚡ Quickstart'
|
||||
description: '💡 Create a RAG app on your own data in a minute'
|
||||
description: '💡 Create an AI app on your own data in a minute'
|
||||
---
|
||||
|
||||
## Installation
|
||||
@@ -31,41 +31,47 @@ This section gives a quickstart example of using Mistral as the Open source LLM
|
||||
We are using Mistral hosted at Hugging Face, so will you need a Hugging Face token to run this example. Its *free* and you can create one [here](https://huggingface.co/docs/hub/security-tokens).
|
||||
|
||||
<CodeGroup>
|
||||
```python quickstart.py
|
||||
```python huggingface_demo.py
|
||||
import os
|
||||
# replace this with your HF key
|
||||
# Replace this with your HF token
|
||||
os.environ["HUGGINGFACE_ACCESS_TOKEN"] = "hf_xxxx"
|
||||
|
||||
from embedchain import App
|
||||
app = App.from_config("mistral.yaml")
|
||||
|
||||
config = {
|
||||
'llm': {
|
||||
'provider': 'huggingface',
|
||||
'config': {
|
||||
'model': 'mistralai/Mistral-7B-Instruct-v0.2',
|
||||
'top_p': 0.5
|
||||
}
|
||||
},
|
||||
'embedder': {
|
||||
'provider': 'huggingface',
|
||||
'config': {
|
||||
'model': 'sentence-transformers/all-mpnet-base-v2'
|
||||
}
|
||||
}
|
||||
}
|
||||
app = App.from_config(config=config)
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
app.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
app.query("What is the net worth of Elon Musk today?")
|
||||
# Answer: The net worth of Elon Musk today is $258.7 billion.
|
||||
```
|
||||
```yaml mistral.yaml
|
||||
llm:
|
||||
provider: huggingface
|
||||
config:
|
||||
model: 'mistralai/Mistral-7B-Instruct-v0.2'
|
||||
top_p: 0.5
|
||||
embedder:
|
||||
provider: huggingface
|
||||
config:
|
||||
model: 'sentence-transformers/all-mpnet-base-v2'
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Paid Models
|
||||
|
||||
In this section, we will use both LLM and embedding model from OpenAI.
|
||||
|
||||
```python quickstart.py
|
||||
```python openai_demo.py
|
||||
import os
|
||||
# replace this with your OpenAI key
|
||||
from embedchain import App
|
||||
|
||||
# Replace this with your OpenAI key
|
||||
os.environ["OPENAI_API_KEY"] = "sk-xxxx"
|
||||
|
||||
from embedchain import App
|
||||
app = App()
|
||||
app.add("https://www.forbes.com/profile/elon-musk")
|
||||
app.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
|
||||
@@ -5,22 +5,30 @@ description: 'Integrate with Langsmith to debug and monitor your LLM app'
|
||||
|
||||
Embedchain now supports integration with [LangSmith](https://www.langchain.com/langsmith).
|
||||
|
||||
To use langsmith, you need to do the following steps
|
||||
To use LangSmith, you need to do the following steps.
|
||||
|
||||
1. Have an account on langsmith and keep the environment variables in handy
|
||||
2. Set the environments variables in your app so that embedchain has context about it.
|
||||
1. Have an account on LangSmith and keep the environment variables in handy
|
||||
2. Set the environment variables in your app so that embedchain has context about it.
|
||||
3. Just use embedchain and everything will be logged to LangSmith, so that you can better test and monitor your application.
|
||||
|
||||
Lets cover each step in detail.
|
||||
Let's cover each step in detail.
|
||||
|
||||
* First make sure that you a LangSmith account created and have all the necessary variables handy. LangSmith has a [good documentation](https://docs.smith.langchain.com/) on how to get started with their service.
|
||||
|
||||
* Once you have the account setup, we will need the following environment variables
|
||||
* First make sure that you have created a LangSmith account and have all the necessary variables handy. LangSmith has a [good documentation](https://docs.smith.langchain.com/) on how to get started with their service.
|
||||
|
||||
* Once you have setup the account, we will need the following environment variables
|
||||
|
||||
```bash
|
||||
# Setting environment variable for LangChain Tracing V2 integration.
|
||||
export LANGCHAIN_TRACING_V2=true
|
||||
|
||||
# Setting the API endpoint for LangChain.
|
||||
export LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
|
||||
|
||||
# Replace '<your-api-key>' with your LangChain API key.
|
||||
export LANGCHAIN_API_KEY=<your-api-key>
|
||||
|
||||
# Replace '<your-project>' with your LangChain project name, or it defaults to "default".
|
||||
export LANGCHAIN_PROJECT=<your-project> # if not specified, defaults to "default"
|
||||
```
|
||||
|
||||
@@ -29,20 +37,32 @@ If you are using Python, you can use the following code to set environment varia
|
||||
```python
|
||||
import os
|
||||
|
||||
# Setting environment variable for LangChain Tracing V2 integration.
|
||||
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
|
||||
|
||||
# Setting the API endpoint for LangChain.
|
||||
os.environ['LANGCHAIN_ENDPOINT'] = 'https://api.smith.langchain.com'
|
||||
os.environ['LANGCHAIN_API_KEY'] = <your-api-key>
|
||||
os.environ['LANGCHAIN_PROJECT] = <your-project>
|
||||
|
||||
# Replace '<your-api-key>' with your LangChain API key.
|
||||
os.environ['LANGCHAIN_API_KEY'] = '<your-api-key>'
|
||||
|
||||
# Replace '<your-project>' with your LangChain project name.
|
||||
os.environ['LANGCHAIN_PROJECT'] = '<your-project>'
|
||||
```
|
||||
|
||||
* Now create an app using embedchain and everything will be automatically visible in the LangSmith
|
||||
* Now create an app using Embedchain and everything will be automatically visible in the LangSmith
|
||||
|
||||
|
||||
```python
|
||||
from embedchain import App
|
||||
|
||||
# Initialize EmbedChain application.
|
||||
app = App()
|
||||
|
||||
# Add data to your app
|
||||
app.add("https://en.wikipedia.org/wiki/Elon_Musk")
|
||||
|
||||
# Query your app
|
||||
app.query("How many companies did Elon found?")
|
||||
```
|
||||
|
||||
|
||||
+2
-4
@@ -155,8 +155,7 @@
|
||||
"deployment/railway",
|
||||
"deployment/streamlit_io",
|
||||
"deployment/gradio_app",
|
||||
"deployment/huggingface_spaces",
|
||||
"deployment/embedchain_ai"
|
||||
"deployment/huggingface_spaces"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -236,8 +235,7 @@
|
||||
"contribution/guidelines",
|
||||
"contribution/dev",
|
||||
"contribution/docs",
|
||||
"contribution/python",
|
||||
"contribution/javascript"
|
||||
"contribution/python"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
@@ -1,56 +0,0 @@
|
||||
{
|
||||
// Configuration for JavaScript files
|
||||
"extends": [
|
||||
"airbnb-base",
|
||||
"plugin:prettier/recommended"
|
||||
],
|
||||
"rules": {
|
||||
"prettier/prettier": [
|
||||
"error",
|
||||
{
|
||||
"singleQuote": true,
|
||||
"endOfLine": "auto"
|
||||
}
|
||||
]
|
||||
},
|
||||
"overrides": [
|
||||
// Configuration for TypeScript files
|
||||
{
|
||||
"files": ["**/*.ts", "**/__tests__/*.test.ts"],
|
||||
"plugins": [
|
||||
"@typescript-eslint",
|
||||
"unused-imports",
|
||||
"simple-import-sort"
|
||||
],
|
||||
"extends": [
|
||||
"airbnb-typescript",
|
||||
"plugin:prettier/recommended"
|
||||
],
|
||||
"parserOptions": {
|
||||
"project": "./tsconfig.json"
|
||||
},
|
||||
"rules": {
|
||||
"prettier/prettier": [
|
||||
"error",
|
||||
{
|
||||
"singleQuote": true,
|
||||
"endOfLine": "auto"
|
||||
}
|
||||
],
|
||||
"@typescript-eslint/comma-dangle": "off", // Avoid conflict rule between Eslint and Prettier
|
||||
"@typescript-eslint/consistent-type-imports": "error", // Ensure `import type` is used when it's necessary
|
||||
"import/prefer-default-export": "off", // Named export is easier to refactor automatically
|
||||
"simple-import-sort/imports": "error", // Import configuration for `eslint-plugin-simple-import-sort`
|
||||
"simple-import-sort/exports": "error", // Export configuration for `eslint-plugin-simple-import-sort`
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"react/jsx-filename-extension": "off", // Gives error
|
||||
"unused-imports/no-unused-imports": "error",
|
||||
"unused-imports/no-unused-vars": [
|
||||
"error",
|
||||
{ "argsIgnorePattern": "^_" }
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
name: Node.js Package
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
- run: npm run build
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: types
|
||||
path: types
|
||||
|
||||
publish-npm:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: types
|
||||
path: types
|
||||
- run: npm ci
|
||||
- run: npm publish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.npm_token}}
|
||||
@@ -1,138 +0,0 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
.cache
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
|
||||
.ideas.md
|
||||
.todos.md
|
||||
|
||||
# Custom
|
||||
dist
|
||||
types
|
||||
build
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npx --no -- commitlint --edit $1
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
# Disable concurent to run `check-types` after ESLint in lint-staged
|
||||
npx lint-staged --concurrent false
|
||||
@@ -1,8 +0,0 @@
|
||||
cff-version: 1.2.0
|
||||
message: "If you use this software, please cite it as below."
|
||||
authors:
|
||||
- family-names: "Singh"
|
||||
given-names: "Taranjeet"
|
||||
title: "Embedchain"
|
||||
date-released: 2023-06-25
|
||||
url: "https://github.com/embedchain/embedchainjs"
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,254 +0,0 @@
|
||||
# embedchainjs
|
||||
|
||||
[](https://discord.gg/CUU9FPhRNt)
|
||||
[](https://twitter.com/embedchain)
|
||||
[](https://embedchain.substack.com/)
|
||||
|
||||
embedchain is a framework to easily create LLM powered bots over any dataset. embedchainjs is Javascript version of embedchain. If you want a python version, check out [embedchain-python](https://github.com/embedchain/embedchain)
|
||||
|
||||
# 🤝 Let's Talk Embedchain!
|
||||
|
||||
Schedule a [Feedback Session](https://cal.com/taranjeetio/ec) with Taranjeet, the founder, to discuss any issues, provide feedback, or explore improvements.
|
||||
|
||||
# How it works
|
||||
|
||||
It abstracts the entire process of loading dataset, chunking it, creating embeddings and then storing in vector database.
|
||||
|
||||
You can add a single or multiple dataset using `.add` and `.addLocal` function and then use `.query` function to find an answer from the added datasets.
|
||||
|
||||
If you want to create a Naval Ravikant bot which has 2 of his blog posts, as well as a question and answer pair you supply, all you need to do is add the links to the blog posts and the QnA pair and embedchain will create a bot for you.
|
||||
|
||||
```javascript
|
||||
const dotenv = require("dotenv");
|
||||
dotenv.config();
|
||||
const { App } = require("embedchain");
|
||||
|
||||
//Run the app commands inside an async function only
|
||||
async function testApp() {
|
||||
const navalChatBot = await App();
|
||||
|
||||
// Embed Online Resources
|
||||
await navalChatBot.add("web_page", "https://nav.al/feedback");
|
||||
await navalChatBot.add("web_page", "https://nav.al/agi");
|
||||
await navalChatBot.add(
|
||||
"pdf_file",
|
||||
"https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Almanack-of-Naval-Ravikant_Final.pdf"
|
||||
);
|
||||
|
||||
// Embed Local Resources
|
||||
await navalChatBot.addLocal("qna_pair", [
|
||||
"Who is Naval Ravikant?",
|
||||
"Naval Ravikant is an Indian-American entrepreneur and investor.",
|
||||
]);
|
||||
|
||||
const result = await navalChatBot.query(
|
||||
"What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?"
|
||||
);
|
||||
console.log(result);
|
||||
// answer: Naval argues that humans possess the unique capacity to understand explanations or concepts to the maximum extent possible in this physical reality.
|
||||
}
|
||||
|
||||
testApp();
|
||||
```
|
||||
|
||||
# Getting Started
|
||||
|
||||
## Installation
|
||||
|
||||
- First make sure that you have the package installed. If not, then install it using `npm`
|
||||
|
||||
```bash
|
||||
npm install embedchain && npm install -S openai@^3.3.0
|
||||
```
|
||||
|
||||
- Currently, it is only compatible with openai 3.X, not the latest version 4.X. Please make sure to use the right version, otherwise you will see the `ChromaDB` error `TypeError: OpenAIApi.Configuration is not a constructor`
|
||||
|
||||
- Make sure that dotenv package is installed and your `OPENAI_API_KEY` in a file called `.env` in the root folder. You can install dotenv by
|
||||
|
||||
```js
|
||||
npm install dotenv
|
||||
```
|
||||
|
||||
- Download and install Docker on your device by visiting [this link](https://www.docker.com/). You will need this to run Chroma vector database on your machine.
|
||||
|
||||
- Run the following commands to setup Chroma container in Docker
|
||||
|
||||
```bash
|
||||
git clone https://github.com/chroma-core/chroma.git
|
||||
cd chroma
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
- Once Chroma container has been set up, run it inside Docker
|
||||
|
||||
## Usage
|
||||
|
||||
- We use OpenAI's embedding model to create embeddings for chunks and ChatGPT API as LLM to get answer given the relevant docs. Make sure that you have an OpenAI account and an API key. If you have dont have an API key, you can create one by visiting [this link](https://platform.openai.com/account/api-keys).
|
||||
|
||||
- Once you have the API key, set it in an environment variable called `OPENAI_API_KEY`
|
||||
|
||||
```js
|
||||
// Set this inside your .env file
|
||||
OPENAI_API_KEY = "sk-xxxx";
|
||||
```
|
||||
|
||||
- Load the environment variables inside your .js file using the following commands
|
||||
|
||||
```js
|
||||
const dotenv = require("dotenv");
|
||||
dotenv.config();
|
||||
```
|
||||
|
||||
- Next import the `App` class from embedchain and use `.add` function to add any dataset.
|
||||
- Now your app is created. You can use `.query` function to get the answer for any query.
|
||||
|
||||
```js
|
||||
const dotenv = require("dotenv");
|
||||
dotenv.config();
|
||||
const { App } = require("embedchain");
|
||||
|
||||
async function testApp() {
|
||||
const navalChatBot = await App();
|
||||
|
||||
// Embed Online Resources
|
||||
await navalChatBot.add("web_page", "https://nav.al/feedback");
|
||||
await navalChatBot.add("web_page", "https://nav.al/agi");
|
||||
await navalChatBot.add(
|
||||
"pdf_file",
|
||||
"https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Almanack-of-Naval-Ravikant_Final.pdf"
|
||||
);
|
||||
|
||||
// Embed Local Resources
|
||||
await navalChatBot.addLocal("qna_pair", [
|
||||
"Who is Naval Ravikant?",
|
||||
"Naval Ravikant is an Indian-American entrepreneur and investor.",
|
||||
]);
|
||||
|
||||
const result = await navalChatBot.query(
|
||||
"What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?"
|
||||
);
|
||||
console.log(result);
|
||||
// answer: Naval argues that humans possess the unique capacity to understand explanations or concepts to the maximum extent possible in this physical reality.
|
||||
}
|
||||
|
||||
testApp();
|
||||
```
|
||||
|
||||
- If there is any other app instance in your script or app, you can change the import as
|
||||
|
||||
```javascript
|
||||
const { App: EmbedChainApp } = require("embedchain");
|
||||
|
||||
// or
|
||||
|
||||
const { App: ECApp } = require("embedchain");
|
||||
```
|
||||
|
||||
## Format supported
|
||||
|
||||
We support the following formats:
|
||||
|
||||
### PDF File
|
||||
|
||||
To add any pdf file, use the data_type as `pdf_file`. Eg:
|
||||
|
||||
```javascript
|
||||
await app.add("pdf_file", "a_valid_url_where_pdf_file_can_be_accessed");
|
||||
```
|
||||
|
||||
### Web Page
|
||||
|
||||
To add any web page, use the data_type as `web_page`. Eg:
|
||||
|
||||
```javascript
|
||||
await app.add("web_page", "a_valid_web_page_url");
|
||||
```
|
||||
|
||||
### QnA Pair
|
||||
|
||||
To supply your own QnA pair, use the data_type as `qna_pair` and enter a tuple. Eg:
|
||||
|
||||
```javascript
|
||||
await app.addLocal("qna_pair", ["Question", "Answer"]);
|
||||
```
|
||||
|
||||
### More Formats coming soon
|
||||
|
||||
- If you want to add any other format, please create an [issue](https://github.com/embedchain/embedchainjs/issues) and we will add it to the list of supported formats.
|
||||
|
||||
## Testing
|
||||
|
||||
Before you consume valuable tokens, you should make sure that the embedding you have done works and that it's receiving the correct document from the database.
|
||||
|
||||
For this you can use the `dryRun` method.
|
||||
|
||||
Following the example above, add this to your script:
|
||||
|
||||
```js
|
||||
let result = await naval_chat_bot.dryRun("What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?");console.log(result);
|
||||
|
||||
'''
|
||||
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.
|
||||
terms of the unseen. And I think that’s critical. That is what humans do uniquely that no other creature, no other computer, no other intelligence—biological or artificial—that we have ever encountered does. And not only do we do it uniquely, but if we were to meet an alien species that also had the power to generate these good explanations, there is no explanation that they could generate that we could not understand. We are maximally capable of understanding. There is no concept out there that is possible in this physical reality that a human being, given sufficient time and resources and
|
||||
Query: What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?
|
||||
Helpful Answer:
|
||||
'''
|
||||
```
|
||||
|
||||
_The embedding is confirmed to work as expected. It returns the right document, even if the question is asked slightly different. No prompt tokens have been consumed._
|
||||
|
||||
**The dry run will still consume tokens to embed your query, but it is only ~1/15 of the prompt.**
|
||||
|
||||
# How does it work?
|
||||
|
||||
Creating a chat bot over any dataset needs the following steps to happen
|
||||
|
||||
- load the data
|
||||
- create meaningful chunks
|
||||
- create embeddings for each chunk
|
||||
- store the chunks in vector database
|
||||
|
||||
Whenever a user asks any query, following process happens to find the answer for the query
|
||||
|
||||
- create the embedding for query
|
||||
- find similar documents for this query from vector database
|
||||
- pass similar documents as context to LLM to get the final answer.
|
||||
|
||||
The process of loading the dataset and then querying involves multiple steps and each steps has nuances of it is own.
|
||||
|
||||
- How should I chunk the data? What is a meaningful chunk size?
|
||||
- How should I create embeddings for each chunk? Which embedding model should I use?
|
||||
- How should I store the chunks in vector database? Which vector database should I use?
|
||||
- Should I store meta data along with the embeddings?
|
||||
- How should I find similar documents for a query? Which ranking model should I use?
|
||||
|
||||
These questions may be trivial for some but for a lot of us, it needs research, experimentation and time to find out the accurate answers.
|
||||
|
||||
embedchain is a framework which takes care of all these nuances and provides a simple interface to create bots over any dataset.
|
||||
|
||||
In the first release, we are making it easier for anyone to get a chatbot over any dataset up and running in less than a minute. All you need to do is create an app instance, add the data sets using `.add` function and then use `.query` function to get the relevant answer.
|
||||
|
||||
# Team
|
||||
|
||||
## Author
|
||||
|
||||
- Taranjeet Singh ([@taranjeetio](https://twitter.com/taranjeetio))
|
||||
|
||||
## Maintainer
|
||||
|
||||
- [cachho](https://github.com/cachho)
|
||||
- [sahilyadav902](https://github.com/sahilyadav902)
|
||||
|
||||
## Citation
|
||||
|
||||
If you utilize this repository, please consider citing it with:
|
||||
```
|
||||
@misc{embedchain,
|
||||
author = {Taranjeet Singh},
|
||||
title = {Embechain: Framework to easily create LLM powered bots over any dataset},
|
||||
year = {2023},
|
||||
publisher = {GitHub},
|
||||
journal = {GitHub repository},
|
||||
howpublished = {\url{https://github.com/embedchain/embedchainjs}},
|
||||
}
|
||||
```
|
||||
@@ -1 +0,0 @@
|
||||
module.exports = { extends: ['@commitlint/config-conventional'] };
|
||||
@@ -1,66 +0,0 @@
|
||||
import { EmbedChainApp } from '../embedchain';
|
||||
|
||||
const mockAdd = jest.fn();
|
||||
const mockAddLocal = jest.fn();
|
||||
const mockQuery = jest.fn();
|
||||
|
||||
jest.mock('../embedchain', () => {
|
||||
return {
|
||||
EmbedChainApp: jest.fn().mockImplementation(() => {
|
||||
return {
|
||||
add: mockAdd,
|
||||
addLocal: mockAddLocal,
|
||||
query: mockQuery,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('Test App', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('tests the App', async () => {
|
||||
mockQuery.mockResolvedValue(
|
||||
'Naval argues that humans possess the unique capacity to understand explanations or concepts to the maximum extent possible in this physical reality.'
|
||||
);
|
||||
|
||||
const navalChatBot = await new EmbedChainApp(undefined, false);
|
||||
|
||||
// Embed Online Resources
|
||||
await navalChatBot.add('web_page', 'https://nav.al/feedback');
|
||||
await navalChatBot.add('web_page', 'https://nav.al/agi');
|
||||
await navalChatBot.add(
|
||||
'pdf_file',
|
||||
'https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Almanack-of-Naval-Ravikant_Final.pdf'
|
||||
);
|
||||
|
||||
// Embed Local Resources
|
||||
await navalChatBot.addLocal('qna_pair', [
|
||||
'Who is Naval Ravikant?',
|
||||
'Naval Ravikant is an Indian-American entrepreneur and investor.',
|
||||
]);
|
||||
|
||||
const result = await navalChatBot.query(
|
||||
'What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?'
|
||||
);
|
||||
|
||||
expect(mockAdd).toHaveBeenCalledWith('web_page', 'https://nav.al/feedback');
|
||||
expect(mockAdd).toHaveBeenCalledWith('web_page', 'https://nav.al/agi');
|
||||
expect(mockAdd).toHaveBeenCalledWith(
|
||||
'pdf_file',
|
||||
'https://navalmanack.s3.amazonaws.com/Eric-Jorgenson_The-Almanack-of-Naval-Ravikant_Final.pdf'
|
||||
);
|
||||
expect(mockAddLocal).toHaveBeenCalledWith('qna_pair', [
|
||||
'Who is Naval Ravikant?',
|
||||
'Naval Ravikant is an Indian-American entrepreneur and investor.',
|
||||
]);
|
||||
expect(mockQuery).toHaveBeenCalledWith(
|
||||
'What unique capacity does Naval argue humans possess when it comes to understanding explanations or concepts?'
|
||||
);
|
||||
expect(result).toBe(
|
||||
'Naval argues that humans possess the unique capacity to understand explanations or concepts to the maximum extent possible in this physical reality.'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,44 +0,0 @@
|
||||
import { createHash } from 'crypto';
|
||||
import type { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
|
||||
|
||||
import type { BaseLoader } from '../loaders';
|
||||
import type { Input, LoaderResult } from '../models';
|
||||
import type { ChunkResult } from '../models/ChunkResult';
|
||||
|
||||
class BaseChunker {
|
||||
textSplitter: RecursiveCharacterTextSplitter;
|
||||
|
||||
constructor(textSplitter: RecursiveCharacterTextSplitter) {
|
||||
this.textSplitter = textSplitter;
|
||||
}
|
||||
|
||||
async createChunks(loader: BaseLoader, url: Input): Promise<ChunkResult> {
|
||||
const documents: ChunkResult['documents'] = [];
|
||||
const ids: ChunkResult['ids'] = [];
|
||||
const datas: LoaderResult = await loader.loadData(url);
|
||||
const metadatas: ChunkResult['metadatas'] = [];
|
||||
|
||||
const dataPromises = datas.map(async (data) => {
|
||||
const { content, metaData } = data;
|
||||
const chunks: string[] = await this.textSplitter.splitText(content);
|
||||
chunks.forEach((chunk) => {
|
||||
const chunkId = createHash('sha256')
|
||||
.update(chunk + metaData.url)
|
||||
.digest('hex');
|
||||
ids.push(chunkId);
|
||||
documents.push(chunk);
|
||||
metadatas.push(metaData);
|
||||
});
|
||||
});
|
||||
|
||||
await Promise.all(dataPromises);
|
||||
|
||||
return {
|
||||
documents,
|
||||
ids,
|
||||
metadatas,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { BaseChunker };
|
||||
@@ -1,26 +0,0 @@
|
||||
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
|
||||
|
||||
import { BaseChunker } from './BaseChunker';
|
||||
|
||||
interface TextSplitterChunkParams {
|
||||
chunkSize: number;
|
||||
chunkOverlap: number;
|
||||
keepSeparator: boolean;
|
||||
}
|
||||
|
||||
const TEXT_SPLITTER_CHUNK_PARAMS: TextSplitterChunkParams = {
|
||||
chunkSize: 1000,
|
||||
chunkOverlap: 0,
|
||||
keepSeparator: false,
|
||||
};
|
||||
|
||||
class PdfFileChunker extends BaseChunker {
|
||||
constructor() {
|
||||
const textSplitter = new RecursiveCharacterTextSplitter(
|
||||
TEXT_SPLITTER_CHUNK_PARAMS
|
||||
);
|
||||
super(textSplitter);
|
||||
}
|
||||
}
|
||||
|
||||
export { PdfFileChunker };
|
||||
@@ -1,26 +0,0 @@
|
||||
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
|
||||
|
||||
import { BaseChunker } from './BaseChunker';
|
||||
|
||||
interface TextSplitterChunkParams {
|
||||
chunkSize: number;
|
||||
chunkOverlap: number;
|
||||
keepSeparator: boolean;
|
||||
}
|
||||
|
||||
const TEXT_SPLITTER_CHUNK_PARAMS: TextSplitterChunkParams = {
|
||||
chunkSize: 300,
|
||||
chunkOverlap: 0,
|
||||
keepSeparator: false,
|
||||
};
|
||||
|
||||
class QnaPairChunker extends BaseChunker {
|
||||
constructor() {
|
||||
const textSplitter = new RecursiveCharacterTextSplitter(
|
||||
TEXT_SPLITTER_CHUNK_PARAMS
|
||||
);
|
||||
super(textSplitter);
|
||||
}
|
||||
}
|
||||
|
||||
export { QnaPairChunker };
|
||||
@@ -1,26 +0,0 @@
|
||||
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
|
||||
|
||||
import { BaseChunker } from './BaseChunker';
|
||||
|
||||
interface TextSplitterChunkParams {
|
||||
chunkSize: number;
|
||||
chunkOverlap: number;
|
||||
keepSeparator: boolean;
|
||||
}
|
||||
|
||||
const TEXT_SPLITTER_CHUNK_PARAMS: TextSplitterChunkParams = {
|
||||
chunkSize: 500,
|
||||
chunkOverlap: 0,
|
||||
keepSeparator: false,
|
||||
};
|
||||
|
||||
class WebPageChunker extends BaseChunker {
|
||||
constructor() {
|
||||
const textSplitter = new RecursiveCharacterTextSplitter(
|
||||
TEXT_SPLITTER_CHUNK_PARAMS
|
||||
);
|
||||
super(textSplitter);
|
||||
}
|
||||
}
|
||||
|
||||
export { WebPageChunker };
|
||||
@@ -1,6 +0,0 @@
|
||||
import { BaseChunker } from './BaseChunker';
|
||||
import { PdfFileChunker } from './PdfFile';
|
||||
import { QnaPairChunker } from './QnaPair';
|
||||
import { WebPageChunker } from './WebPage';
|
||||
|
||||
export { BaseChunker, PdfFileChunker, QnaPairChunker, WebPageChunker };
|
||||
@@ -1,317 +0,0 @@
|
||||
/* eslint-disable max-classes-per-file */
|
||||
import type { Collection } from 'chromadb';
|
||||
import type { QueryResponse } from 'chromadb/dist/main/types';
|
||||
import * as fs from 'fs';
|
||||
import { Document } from 'langchain/document';
|
||||
import OpenAI from 'openai';
|
||||
import * as path from 'path';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import type { BaseChunker } from './chunkers';
|
||||
import { PdfFileChunker, QnaPairChunker, WebPageChunker } from './chunkers';
|
||||
import type { BaseLoader } from './loaders';
|
||||
import { LocalQnaPairLoader, PdfFileLoader, WebPageLoader } from './loaders';
|
||||
import type {
|
||||
DataDict,
|
||||
DataType,
|
||||
FormattedResult,
|
||||
Input,
|
||||
LocalInput,
|
||||
Metadata,
|
||||
Method,
|
||||
RemoteInput,
|
||||
} from './models';
|
||||
import { ChromaDB } from './vectordb';
|
||||
import type { BaseVectorDB } from './vectordb/BaseVectorDb';
|
||||
|
||||
const openai = new OpenAI({
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
});
|
||||
|
||||
class EmbedChain {
|
||||
dbClient: any;
|
||||
|
||||
// TODO: Definitely assign
|
||||
collection!: Collection;
|
||||
|
||||
userAsks: [DataType, Input][] = [];
|
||||
|
||||
initApp: Promise<void>;
|
||||
|
||||
collectMetrics: boolean;
|
||||
|
||||
sId: string; // sessionId
|
||||
|
||||
constructor(db?: BaseVectorDB, collectMetrics: boolean = true) {
|
||||
if (!db) {
|
||||
this.initApp = this.setupChroma();
|
||||
} else {
|
||||
this.initApp = this.setupOther(db);
|
||||
}
|
||||
|
||||
this.collectMetrics = collectMetrics;
|
||||
|
||||
// Send anonymous telemetry
|
||||
this.sId = uuidv4();
|
||||
this.sendTelemetryEvent('init');
|
||||
}
|
||||
|
||||
async setupChroma(): Promise<void> {
|
||||
const db = new ChromaDB();
|
||||
await db.initDb;
|
||||
this.dbClient = db.client;
|
||||
if (db.collection) {
|
||||
this.collection = db.collection;
|
||||
} else {
|
||||
// TODO: Add proper error handling
|
||||
console.error('No collection');
|
||||
}
|
||||
}
|
||||
|
||||
async setupOther(db: BaseVectorDB): Promise<void> {
|
||||
await db.initDb;
|
||||
// TODO: Figure out how we can initialize an unknown database.
|
||||
// this.dbClient = db.client;
|
||||
// this.collection = db.collection;
|
||||
this.userAsks = [];
|
||||
}
|
||||
|
||||
static getLoader(dataType: DataType) {
|
||||
const loaders: { [t in DataType]: BaseLoader } = {
|
||||
pdf_file: new PdfFileLoader(),
|
||||
web_page: new WebPageLoader(),
|
||||
qna_pair: new LocalQnaPairLoader(),
|
||||
};
|
||||
return loaders[dataType];
|
||||
}
|
||||
|
||||
static getChunker(dataType: DataType) {
|
||||
const chunkers: { [t in DataType]: BaseChunker } = {
|
||||
pdf_file: new PdfFileChunker(),
|
||||
web_page: new WebPageChunker(),
|
||||
qna_pair: new QnaPairChunker(),
|
||||
};
|
||||
return chunkers[dataType];
|
||||
}
|
||||
|
||||
public async add(dataType: DataType, url: RemoteInput) {
|
||||
const loader = EmbedChain.getLoader(dataType);
|
||||
const chunker = EmbedChain.getChunker(dataType);
|
||||
this.userAsks.push([dataType, url]);
|
||||
const { documents, countNewChunks } = await this.loadAndEmbed(
|
||||
loader,
|
||||
chunker,
|
||||
url
|
||||
);
|
||||
|
||||
if (this.collectMetrics) {
|
||||
const wordCount = documents.reduce(
|
||||
(sum, document) => sum + document.split(' ').length,
|
||||
0
|
||||
);
|
||||
|
||||
this.sendTelemetryEvent('add', {
|
||||
data_type: dataType,
|
||||
word_count: wordCount,
|
||||
chunks_count: countNewChunks,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async addLocal(dataType: DataType, content: LocalInput) {
|
||||
const loader = EmbedChain.getLoader(dataType);
|
||||
const chunker = EmbedChain.getChunker(dataType);
|
||||
this.userAsks.push([dataType, content]);
|
||||
const { documents, countNewChunks } = await this.loadAndEmbed(
|
||||
loader,
|
||||
chunker,
|
||||
content
|
||||
);
|
||||
|
||||
if (this.collectMetrics) {
|
||||
const wordCount = documents.reduce(
|
||||
(sum, document) => sum + document.split(' ').length,
|
||||
0
|
||||
);
|
||||
|
||||
this.sendTelemetryEvent('add_local', {
|
||||
data_type: dataType,
|
||||
word_count: wordCount,
|
||||
chunks_count: countNewChunks,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected async loadAndEmbed(
|
||||
loader: any,
|
||||
chunker: BaseChunker,
|
||||
src: Input
|
||||
): Promise<{
|
||||
documents: string[];
|
||||
metadatas: Metadata[];
|
||||
ids: string[];
|
||||
countNewChunks: number;
|
||||
}> {
|
||||
const embeddingsData = await chunker.createChunks(loader, src);
|
||||
let { documents, ids, metadatas } = embeddingsData;
|
||||
|
||||
const existingDocs = await this.collection.get({ ids });
|
||||
const existingIds = new Set(existingDocs.ids);
|
||||
|
||||
if (existingIds.size > 0) {
|
||||
const dataDict: DataDict = {};
|
||||
for (let i = 0; i < ids.length; i += 1) {
|
||||
const id = ids[i];
|
||||
if (!existingIds.has(id)) {
|
||||
dataDict[id] = { doc: documents[i], meta: metadatas[i] };
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(dataDict).length === 0) {
|
||||
console.log(`All data from ${src} already exists in the database.`);
|
||||
return { documents: [], metadatas: [], ids: [], countNewChunks: 0 };
|
||||
}
|
||||
ids = Object.keys(dataDict);
|
||||
const dataValues = Object.values(dataDict);
|
||||
documents = dataValues.map(({ doc }) => doc);
|
||||
metadatas = dataValues.map(({ meta }) => meta);
|
||||
}
|
||||
|
||||
const countBeforeAddition = await this.count();
|
||||
await this.collection.add({ documents, metadatas, ids });
|
||||
const countNewChunks = (await this.count()) - countBeforeAddition;
|
||||
console.log(
|
||||
`Successfully saved ${src}. New chunks count: ${countNewChunks}`
|
||||
);
|
||||
return { documents, metadatas, ids, countNewChunks };
|
||||
}
|
||||
|
||||
static async formatResult(
|
||||
results: QueryResponse
|
||||
): Promise<FormattedResult[]> {
|
||||
return results.documents[0].map((document: any, index: number) => {
|
||||
const metadata = results.metadatas[0][index] || {};
|
||||
// TODO: Add proper error handling
|
||||
const distance = results.distances ? results.distances[0][index] : null;
|
||||
return [new Document({ pageContent: document, metadata }), distance];
|
||||
});
|
||||
}
|
||||
|
||||
static async getOpenAiAnswer(prompt: string) {
|
||||
const messages: OpenAI.Chat.CreateChatCompletionRequestMessage[] = [
|
||||
{ role: 'user', content: prompt },
|
||||
];
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-3.5-turbo',
|
||||
messages,
|
||||
temperature: 0,
|
||||
max_tokens: 1000,
|
||||
top_p: 1,
|
||||
});
|
||||
return (
|
||||
response.choices[0].message?.content ?? 'Response could not be processed.'
|
||||
);
|
||||
}
|
||||
|
||||
protected async retrieveFromDatabase(inputQuery: string) {
|
||||
const result = await this.collection.query({
|
||||
nResults: 1,
|
||||
queryTexts: [inputQuery],
|
||||
});
|
||||
const resultFormatted = await EmbedChain.formatResult(result);
|
||||
const content = resultFormatted[0][0].pageContent;
|
||||
return content;
|
||||
}
|
||||
|
||||
static generatePrompt(inputQuery: string, context: any) {
|
||||
const prompt = `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.\n${context}\nQuery: ${inputQuery}\nHelpful Answer:`;
|
||||
return prompt;
|
||||
}
|
||||
|
||||
static async getAnswerFromLlm(prompt: string) {
|
||||
const answer = await EmbedChain.getOpenAiAnswer(prompt);
|
||||
return answer;
|
||||
}
|
||||
|
||||
public async query(inputQuery: string) {
|
||||
const context = await this.retrieveFromDatabase(inputQuery);
|
||||
const prompt = EmbedChain.generatePrompt(inputQuery, context);
|
||||
const answer = await EmbedChain.getAnswerFromLlm(prompt);
|
||||
this.sendTelemetryEvent('query');
|
||||
return answer;
|
||||
}
|
||||
|
||||
public async dryRun(input_query: string) {
|
||||
const context = await this.retrieveFromDatabase(input_query);
|
||||
const prompt = EmbedChain.generatePrompt(input_query, context);
|
||||
return prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the number of embeddings.
|
||||
* @returns {Promise<number>}: The number of embeddings.
|
||||
*/
|
||||
public count(): Promise<number> {
|
||||
return this.collection.count();
|
||||
}
|
||||
|
||||
protected async sendTelemetryEvent(method: Method, extraMetadata?: object) {
|
||||
if (!this.collectMetrics) {
|
||||
return;
|
||||
}
|
||||
const url = 'https://api.embedchain.ai/api/v1/telemetry/';
|
||||
|
||||
// Read package version from filesystem (because it's not in the ts root dir)
|
||||
const packageJsonPath = path.join(__dirname, '..', 'package.json');
|
||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
||||
|
||||
const metadata = {
|
||||
s_id: this.sId,
|
||||
version: packageJson.version,
|
||||
method,
|
||||
language: 'js',
|
||||
...extraMetadata,
|
||||
};
|
||||
|
||||
const maxRetries = 3;
|
||||
|
||||
// Retry the fetch
|
||||
for (let i = 0; i < maxRetries; i += 1) {
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ metadata }),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// Break out of the loop if the request was successful
|
||||
break;
|
||||
} else {
|
||||
// Log the unsuccessful response (optional)
|
||||
console.error(
|
||||
`Telemetry: Attempt ${i + 1} failed with status:`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// Log the error (optional)
|
||||
console.error(`Telemetry: Attempt ${i + 1} failed with error:`, error);
|
||||
}
|
||||
|
||||
// If this was the last attempt, throw an error or handle the failure
|
||||
if (i === maxRetries - 1) {
|
||||
console.error('Telemetry: Max retries reached');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class EmbedChainApp extends EmbedChain {
|
||||
// The EmbedChain app.
|
||||
// Has two functions: add and query.
|
||||
// adds(dataType, url): adds the data from the given URL to the vector db.
|
||||
// query(query): finds answer to the given query using vector database and LLM.
|
||||
}
|
||||
|
||||
export { EmbedChainApp };
|
||||
@@ -1,7 +0,0 @@
|
||||
import { EmbedChainApp } from './embedchain';
|
||||
|
||||
export const App = async () => {
|
||||
const app = new EmbedChainApp();
|
||||
await app.initApp;
|
||||
return app;
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { Input, LoaderResult } from '../models';
|
||||
|
||||
export abstract class BaseLoader {
|
||||
abstract loadData(src: Input): Promise<LoaderResult>;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { LoaderResult, QnaPair } from '../models';
|
||||
import { BaseLoader } from './BaseLoader';
|
||||
|
||||
class LocalQnaPairLoader extends BaseLoader {
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
async loadData(content: QnaPair): Promise<LoaderResult> {
|
||||
const [question, answer] = content;
|
||||
const contentText = `Q: ${question}\nA: ${answer}`;
|
||||
const metaData = {
|
||||
url: 'local',
|
||||
};
|
||||
return [
|
||||
{
|
||||
content: contentText,
|
||||
metaData,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export { LocalQnaPairLoader };
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { TextContent } from 'pdfjs-dist/types/src/display/api';
|
||||
|
||||
import type { LoaderResult, Metadata } from '../models';
|
||||
import { cleanString } from '../utils';
|
||||
import { BaseLoader } from './BaseLoader';
|
||||
|
||||
const pdfjsLib = require('pdfjs-dist');
|
||||
|
||||
interface Page {
|
||||
page_content: string;
|
||||
}
|
||||
|
||||
class PdfFileLoader extends BaseLoader {
|
||||
static async getPagesFromPdf(url: string): Promise<Page[]> {
|
||||
const loadingTask = pdfjsLib.getDocument(url);
|
||||
const pdf = await loadingTask.promise;
|
||||
const { numPages } = pdf;
|
||||
|
||||
const promises = Array.from({ length: numPages }, async (_, i) => {
|
||||
const page = await pdf.getPage(i + 1);
|
||||
const pageText: TextContent = await page.getTextContent();
|
||||
const pageContent: string = pageText.items
|
||||
.map((item) => ('str' in item ? item.str : ''))
|
||||
.join(' ');
|
||||
|
||||
return {
|
||||
page_content: pageContent,
|
||||
};
|
||||
});
|
||||
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
async loadData(url: string): Promise<LoaderResult> {
|
||||
const pages: Page[] = await PdfFileLoader.getPagesFromPdf(url);
|
||||
const output: LoaderResult = [];
|
||||
|
||||
if (!pages.length) {
|
||||
throw new Error('No data found');
|
||||
}
|
||||
|
||||
pages.forEach((page) => {
|
||||
let content: string = page.page_content;
|
||||
content = cleanString(content);
|
||||
const metaData: Metadata = {
|
||||
url,
|
||||
};
|
||||
output.push({
|
||||
content,
|
||||
metaData,
|
||||
});
|
||||
});
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
export { PdfFileLoader };
|
||||
@@ -1,51 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
import { cleanString } from '../utils';
|
||||
import { BaseLoader } from './BaseLoader';
|
||||
|
||||
class WebPageLoader extends BaseLoader {
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
async loadData(url: string) {
|
||||
const response = await axios.get(url);
|
||||
const html = response.data;
|
||||
const dom = new JSDOM(html);
|
||||
const { document } = dom.window;
|
||||
const unwantedTags = [
|
||||
'nav',
|
||||
'aside',
|
||||
'form',
|
||||
'header',
|
||||
'noscript',
|
||||
'svg',
|
||||
'canvas',
|
||||
'footer',
|
||||
'script',
|
||||
'style',
|
||||
];
|
||||
unwantedTags.forEach((tagName) => {
|
||||
const elements = document.getElementsByTagName(tagName);
|
||||
Array.from(elements).forEach((element) => {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
(element as HTMLElement).textContent = ' ';
|
||||
});
|
||||
});
|
||||
|
||||
const output = [];
|
||||
let content = document.body.textContent;
|
||||
if (!content) {
|
||||
throw new Error('Web page content is empty.');
|
||||
}
|
||||
content = cleanString(content);
|
||||
const metaData = {
|
||||
url,
|
||||
};
|
||||
output.push({
|
||||
content,
|
||||
metaData,
|
||||
});
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
export { WebPageLoader };
|
||||
@@ -1,6 +0,0 @@
|
||||
import { BaseLoader } from './BaseLoader';
|
||||
import { LocalQnaPairLoader } from './LocalQnaPair';
|
||||
import { PdfFileLoader } from './PdfFile';
|
||||
import { WebPageLoader } from './WebPage';
|
||||
|
||||
export { BaseLoader, LocalQnaPairLoader, PdfFileLoader, WebPageLoader };
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Metadata } from './Metadata';
|
||||
|
||||
export type ChunkResult = {
|
||||
documents: string[];
|
||||
ids: string[];
|
||||
metadatas: Metadata[];
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { ChunkResult } from './ChunkResult';
|
||||
|
||||
type Data = {
|
||||
doc: ChunkResult['documents'][0];
|
||||
meta: ChunkResult['metadatas'][0];
|
||||
};
|
||||
|
||||
export type DataDict = {
|
||||
[id: string]: Data;
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
export type DataType = 'pdf_file' | 'web_page' | 'qna_pair';
|
||||
@@ -1,3 +0,0 @@
|
||||
import type { Document } from 'langchain/document';
|
||||
|
||||
export type FormattedResult = [Document, number | null];
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { QnaPair } from './QnAPair';
|
||||
|
||||
export type RemoteInput = string;
|
||||
|
||||
export type LocalInput = QnaPair;
|
||||
|
||||
export type Input = RemoteInput | LocalInput;
|
||||
@@ -1,3 +0,0 @@
|
||||
import type { Metadata } from './Metadata';
|
||||
|
||||
export type LoaderResult = { content: any; metaData: Metadata }[];
|
||||
@@ -1,3 +0,0 @@
|
||||
export type Metadata = {
|
||||
url: string;
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
export type Method = 'init' | 'query' | 'add' | 'add_local';
|
||||
@@ -1,4 +0,0 @@
|
||||
type Question = string;
|
||||
type Answer = string;
|
||||
|
||||
export type QnaPair = [Question, Answer];
|
||||
@@ -1,21 +0,0 @@
|
||||
import { DataDict } from './DataDict';
|
||||
import { DataType } from './DataType';
|
||||
import { FormattedResult } from './FormattedResult';
|
||||
import { Input, LocalInput, RemoteInput } from './Input';
|
||||
import { LoaderResult } from './LoaderResult';
|
||||
import { Metadata } from './Metadata';
|
||||
import { Method } from './Method';
|
||||
import { QnaPair } from './QnAPair';
|
||||
|
||||
export {
|
||||
DataDict,
|
||||
DataType,
|
||||
FormattedResult,
|
||||
Input,
|
||||
LoaderResult,
|
||||
LocalInput,
|
||||
Metadata,
|
||||
Method,
|
||||
QnaPair,
|
||||
RemoteInput,
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
/**
|
||||
* This function takes in a string and performs a series of text cleaning operations.
|
||||
* @param {str} text: The text to be cleaned. This is expected to be a string.
|
||||
* @returns {str}: The cleaned text after all the cleaning operations have been performed.
|
||||
*/
|
||||
export function cleanString(text: string): string {
|
||||
// Replacement of newline characters:
|
||||
let cleanedText = text.replace(/\n/g, ' ');
|
||||
|
||||
// Stripping and reducing multiple spaces to single:
|
||||
cleanedText = cleanedText.trim().replace(/\s+/g, ' ');
|
||||
|
||||
// Removing backslashes:
|
||||
cleanedText = cleanedText.replace(/\\/g, '');
|
||||
|
||||
// Replacing hash characters:
|
||||
cleanedText = cleanedText.replace(/#/g, ' ');
|
||||
|
||||
// Eliminating consecutive non-alphanumeric characters:
|
||||
// This regex identifies consecutive non-alphanumeric characters (i.e., not a word character [a-zA-Z0-9_] and not a whitespace) in the string
|
||||
// and replaces each group of such characters with a single occurrence of that character.
|
||||
// For example, "!!! hello !!!" would become "! hello !".
|
||||
cleanedText = cleanedText.replace(/([^\w\s])\1*/g, '$1');
|
||||
|
||||
return cleanedText;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
class BaseVectorDB {
|
||||
initDb: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
this.initDb = this.getClientAndCollection();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
protected async getClientAndCollection(): Promise<void> {
|
||||
throw new Error('getClientAndCollection() method is not implemented');
|
||||
}
|
||||
}
|
||||
|
||||
export { BaseVectorDB };
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { Collection } from 'chromadb';
|
||||
import { ChromaClient, OpenAIEmbeddingFunction } from 'chromadb';
|
||||
|
||||
import { BaseVectorDB } from './BaseVectorDb';
|
||||
|
||||
const embedder = new OpenAIEmbeddingFunction({
|
||||
openai_api_key: process.env.OPENAI_API_KEY ?? '',
|
||||
});
|
||||
|
||||
class ChromaDB extends BaseVectorDB {
|
||||
client: ChromaClient | undefined;
|
||||
|
||||
collection: Collection | null = null;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected async getClientAndCollection(): Promise<void> {
|
||||
this.client = new ChromaClient({ path: 'http://localhost:8000' });
|
||||
try {
|
||||
this.collection = await this.client.getCollection({
|
||||
name: 'embedchain_store',
|
||||
embeddingFunction: embedder,
|
||||
});
|
||||
} catch (err) {
|
||||
if (!this.collection) {
|
||||
this.collection = await this.client.createCollection({
|
||||
name: 'embedchain_store',
|
||||
embeddingFunction: embedder,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { ChromaDB };
|
||||
@@ -1,3 +0,0 @@
|
||||
import { ChromaDB } from './ChromaDb';
|
||||
|
||||
export { ChromaDB };
|
||||
@@ -1,9 +0,0 @@
|
||||
const { EmbedChainApp } = require("./embedchain/embedchain");
|
||||
|
||||
async function App() {
|
||||
const app = new EmbedChainApp();
|
||||
await app.init_app;
|
||||
return app;
|
||||
}
|
||||
|
||||
module.exports = { App };
|
||||
@@ -1,5 +0,0 @@
|
||||
module.exports = {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
testPathIgnorePatterns: ['.d.ts'],
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
module.exports = {
|
||||
'*.{js,ts}': ['eslint --fix', 'eslint'],
|
||||
'**/*.ts?(x)': () => 'npm run check-types',
|
||||
'*.json': ['prettier --write'],
|
||||
};
|
||||
Generated
-18457
File diff suppressed because it is too large
Load Diff
@@ -1,53 +0,0 @@
|
||||
{
|
||||
"name": "embedchain",
|
||||
"version": "0.0.8",
|
||||
"description": "embedchain is a framework to easily create LLM powered bots over any dataset",
|
||||
"main": "dist/index.js",
|
||||
"types": "types/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"types"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json --listFiles",
|
||||
"prepare": "husky install",
|
||||
"test": "jest",
|
||||
"check-types": "tsc --noEmit --pretty"
|
||||
},
|
||||
"author": "Taranjeet Singh",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"axios": "^1.4.0",
|
||||
"chromadb": "^1.5.6",
|
||||
"jsdom": "^22.1.0",
|
||||
"langchain": "^0.0.136",
|
||||
"openai": "^4.3.1",
|
||||
"pdfjs-dist": "^3.8.162",
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "^17.1.2",
|
||||
"@commitlint/config-conventional": "^17.1.0",
|
||||
"@commitlint/cz-commitlint": "^17.1.2",
|
||||
"@types/jest": "^29.5.1",
|
||||
"@types/jsdom": "^21.1.1",
|
||||
"@typescript-eslint/eslint-plugin": "^5.41.0",
|
||||
"@typescript-eslint/parser": "^5.41.0",
|
||||
"eslint": "^8.34.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-config-airbnb-typescript": "^17.0.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-plugin-import": "^2.27.5",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-simple-import-sort": "^8.0.0",
|
||||
"eslint-plugin-testing-library": "^5.9.1",
|
||||
"eslint-plugin-unused-imports": "^2.0.0",
|
||||
"husky": "^8.0.1",
|
||||
"jest": "^29.5.0",
|
||||
"lint-staged": "^13.0.3",
|
||||
"prettier": "^2.7.1",
|
||||
"ts-jest": "^29.1.0",
|
||||
"ts-loader": "^9.4.2",
|
||||
"typescript": "^5.2.2"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["embedchain/__tests__"]
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es6",
|
||||
"module": "CommonJS",
|
||||
"strict": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "embedchain",
|
||||
"sourceMap": true,
|
||||
"declaration": true,
|
||||
"declarationDir": "types",
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["embedchain/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
+12
-18
@@ -3,7 +3,6 @@ import concurrent.futures
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
import requests
|
||||
@@ -33,6 +32,8 @@ from embedchain.utils.misc import validate_config
|
||||
from embedchain.vectordb.base import BaseVectorDB
|
||||
from embedchain.vectordb.chroma import ChromaDB
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class App(EmbedChain):
|
||||
@@ -51,10 +52,10 @@ class App(EmbedChain):
|
||||
embedding_model: BaseEmbedder = None,
|
||||
llm: BaseLlm = None,
|
||||
config_data: dict = None,
|
||||
log_level=logging.WARN,
|
||||
auto_deploy: bool = False,
|
||||
chunker: ChunkerConfig = None,
|
||||
cache_config: CacheConfig = None,
|
||||
log_level: int = logging.WARN,
|
||||
):
|
||||
"""
|
||||
Initialize a new `App` instance.
|
||||
@@ -69,8 +70,6 @@ class App(EmbedChain):
|
||||
:type llm: BaseLlm, optional
|
||||
:param config_data: Config dictionary, defaults to None
|
||||
:type config_data: dict, optional
|
||||
: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
|
||||
:raises Exception: If an error occurs while creating the pipeline
|
||||
@@ -84,9 +83,6 @@ class App(EmbedChain):
|
||||
if name and config:
|
||||
raise Exception("Cannot provide both name and config. Please provide only one of them.")
|
||||
|
||||
logging.basicConfig(level=log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
# Initialize the metadata db for the app
|
||||
setup_engine(database_uri=os.environ.get("EMBEDCHAIN_DB_URI"))
|
||||
init_db()
|
||||
@@ -102,7 +98,7 @@ class App(EmbedChain):
|
||||
|
||||
self.config = config or AppConfig()
|
||||
self.name = self.config.name
|
||||
self.config.id = self.local_id = str(uuid.uuid4()) if self.config.id is None else self.config.id
|
||||
self.config.id = self.local_id = "default-app-id" if self.config.id is None else self.config.id
|
||||
|
||||
if id is not None:
|
||||
# Init client first since user is trying to fetch the pipeline
|
||||
@@ -239,7 +235,7 @@ class App(EmbedChain):
|
||||
response.raise_for_status()
|
||||
return response.status_code == 200
|
||||
except Exception as e:
|
||||
self.logger.exception(f"Error occurred during file upload: {str(e)}")
|
||||
logger.exception(f"Error occurred during file upload: {str(e)}")
|
||||
print("❌ Error occurred during file upload!")
|
||||
return False
|
||||
|
||||
@@ -273,7 +269,7 @@ class App(EmbedChain):
|
||||
metadata = {"file_path": data_value, "s3_key": s3_key}
|
||||
data_value = presigned_url
|
||||
else:
|
||||
self.logger.error(f"File upload failed for hash: {data_hash}")
|
||||
logger.error(f"File upload failed for hash: {data_hash}")
|
||||
return False
|
||||
else:
|
||||
if data_type == "qna_pair":
|
||||
@@ -295,7 +291,7 @@ class App(EmbedChain):
|
||||
data_sources = self.db_session.query(DataSource).filter_by(app_id=self.local_id).all()
|
||||
results = []
|
||||
for row in data_sources:
|
||||
results.append({"data_type": row.data_type, "data_value": row.data_value, "metadata": row.metadata})
|
||||
results.append({"data_type": row.type, "data_value": row.value, "metadata": row.meta_data})
|
||||
return results
|
||||
|
||||
def deploy(self):
|
||||
@@ -358,15 +354,13 @@ class App(EmbedChain):
|
||||
elif config and isinstance(config, dict):
|
||||
config_data = config
|
||||
else:
|
||||
logging.error(
|
||||
logger.error(
|
||||
"Please provide either a config file path (YAML or JSON) or a config dictionary. Falling back to defaults because no config is provided.", # noqa: E501
|
||||
)
|
||||
config_data = {}
|
||||
|
||||
try:
|
||||
validate_config(config_data)
|
||||
except Exception as e:
|
||||
raise Exception(f"Error occurred while validating the config. Error: {str(e)}")
|
||||
# Validate the config
|
||||
validate_config(config_data)
|
||||
|
||||
app_config_data = config_data.get("app", {}).get("config", {})
|
||||
vector_db_config_data = config_data.get("vectordb", {})
|
||||
@@ -478,12 +472,12 @@ class App(EmbedChain):
|
||||
EvalMetric.GROUNDEDNESS.value,
|
||||
]
|
||||
|
||||
logging.info(f"Collecting data from {len(queries)} questions for evaluation...")
|
||||
logger.info(f"Collecting data from {len(queries)} questions for evaluation...")
|
||||
dataset = []
|
||||
for q, a, c in zip(queries, answers, contexts):
|
||||
dataset.append(EvalData(question=q, answer=a, contexts=c))
|
||||
|
||||
logging.info(f"Evaluating {len(dataset)} data points...")
|
||||
logger.info(f"Evaluating {len(dataset)} data points...")
|
||||
result = {}
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
|
||||
future_to_metric = {executor.submit(self._eval, dataset, metric): metric for metric in metrics}
|
||||
|
||||
@@ -17,6 +17,8 @@ except ModuleNotFoundError:
|
||||
) from None
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
intents = discord.Intents.default()
|
||||
intents.message_content = True
|
||||
client = discord.Client(intents=intents)
|
||||
@@ -37,7 +39,7 @@ class DiscordBot(BaseBot):
|
||||
self.add(data)
|
||||
response = f"Added data from: {data}"
|
||||
except Exception:
|
||||
logging.exception(f"Failed to add data {data}.")
|
||||
logger.exception(f"Failed to add data {data}.")
|
||||
response = "Some error occurred while adding data."
|
||||
return response
|
||||
|
||||
@@ -45,7 +47,7 @@ class DiscordBot(BaseBot):
|
||||
try:
|
||||
response = self.query(message)
|
||||
except Exception:
|
||||
logging.exception(f"Failed to query {message}.")
|
||||
logger.exception(f"Failed to query {message}.")
|
||||
response = "An error occurred. Please try again!"
|
||||
return response
|
||||
|
||||
@@ -60,7 +62,7 @@ class DiscordBot(BaseBot):
|
||||
async def query_command(interaction: discord.Interaction, question: str):
|
||||
await interaction.response.defer()
|
||||
member = client.guilds[0].get_member(client.user.id)
|
||||
logging.info(f"User: {member}, Query: {question}")
|
||||
logger.info(f"User: {member}, Query: {question}")
|
||||
try:
|
||||
answer = discord_bot.ask_bot(question)
|
||||
if args.include_question:
|
||||
@@ -70,20 +72,20 @@ async def query_command(interaction: discord.Interaction, question: str):
|
||||
await interaction.followup.send(response)
|
||||
except Exception as e:
|
||||
await interaction.followup.send("An error occurred. Please try again!")
|
||||
logging.error("Error occurred during 'query' command:", e)
|
||||
logger.error("Error occurred during 'query' command:", e)
|
||||
|
||||
|
||||
@tree.command(name="add", description="add new content to the embedchain database")
|
||||
async def add_command(interaction: discord.Interaction, url_or_text: str):
|
||||
await interaction.response.defer()
|
||||
member = client.guilds[0].get_member(client.user.id)
|
||||
logging.info(f"User: {member}, Add: {url_or_text}")
|
||||
logger.info(f"User: {member}, Add: {url_or_text}")
|
||||
try:
|
||||
response = discord_bot.add_data(url_or_text)
|
||||
await interaction.followup.send(response)
|
||||
except Exception as e:
|
||||
await interaction.followup.send("An error occurred. Please try again!")
|
||||
logging.error("Error occurred during 'add' command:", e)
|
||||
logger.error("Error occurred during 'add' command:", e)
|
||||
|
||||
|
||||
@tree.command(name="ping", description="Simple ping pong command")
|
||||
@@ -96,7 +98,7 @@ async def on_app_command_error(interaction: discord.Interaction, error: discord.
|
||||
if isinstance(error, commands.CommandNotFound):
|
||||
await interaction.followup.send("Invalid command. Please refer to the documentation for correct syntax.")
|
||||
else:
|
||||
logging.error("Error occurred during command execution:", error)
|
||||
logger.error("Error occurred during command execution:", error)
|
||||
|
||||
|
||||
@client.event
|
||||
@@ -104,8 +106,8 @@ async def on_ready():
|
||||
# TODO: Sync in admin command, to not hit rate limits.
|
||||
# This might be overkill for most users, and it would require to set a guild or user id, where sync is allowed.
|
||||
await tree.sync()
|
||||
logging.debug("Command tree synced")
|
||||
logging.info(f"Logged in as {client.user.name}")
|
||||
logger.debug("Command tree synced")
|
||||
logger.info(f"Logged in as {client.user.name}")
|
||||
|
||||
|
||||
def start_command():
|
||||
|
||||
@@ -19,6 +19,8 @@ except ModuleNotFoundError:
|
||||
) from None
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
|
||||
|
||||
|
||||
@@ -42,10 +44,10 @@ class SlackBot(BaseBot):
|
||||
try:
|
||||
response = self.chat_bot.chat(question)
|
||||
self.send_slack_message(message["channel"], response)
|
||||
logging.info("Query answered successfully!")
|
||||
logger.info("Query answered successfully!")
|
||||
except Exception as e:
|
||||
self.send_slack_message(message["channel"], "An error occurred. Please try again!")
|
||||
logging.error("Error occurred during 'query' command:", e)
|
||||
logger.error("Error occurred during 'query' command:", e)
|
||||
elif text.startswith("add"):
|
||||
_, data_type, url_or_text = text.split(" ", 2)
|
||||
if url_or_text.startswith("<") and url_or_text.endswith(">"):
|
||||
@@ -55,10 +57,10 @@ class SlackBot(BaseBot):
|
||||
self.send_slack_message(message["channel"], f"Added {data_type} : {url_or_text}")
|
||||
except ValueError as e:
|
||||
self.send_slack_message(message["channel"], f"Error: {str(e)}")
|
||||
logging.error("Error occurred during 'add' command:", e)
|
||||
logger.error("Error occurred during 'add' command:", e)
|
||||
except Exception as e:
|
||||
self.send_slack_message(message["channel"], f"Failed to add {data_type} : {url_or_text}")
|
||||
logging.error("Error occurred during 'add' command:", e)
|
||||
logger.error("Error occurred during 'add' command:", e)
|
||||
|
||||
def send_slack_message(self, channel, message):
|
||||
response = self.client.chat_postMessage(channel=channel, text=message)
|
||||
@@ -68,7 +70,7 @@ class SlackBot(BaseBot):
|
||||
app = Flask(__name__)
|
||||
|
||||
def signal_handler(sig, frame):
|
||||
logging.info("\nGracefully shutting down the SlackBot...")
|
||||
logger.info("\nGracefully shutting down the SlackBot...")
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
@@ -8,6 +8,8 @@ from embedchain.helpers.json_serializable import register_deserializable
|
||||
|
||||
from .base import BaseBot
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class WhatsAppBot(BaseBot):
|
||||
@@ -35,7 +37,7 @@ class WhatsAppBot(BaseBot):
|
||||
self.add(data)
|
||||
response = f"Added data from: {data}"
|
||||
except Exception:
|
||||
logging.exception(f"Failed to add data {data}.")
|
||||
logger.exception(f"Failed to add data {data}.")
|
||||
response = "Some error occurred while adding data."
|
||||
return response
|
||||
|
||||
@@ -43,7 +45,7 @@ class WhatsAppBot(BaseBot):
|
||||
try:
|
||||
response = self.query(message)
|
||||
except Exception:
|
||||
logging.exception(f"Failed to query {message}.")
|
||||
logger.exception(f"Failed to query {message}.")
|
||||
response = "An error occurred. Please try again!"
|
||||
return response
|
||||
|
||||
@@ -51,7 +53,7 @@ class WhatsAppBot(BaseBot):
|
||||
app = self.flask.Flask(__name__)
|
||||
|
||||
def signal_handler(sig, frame):
|
||||
logging.info("\nGracefully shutting down the WhatsAppBot...")
|
||||
logger.info("\nGracefully shutting down the WhatsAppBot...")
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
+4
-2
@@ -14,6 +14,8 @@ from gptcache.similarity_evaluation.distance import \
|
||||
from gptcache.similarity_evaluation.exact_match import \
|
||||
ExactMatchEvaluation # noqa: F401
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def gptcache_pre_function(data: dict[str, Any], **params: dict[str, Any]):
|
||||
return data["input_query"]
|
||||
@@ -24,12 +26,12 @@ def gptcache_data_manager(vector_dimension):
|
||||
|
||||
|
||||
def gptcache_data_convert(cache_data):
|
||||
logging.info("[Cache] Cache hit, returning cache data...")
|
||||
logger.info("[Cache] Cache hit, returning cache data...")
|
||||
return cache_data
|
||||
|
||||
|
||||
def gptcache_update_cache_callback(llm_data, update_cache_func, *args, **kwargs):
|
||||
logging.info("[Cache] Cache missed, updating cache...")
|
||||
logger.info("[Cache] Cache missed, updating cache...")
|
||||
update_cache_func(Answer(llm_data, CacheDataType.STR))
|
||||
return llm_data
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ from embedchain.config.add_config import ChunkerConfig
|
||||
from embedchain.helpers.json_serializable import JSONSerializable
|
||||
from embedchain.models.data_type import DataType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BaseChunker(JSONSerializable):
|
||||
def __init__(self, text_splitter):
|
||||
@@ -27,7 +29,7 @@ class BaseChunker(JSONSerializable):
|
||||
chunk_ids = []
|
||||
id_map = {}
|
||||
min_chunk_size = config.min_chunk_size if config is not None else 1
|
||||
logging.info(f"Skipping chunks smaller than {min_chunk_size} characters")
|
||||
logger.info(f"Skipping chunks smaller than {min_chunk_size} characters")
|
||||
data_result = loader.load_data(src)
|
||||
data_records = data_result["data"]
|
||||
doc_id = data_result["doc_id"]
|
||||
@@ -82,4 +84,4 @@ class BaseChunker(JSONSerializable):
|
||||
|
||||
@staticmethod
|
||||
def get_word_count(documents) -> int:
|
||||
return sum([len(document.split(" ")) for document in documents])
|
||||
return sum(len(document.split(" ")) for document in documents)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
from typing import Optional
|
||||
|
||||
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||
|
||||
from embedchain.chunkers.base_chunker import BaseChunker
|
||||
from embedchain.config.add_config import ChunkerConfig
|
||||
from embedchain.helpers.json_serializable import register_deserializable
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class ExcelFileChunker(BaseChunker):
|
||||
"""Chunker for Excel file."""
|
||||
|
||||
def __init__(self, config: Optional[ChunkerConfig] = None):
|
||||
if config is None:
|
||||
config = ChunkerConfig(chunk_size=1000, chunk_overlap=0, length_function=len)
|
||||
text_splitter = RecursiveCharacterTextSplitter(
|
||||
chunk_size=config.chunk_size,
|
||||
chunk_overlap=config.chunk_overlap,
|
||||
length_function=config.length_function,
|
||||
)
|
||||
super().__init__(text_splitter)
|
||||
+10
-8
@@ -7,6 +7,8 @@ import requests
|
||||
|
||||
from embedchain.constants import CONFIG_DIR, CONFIG_FILE
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, api_key=None, host="https://apiv2.embedchain.ai"):
|
||||
@@ -24,7 +26,7 @@ class Client:
|
||||
else:
|
||||
if "api_key" in self.config_data:
|
||||
self.api_key = self.config_data["api_key"]
|
||||
logging.info("API key loaded successfully!")
|
||||
logger.info("API key loaded successfully!")
|
||||
else:
|
||||
raise ValueError(
|
||||
"You are not logged in. Please obtain an API key from https://app.embedchain.ai/settings/keys/"
|
||||
@@ -64,7 +66,7 @@ class Client:
|
||||
with open(CONFIG_FILE, "w") as config_file:
|
||||
json.dump(self.config_data, config_file, indent=4)
|
||||
|
||||
logging.info("API key saved successfully!")
|
||||
logger.info("API key saved successfully!")
|
||||
|
||||
def clear(self):
|
||||
if "api_key" in self.config_data:
|
||||
@@ -72,17 +74,17 @@ class Client:
|
||||
with open(CONFIG_FILE, "w") as config_file:
|
||||
json.dump(self.config_data, config_file, indent=4)
|
||||
self.api_key = None
|
||||
logging.info("API key deleted successfully!")
|
||||
logger.info("API key deleted successfully!")
|
||||
else:
|
||||
logging.warning("API key not found in the configuration file.")
|
||||
logger.warning("API key not found in the configuration file.")
|
||||
|
||||
def update(self, api_key):
|
||||
if self.check(api_key):
|
||||
self.api_key = api_key
|
||||
self.save()
|
||||
logging.info("API key updated successfully!")
|
||||
logger.info("API key updated successfully!")
|
||||
else:
|
||||
logging.warning("Invalid API key provided. API key not updated.")
|
||||
logger.warning("Invalid API key provided. API key not updated.")
|
||||
|
||||
def check(self, api_key):
|
||||
validation_url = f"{self.host}/api/v1/accounts/api_keys/validate/"
|
||||
@@ -90,8 +92,8 @@ class Client:
|
||||
if response.status_code == 200:
|
||||
return True
|
||||
else:
|
||||
logging.warning(f"Response from API: {response.text}")
|
||||
logging.warning("Invalid API key. Unable to validate.")
|
||||
logger.warning(f"Response from API: {response.text}")
|
||||
logger.warning("Invalid API key. Unable to validate.")
|
||||
return False
|
||||
|
||||
def get(self):
|
||||
|
||||
@@ -6,6 +6,7 @@ from .base_config import BaseConfig
|
||||
from .cache_config import CacheConfig
|
||||
from .embedder.base import BaseEmbedderConfig
|
||||
from .embedder.base import BaseEmbedderConfig as EmbedderConfig
|
||||
from .embedder.ollama import OllamaEmbedderConfig
|
||||
from .llm.base import BaseLlmConfig
|
||||
from .vectordb.chroma import ChromaDbConfig
|
||||
from .vectordb.elasticsearch import ElasticsearchDBConfig
|
||||
|
||||
@@ -5,6 +5,8 @@ from embedchain.config.base_config import BaseConfig
|
||||
from embedchain.helpers.json_serializable import JSONSerializable
|
||||
from embedchain.vectordb.base import BaseVectorDB
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BaseAppConfig(BaseConfig, JSONSerializable):
|
||||
"""
|
||||
@@ -36,28 +38,21 @@ class BaseAppConfig(BaseConfig, JSONSerializable):
|
||||
defaults to None
|
||||
:type collection_name: Optional[str], optional
|
||||
"""
|
||||
self._setup_logging(log_level)
|
||||
self.id = id
|
||||
self.collect_metrics = True if (collect_metrics is True or collect_metrics is None) else False
|
||||
self.collection_name = collection_name
|
||||
|
||||
if db:
|
||||
self._db = db
|
||||
logging.warning(
|
||||
logger.warning(
|
||||
"DEPRECATION WARNING: Please supply the database as the second parameter during app init. "
|
||||
"Such as `app(config=config, db=db)`."
|
||||
)
|
||||
|
||||
if collection_name:
|
||||
logging.warning("DEPRECATION WARNING: Please supply the collection name to the database config.")
|
||||
logger.warning("DEPRECATION WARNING: Please supply the collection name to the database config.")
|
||||
return
|
||||
|
||||
def _setup_logging(self, debug_level):
|
||||
level = logging.WARNING # Default level
|
||||
if debug_level is not None:
|
||||
level = getattr(logging, debug_level.upper(), None)
|
||||
if not isinstance(level, int):
|
||||
raise ValueError(f"Invalid log level: {debug_level}")
|
||||
|
||||
logging.basicConfig(format="%(asctime)s [%(name)s] [%(levelname)s] %(message)s", level=level)
|
||||
self.logger = logging.getLogger(__name__)
|
||||
def _setup_logging(self, log_level):
|
||||
logger.basicConfig(format="%(asctime)s [%(name)s] [%(levelname)s] %(message)s", level=log_level)
|
||||
self.logger = logger.getLogger(__name__)
|
||||
|
||||
@@ -11,6 +11,7 @@ class BaseEmbedderConfig:
|
||||
deployment_name: Optional[str] = None,
|
||||
vector_dimension: Optional[int] = None,
|
||||
api_key: Optional[str] = None,
|
||||
api_base: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Initialize a new instance of an embedder config class.
|
||||
@@ -24,3 +25,4 @@ class BaseEmbedderConfig:
|
||||
self.deployment_name = deployment_name
|
||||
self.vector_dimension = vector_dimension
|
||||
self.api_key = api_key
|
||||
self.api_base = api_base
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
from typing import Optional
|
||||
|
||||
from embedchain.config.embedder.base import BaseEmbedderConfig
|
||||
from embedchain.helpers.json_serializable import register_deserializable
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class OllamaEmbedderConfig(BaseEmbedderConfig):
|
||||
def __init__(
|
||||
self,
|
||||
model: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
):
|
||||
super().__init__(model)
|
||||
self.base_url = base_url or "http://localhost:11434"
|
||||
@@ -1,11 +1,13 @@
|
||||
import logging
|
||||
import re
|
||||
from string import Template
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
from embedchain.config.base_config import BaseConfig
|
||||
from embedchain.helpers.json_serializable import register_deserializable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_PROMPT = """
|
||||
You are a Q&A expert system. Your responses must always be rooted in the context provided for each query. Here are some guidelines to follow:
|
||||
|
||||
@@ -87,15 +89,20 @@ class BaseLlmConfig(BaseConfig):
|
||||
max_tokens: int = 1000,
|
||||
top_p: float = 1,
|
||||
stream: bool = False,
|
||||
online: bool = False,
|
||||
deployment_name: Optional[str] = None,
|
||||
system_prompt: Optional[str] = None,
|
||||
where: dict[str, Any] = None,
|
||||
query_type: Optional[str] = None,
|
||||
callbacks: Optional[list] = None,
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
endpoint: Optional[str] = None,
|
||||
model_kwargs: Optional[dict[str, Any]] = None,
|
||||
http_client: Optional[Any] = None,
|
||||
http_async_client: Optional[Any] = None,
|
||||
local: Optional[bool] = False,
|
||||
default_headers: Optional[Mapping[str, str]] = None,
|
||||
):
|
||||
"""
|
||||
Initializes a configuration class instance for the LLM.
|
||||
@@ -123,6 +130,8 @@ class BaseLlmConfig(BaseConfig):
|
||||
:type top_p: float, optional
|
||||
:param stream: Control if response is streamed back to user, defaults to False
|
||||
:type stream: bool, optional
|
||||
:param online: Controls whether to use internet for answering query, defaults to False
|
||||
:type online: bool, optional
|
||||
:param deployment_name: t.b.a., defaults to None
|
||||
:type deployment_name: Optional[str], optional
|
||||
:param system_prompt: System prompt string, defaults to None
|
||||
@@ -141,12 +150,14 @@ class BaseLlmConfig(BaseConfig):
|
||||
:type query_type: Optional[str], optional
|
||||
:param local: If True, the model will be run locally, defaults to False (for huggingface provider)
|
||||
:type local: Optional[bool], optional
|
||||
:param default_headers: Set additional HTTP headers to be sent with requests to OpenAI
|
||||
:type default_headers: Optional[Mapping[str, str]], optional
|
||||
:raises ValueError: If the template is not valid as template should
|
||||
contain $context and $query (and optionally $history)
|
||||
:raises ValueError: Stream is not boolean
|
||||
"""
|
||||
if template is not None:
|
||||
logging.warning(
|
||||
logger.warning(
|
||||
"The `template` argument is deprecated and will be removed in a future version. "
|
||||
+ "Please use `prompt` instead."
|
||||
)
|
||||
@@ -166,9 +177,14 @@ class BaseLlmConfig(BaseConfig):
|
||||
self.query_type = query_type
|
||||
self.callbacks = callbacks
|
||||
self.api_key = api_key
|
||||
self.base_url = base_url
|
||||
self.endpoint = endpoint
|
||||
self.model_kwargs = model_kwargs
|
||||
self.http_client = http_client
|
||||
self.http_async_client = http_async_client
|
||||
self.local = local
|
||||
self.default_headers = default_headers
|
||||
self.online = online
|
||||
|
||||
if isinstance(prompt, str):
|
||||
prompt = Template(prompt)
|
||||
|
||||
@@ -2,7 +2,7 @@ import os
|
||||
from pathlib import Path
|
||||
|
||||
ABS_PATH = os.getcwd()
|
||||
HOME_DIR = str(Path.home())
|
||||
HOME_DIR = os.environ.get("EMBEDCHAIN_CONFIG_DIR", str(Path.home()))
|
||||
CONFIG_DIR = os.path.join(HOME_DIR, ".embedchain")
|
||||
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
|
||||
SQLITE_PATH = os.path.join(CONFIG_DIR, "embedchain.db")
|
||||
|
||||
@@ -80,6 +80,7 @@ class DataFormatter(JSONSerializable):
|
||||
DataType.SLACK: "embedchain.loaders.slack.SlackLoader",
|
||||
DataType.DROPBOX: "embedchain.loaders.dropbox.DropboxLoader",
|
||||
DataType.TEXT_FILE: "embedchain.loaders.text_file.TextFileLoader",
|
||||
DataType.EXCEL_FILE: "embedchain.loaders.excel_file.ExcelFileLoader",
|
||||
}
|
||||
|
||||
if data_type == DataType.CUSTOM or loader is not None:
|
||||
@@ -127,6 +128,7 @@ class DataFormatter(JSONSerializable):
|
||||
DataType.SLACK: "embedchain.chunkers.common_chunker.CommonChunker",
|
||||
DataType.DROPBOX: "embedchain.chunkers.common_chunker.CommonChunker",
|
||||
DataType.TEXT_FILE: "embedchain.chunkers.common_chunker.CommonChunker",
|
||||
DataType.EXCEL_FILE: "embedchain.chunkers.excel_file.ExcelFileChunker",
|
||||
}
|
||||
|
||||
if chunker is not None:
|
||||
|
||||
+60
-34
@@ -6,9 +6,7 @@ from typing import Any, Optional, Union
|
||||
from dotenv import load_dotenv
|
||||
from langchain.docstore.document import Document
|
||||
|
||||
from embedchain.cache import (adapt, get_gptcache_session,
|
||||
gptcache_data_convert,
|
||||
gptcache_update_cache_callback)
|
||||
from embedchain.cache import adapt, get_gptcache_session, gptcache_data_convert, gptcache_update_cache_callback
|
||||
from embedchain.chunkers.base_chunker import BaseChunker
|
||||
from embedchain.config import AddConfig, BaseLlmConfig, ChunkerConfig
|
||||
from embedchain.config.base_app_config import BaseAppConfig
|
||||
@@ -18,13 +16,14 @@ from embedchain.embedder.base import BaseEmbedder
|
||||
from embedchain.helpers.json_serializable import JSONSerializable
|
||||
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.models.data_type import DataType, DirectDataType, IndirectDataType, SpecialDataType
|
||||
from embedchain.utils.misc import detect_datatype, is_valid_json_string
|
||||
from embedchain.vectordb.base import BaseVectorDB
|
||||
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EmbedChain(JSONSerializable):
|
||||
def __init__(
|
||||
@@ -95,13 +94,13 @@ class EmbedChain(JSONSerializable):
|
||||
|
||||
@property
|
||||
def online(self):
|
||||
return self.llm.online
|
||||
return self.llm.config.online
|
||||
|
||||
@online.setter
|
||||
def online(self, value):
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"Boolean value expected but got {type(value)}.")
|
||||
self.llm.online = value
|
||||
self.llm.config.online = value
|
||||
|
||||
def add(
|
||||
self,
|
||||
@@ -130,7 +129,14 @@ class EmbedChain(JSONSerializable):
|
||||
:type config: Optional[AddConfig], optional
|
||||
:raises ValueError: Invalid data type
|
||||
:param dry_run: Optional. A dry run displays the chunks to ensure that the loader and chunker work as intended.
|
||||
deafaults to False
|
||||
defaults to False
|
||||
:type dry_run: bool
|
||||
:param loader: The loader to use to load the data, defaults to None
|
||||
:type loader: BaseLoader, optional
|
||||
:param chunker: The chunker to use to chunk the data, defaults to None
|
||||
:type chunker: BaseChunker, optional
|
||||
:param kwargs: To read more params for the query function
|
||||
:type kwargs: dict[str, Any]
|
||||
:return: source_hash, a md5-hash of the source, in hexadecimal representation.
|
||||
:rtype: str
|
||||
"""
|
||||
@@ -143,10 +149,10 @@ class EmbedChain(JSONSerializable):
|
||||
|
||||
try:
|
||||
DataType(source)
|
||||
logging.warning(
|
||||
logger.warning(
|
||||
f"""Starting from version v0.0.40, Embedchain can automatically detect the data type. So, in the `add` method, the argument order has changed. You no longer need to specify '{source}' for the `source` argument. So the code snippet will be `.add("{data_type}", "{source}")`""" # noqa #E501
|
||||
)
|
||||
logging.warning(
|
||||
logger.warning(
|
||||
"Embedchain is swapping the arguments for you. This functionality might be deprecated in the future, so please adjust your code." # noqa #E501
|
||||
)
|
||||
source, data_type = data_type, source
|
||||
@@ -157,7 +163,7 @@ class EmbedChain(JSONSerializable):
|
||||
try:
|
||||
data_type = DataType(data_type)
|
||||
except ValueError:
|
||||
logging.info(
|
||||
logger.info(
|
||||
f"Invalid data_type: '{data_type}', using `custom` instead.\n Check docs to pass the valid data type: `https://docs.embedchain.ai/data-sources/overview`" # noqa: E501
|
||||
)
|
||||
data_type = DataType.CUSTOM
|
||||
@@ -177,6 +183,10 @@ class EmbedChain(JSONSerializable):
|
||||
if data_type in {DataType.DOCS_SITE}:
|
||||
self.is_docs_site_instance = True
|
||||
|
||||
# Convert the source to a string if it is not already
|
||||
if not isinstance(source, str):
|
||||
source = str(source)
|
||||
|
||||
# Insert the data into the 'ec_data_sources' table
|
||||
self.db_session.add(
|
||||
DataSource(
|
||||
@@ -190,12 +200,12 @@ class EmbedChain(JSONSerializable):
|
||||
try:
|
||||
self.db_session.commit()
|
||||
except Exception as e:
|
||||
logging.error(f"Error adding data source: {e}")
|
||||
logger.error(f"Error adding data source: {e}")
|
||||
self.db_session.rollback()
|
||||
|
||||
if dry_run:
|
||||
data_chunks_info = {"chunks": documents, "metadata": metadatas, "count": len(documents), "type": data_type}
|
||||
logging.debug(f"Dry run info : {data_chunks_info}")
|
||||
logger.debug(f"Dry run info : {data_chunks_info}")
|
||||
return data_chunks_info
|
||||
|
||||
# Send anonymous telemetry
|
||||
@@ -287,12 +297,19 @@ class EmbedChain(JSONSerializable):
|
||||
Loads the data from the given URL, chunks it, and adds it to database.
|
||||
|
||||
:param loader: The loader to use to load the data.
|
||||
:type loader: BaseLoader
|
||||
:param chunker: The chunker to use to chunk the data.
|
||||
:type chunker: BaseChunker
|
||||
:param src: The data to be handled by the loader. Can be a URL for
|
||||
remote sources or local content for local loaders.
|
||||
:param metadata: Optional. Metadata associated with the data source.
|
||||
:type src: Any
|
||||
:param metadata: Metadata associated with the data source.
|
||||
:type metadata: dict[str, Any], optional
|
||||
:param source_hash: Hexadecimal hash of the source.
|
||||
:param dry_run: Optional. A dry run returns chunks and doesn't update DB.
|
||||
:type source_hash: str, optional
|
||||
:param add_config: The `AddConfig` instance to use as configuration options.
|
||||
:type add_config: AddConfig, optional
|
||||
:param dry_run: A dry run returns chunks and doesn't update DB.
|
||||
:type dry_run: bool, defaults to False
|
||||
:return: (list) documents (embedded text), (list) metadata, (list) ids, (int) number of chunks
|
||||
"""
|
||||
@@ -308,12 +325,12 @@ class EmbedChain(JSONSerializable):
|
||||
new_doc_id = embeddings_data["doc_id"]
|
||||
|
||||
if existing_doc_id and existing_doc_id == new_doc_id:
|
||||
print("Doc content has not changed. Skipping creating chunks and embeddings")
|
||||
logger.info("Doc content has not changed. Skipping creating chunks and embeddings")
|
||||
return [], [], [], 0
|
||||
|
||||
# this means that doc content has changed.
|
||||
if existing_doc_id and existing_doc_id != new_doc_id:
|
||||
print("Doc content has changed. Recomputing chunks and embeddings intelligently.")
|
||||
logger.info("Doc content has changed. Recomputing chunks and embeddings intelligently.")
|
||||
self.db.delete({"doc_id": existing_doc_id})
|
||||
|
||||
# get existing ids, and discard doc if any common id exist.
|
||||
@@ -339,7 +356,7 @@ class EmbedChain(JSONSerializable):
|
||||
src_copy = src
|
||||
if len(src_copy) > 50:
|
||||
src_copy = src[:50] + "..."
|
||||
print(f"All data from {src_copy} already exists in the database.")
|
||||
logger.info(f"All data from {src_copy} already exists in the database.")
|
||||
# Make sure to return a matching return type
|
||||
return [], [], [], 0
|
||||
|
||||
@@ -378,18 +395,20 @@ class EmbedChain(JSONSerializable):
|
||||
# Chunk documents into batches of 2048 and handle each batch
|
||||
# helps wigth large loads of embeddings that hit OpenAI limits
|
||||
document_batches = [documents[i : i + 2048] for i in range(0, len(documents), 2048)]
|
||||
for batch in document_batches:
|
||||
metadata_batches = [metadatas[i : i + 2048] for i in range(0, len(metadatas), 2048)]
|
||||
id_batches = [ids[i : i + 2048] for i in range(0, len(ids), 2048)]
|
||||
for batch_docs, batch_meta, batch_ids in zip(document_batches, metadata_batches, id_batches):
|
||||
try:
|
||||
# Add only valid batches
|
||||
if batch:
|
||||
self.db.add(documents=batch, metadatas=metadatas, ids=ids, **kwargs)
|
||||
if batch_docs:
|
||||
self.db.add(documents=batch_docs, metadatas=batch_meta, ids=batch_ids, **kwargs)
|
||||
except Exception as e:
|
||||
print(f"Failed to add batch due to a bad request: {e}")
|
||||
logger.info(f"Failed to add batch due to a bad request: {e}")
|
||||
# Handle the error, e.g., by logging, retrying, or skipping
|
||||
pass
|
||||
|
||||
count_new_chunks = self.db.count() - chunks_before_addition
|
||||
print(f"Successfully saved {src} ({chunker.data_type}). New chunks count: {count_new_chunks}")
|
||||
logger.info(f"Successfully saved {str(src)[:100]} ({chunker.data_type}). New chunks count: {count_new_chunks}")
|
||||
|
||||
return list(documents), metadatas, ids, count_new_chunks
|
||||
|
||||
@@ -466,12 +485,14 @@ class EmbedChain(JSONSerializable):
|
||||
:type input_query: str
|
||||
:param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
|
||||
To persistently use a config, declare it during app init., defaults to None
|
||||
:type config: Optional[BaseLlmConfig], optional
|
||||
:type config: BaseLlmConfig, optional
|
||||
:param dry_run: A dry run does everything except send the resulting prompt to
|
||||
the LLM. The purpose is to test the prompt, not the response., defaults to False
|
||||
: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
|
||||
:type where: dict[str, str], optional
|
||||
:param citations: A boolean to indicate if db should fetch citation source
|
||||
:type citations: bool
|
||||
: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]
|
||||
@@ -488,7 +509,7 @@ class EmbedChain(JSONSerializable):
|
||||
contexts_data_for_llm_query = contexts
|
||||
|
||||
if self.cache_config is not None:
|
||||
logging.info("Cache enabled. Checking cache...")
|
||||
logger.info("Cache enabled. Checking cache...")
|
||||
answer = adapt(
|
||||
llm_handler=self.llm.query,
|
||||
cache_data_convert=gptcache_data_convert,
|
||||
@@ -533,14 +554,16 @@ class EmbedChain(JSONSerializable):
|
||||
:type input_query: str
|
||||
:param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
|
||||
To persistently use a config, declare it during app init., defaults to None
|
||||
:type config: Optional[BaseLlmConfig], optional
|
||||
:type config: BaseLlmConfig, optional
|
||||
:param dry_run: A dry run does everything except send the resulting prompt to
|
||||
the LLM. The purpose is to test the prompt, not the response., defaults to False
|
||||
:type dry_run: bool, optional
|
||||
:param session_id: The session id to use for chat history, defaults to 'default'.
|
||||
:type session_id: Optional[str], optional
|
||||
:type session_id: str, optional
|
||||
:param where: A dictionary of key-value pairs to filter the database results., defaults to None
|
||||
:type where: Optional[dict[str, str]], optional
|
||||
:type where: dict[str, str], optional
|
||||
:param citations: A boolean to indicate if db should fetch citation source
|
||||
:type citations: bool
|
||||
: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]
|
||||
@@ -560,7 +583,7 @@ class EmbedChain(JSONSerializable):
|
||||
self.llm.update_history(app_id=self.config.id, session_id=session_id)
|
||||
|
||||
if self.cache_config is not None:
|
||||
logging.info("Cache enabled. Checking cache...")
|
||||
logger.debug("Cache enabled. Checking cache...")
|
||||
cache_id = f"{session_id}--{self.config.id}"
|
||||
answer = adapt(
|
||||
llm_handler=self.llm.chat,
|
||||
@@ -573,6 +596,7 @@ class EmbedChain(JSONSerializable):
|
||||
dry_run=dry_run,
|
||||
)
|
||||
else:
|
||||
logger.debug("Cache disabled. Running chat without cache.")
|
||||
answer = self.llm.chat(
|
||||
input_query=input_query, contexts=contexts_data_for_llm_query, config=config, dry_run=dry_run
|
||||
)
|
||||
@@ -588,7 +612,7 @@ class EmbedChain(JSONSerializable):
|
||||
else:
|
||||
return answer
|
||||
|
||||
def search(self, query, num_documents=3, where=None, raw_filter=None):
|
||||
def search(self, query, num_documents=3, where=None, raw_filter=None, namespace=None):
|
||||
"""
|
||||
Search for similar documents related to the query in the vector database.
|
||||
|
||||
@@ -597,6 +621,7 @@ class EmbedChain(JSONSerializable):
|
||||
num_documents (int, optional): Number of similar documents to fetch. Defaults to 3.
|
||||
where (dict[str, any], optional): Filter criteria for the search.
|
||||
raw_filter (dict[str, any], optional): Advanced raw filter criteria for the search.
|
||||
namespace (str, optional): The namespace to search in. Defaults to None.
|
||||
|
||||
Raises:
|
||||
ValueError: If both `raw_filter` and `where` are used simultaneously.
|
||||
@@ -618,6 +643,7 @@ class EmbedChain(JSONSerializable):
|
||||
"n_results": num_documents,
|
||||
"citations": True,
|
||||
"app_id": self.config.id,
|
||||
"namespace": namespace,
|
||||
filter_type: filter_criteria,
|
||||
}
|
||||
|
||||
@@ -648,7 +674,7 @@ class EmbedChain(JSONSerializable):
|
||||
self.db_session.query(ChatHistory).filter_by(app_id=self.config.id).delete()
|
||||
self.db_session.commit()
|
||||
except Exception as e:
|
||||
logging.error(f"Error deleting data sources: {e}")
|
||||
logger.error(f"Error deleting data sources: {e}")
|
||||
self.db_session.rollback()
|
||||
return None
|
||||
self.db.reset()
|
||||
@@ -690,11 +716,11 @@ class EmbedChain(JSONSerializable):
|
||||
self.db_session.query(DataSource).filter_by(hash=source_id, app_id=self.config.id).delete()
|
||||
self.db_session.commit()
|
||||
except Exception as e:
|
||||
logging.error(f"Error deleting data sources: {e}")
|
||||
logger.error(f"Error deleting data sources: {e}")
|
||||
self.db_session.rollback()
|
||||
return None
|
||||
self.db.delete(where={"hash": source_id})
|
||||
logging.info(f"Successfully deleted {source_id}")
|
||||
logger.info(f"Successfully deleted {source_id}")
|
||||
# Send anonymous telemetry
|
||||
if self.config.collect_metrics:
|
||||
self.telemetry.capture(event_name="delete", properties=self._telemetry_props)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
from typing import Optional
|
||||
|
||||
from langchain_cohere.embeddings import CohereEmbeddings
|
||||
|
||||
from embedchain.config import BaseEmbedderConfig
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
from embedchain.models import VectorDimensions
|
||||
|
||||
|
||||
class CohereEmbedder(BaseEmbedder):
|
||||
def __init__(self, config: Optional[BaseEmbedderConfig] = None):
|
||||
super().__init__(config=config)
|
||||
|
||||
embeddings = CohereEmbeddings(model=self.config.model)
|
||||
embedding_fn = BaseEmbedder._langchain_default_concept(embeddings)
|
||||
self.set_embedding_fn(embedding_fn=embedding_fn)
|
||||
|
||||
vector_dimension = self.config.vector_dimension or VectorDimensions.COHERE.value
|
||||
self.set_vector_dimension(vector_dimension=vector_dimension)
|
||||
@@ -0,0 +1,28 @@
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings
|
||||
|
||||
from embedchain.config import BaseEmbedderConfig
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
from embedchain.models import VectorDimensions
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class NvidiaEmbedder(BaseEmbedder):
|
||||
def __init__(self, config: Optional[BaseEmbedderConfig] = None):
|
||||
if "NVIDIA_API_KEY" not in os.environ:
|
||||
raise ValueError("NVIDIA_API_KEY environment variable must be set")
|
||||
|
||||
super().__init__(config=config)
|
||||
|
||||
model = self.config.model or "nvolveqa_40k"
|
||||
logger.info(f"Using NVIDIA embedding model: {model}")
|
||||
embedder = NVIDIAEmbeddings(model=model)
|
||||
embedding_fn = BaseEmbedder._langchain_default_concept(embedder)
|
||||
self.set_embedding_fn(embedding_fn=embedding_fn)
|
||||
|
||||
vector_dimension = self.config.vector_dimension or VectorDimensions.NVIDIA_AI.value
|
||||
self.set_vector_dimension(vector_dimension=vector_dimension)
|
||||
@@ -0,0 +1,32 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
from ollama import Client
|
||||
except ImportError:
|
||||
raise ImportError("Ollama Embedder requires extra dependencies. Install with `pip install ollama`") from None
|
||||
|
||||
from langchain_community.embeddings import OllamaEmbeddings
|
||||
|
||||
from embedchain.config import OllamaEmbedderConfig
|
||||
from embedchain.embedder.base import BaseEmbedder
|
||||
from embedchain.models import VectorDimensions
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OllamaEmbedder(BaseEmbedder):
|
||||
def __init__(self, config: Optional[OllamaEmbedderConfig] = None):
|
||||
super().__init__(config=config)
|
||||
|
||||
client = Client(host=config.base_url)
|
||||
local_models = client.list()["models"]
|
||||
if not any(model.get("name") == self.config.model for model in local_models):
|
||||
logger.info(f"Pulling {self.config.model} from Ollama!")
|
||||
client.pull(self.config.model)
|
||||
embeddings = OllamaEmbeddings(model=self.config.model, base_url=config.base_url)
|
||||
embedding_fn = BaseEmbedder._langchain_default_concept(embeddings)
|
||||
self.set_embedding_fn(embedding_fn=embedding_fn)
|
||||
|
||||
vector_dimension = self.config.vector_dimension or VectorDimensions.OLLAMA.value
|
||||
self.set_vector_dimension(vector_dimension=vector_dimension)
|
||||
@@ -17,6 +17,7 @@ class OpenAIEmbedder(BaseEmbedder):
|
||||
self.config.model = "text-embedding-ada-002"
|
||||
|
||||
api_key = self.config.api_key or os.environ["OPENAI_API_KEY"]
|
||||
api_base = self.config.api_base or os.environ.get("OPENAI_API_BASE")
|
||||
|
||||
if self.config.deployment_name:
|
||||
embeddings = AzureOpenAIEmbeddings(deployment=self.config.deployment_name)
|
||||
@@ -28,6 +29,7 @@ class OpenAIEmbedder(BaseEmbedder):
|
||||
) # noqa:E501
|
||||
embedding_fn = OpenAIEmbeddingFunction(
|
||||
api_key=api_key,
|
||||
api_base=api_base,
|
||||
organization_id=os.getenv("OPENAI_ORGANIZATION"),
|
||||
model_name=self.config.model,
|
||||
)
|
||||
|
||||
@@ -12,6 +12,8 @@ from embedchain.config.evaluation.base import AnswerRelevanceConfig
|
||||
from embedchain.evaluation.base import BaseMetric
|
||||
from embedchain.utils.evaluation import EvalData, EvalMetric
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AnswerRelevance(BaseMetric):
|
||||
"""
|
||||
@@ -88,6 +90,6 @@ class AnswerRelevance(BaseMetric):
|
||||
try:
|
||||
results.append(future.result())
|
||||
except Exception as e:
|
||||
logging.error(f"Error evaluating answer relevancy for {data}: {e}")
|
||||
logger.error(f"Error evaluating answer relevancy for {data}: {e}")
|
||||
|
||||
return np.mean(results) if results else 0.0
|
||||
|
||||
@@ -12,6 +12,8 @@ from embedchain.config.evaluation.base import GroundednessConfig
|
||||
from embedchain.evaluation.base import BaseMetric
|
||||
from embedchain.utils.evaluation import EvalData, EvalMetric
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Groundedness(BaseMetric):
|
||||
"""
|
||||
@@ -97,6 +99,6 @@ class Groundedness(BaseMetric):
|
||||
score = future.result()
|
||||
results.append(score)
|
||||
except Exception as e:
|
||||
logging.error(f"Error while evaluating groundedness for data point {data}: {e}")
|
||||
logger.error(f"Error while evaluating groundedness for data point {data}: {e}")
|
||||
|
||||
return np.mean(results) if results else 0.0
|
||||
|
||||
@@ -24,6 +24,8 @@ class LlmFactory:
|
||||
"aws_bedrock": "embedchain.llm.aws_bedrock.AWSBedrockLlm",
|
||||
"mistralai": "embedchain.llm.mistralai.MistralAILlm",
|
||||
"groq": "embedchain.llm.groq.GroqLlm",
|
||||
"nvidia": "embedchain.llm.nvidia.NvidiaLlm",
|
||||
"vllm": "embedchain.llm.vllm.VLLM",
|
||||
}
|
||||
provider_to_config_class = {
|
||||
"embedchain": "embedchain.config.llm.base.BaseLlmConfig",
|
||||
@@ -54,13 +56,17 @@ class EmbedderFactory:
|
||||
"vertexai": "embedchain.embedder.vertexai.VertexAIEmbedder",
|
||||
"google": "embedchain.embedder.google.GoogleAIEmbedder",
|
||||
"mistralai": "embedchain.embedder.mistralai.MistralAIEmbedder",
|
||||
"nvidia": "embedchain.embedder.nvidia.NvidiaEmbedder",
|
||||
"cohere": "embedchain.embedder.cohere.CohereEmbedder",
|
||||
"ollama": "embedchain.embedder.ollama.OllamaEmbedder",
|
||||
}
|
||||
provider_to_config_class = {
|
||||
"azure_openai": "embedchain.config.embedder.base.BaseEmbedderConfig",
|
||||
"openai": "embedchain.config.embedder.base.BaseEmbedderConfig",
|
||||
"gpt4all": "embedchain.config.embedder.base.BaseEmbedderConfig",
|
||||
"google": "embedchain.config.embedder.google.GoogleAIEmbedderConfig",
|
||||
"gpt4all": "embedchain.config.embedder.base.BaseEmbedderConfig",
|
||||
"huggingface": "embedchain.config.embedder.base.BaseEmbedderConfig",
|
||||
"openai": "embedchain.config.embedder.base.BaseEmbedderConfig",
|
||||
"ollama": "embedchain.config.embedder.ollama.OllamaEmbedderConfig",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -8,6 +8,8 @@ T = TypeVar("T", bound="JSONSerializable")
|
||||
# NOTE: Through inheritance, all of our classes should be children of JSONSerializable. (highest level)
|
||||
# NOTE: The @register_deserializable decorator should be added to all user facing child classes. (lowest level)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def register_deserializable(cls: Type[T]) -> Type[T]:
|
||||
"""
|
||||
@@ -57,7 +59,7 @@ class JSONSerializable:
|
||||
try:
|
||||
return json.dumps(self, default=self._auto_encoder, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
logging.error(f"Serialization error: {e}")
|
||||
logger.error(f"Serialization error: {e}")
|
||||
return "{}"
|
||||
|
||||
@classmethod
|
||||
@@ -79,7 +81,7 @@ class JSONSerializable:
|
||||
try:
|
||||
return json.loads(json_str, object_hook=cls._auto_decoder)
|
||||
except Exception as e:
|
||||
logging.error(f"Deserialization error: {e}")
|
||||
logger.error(f"Deserialization error: {e}")
|
||||
# Return a default instance in case of failure
|
||||
return cls()
|
||||
|
||||
@@ -95,10 +97,8 @@ class JSONSerializable:
|
||||
dict: A dictionary representation of the object.
|
||||
"""
|
||||
if hasattr(obj, "__dict__"):
|
||||
dct = obj.__dict__.copy()
|
||||
for key, value in list(
|
||||
dct.items()
|
||||
): # We use list() to get a copy of items to avoid dictionary size change during iteration.
|
||||
dct = {}
|
||||
for key, value in obj.__dict__.items():
|
||||
try:
|
||||
# Recursive: If the value is an instance of a subclass of JSONSerializable,
|
||||
# serialize it using the JSONSerializable serialize method.
|
||||
@@ -118,8 +118,9 @@ class JSONSerializable:
|
||||
# NOTE: Keep in mind that this logic needs to be applied to the decoder too.
|
||||
else:
|
||||
json.dumps(value) # Try to serialize the value.
|
||||
dct[key] = value
|
||||
except TypeError:
|
||||
del dct[key] # If it fails, remove the key-value pair from the dictionary.
|
||||
pass # If it fails, simply pass to skip this key-value pair of the dictionary.
|
||||
|
||||
dct["__class__"] = obj.__class__.__name__
|
||||
return dct
|
||||
|
||||
@@ -2,10 +2,17 @@ import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
from langchain_anthropic import ChatAnthropic
|
||||
except ImportError:
|
||||
raise ImportError("Please install the langchain-anthropic package by running `pip install langchain-anthropic`.")
|
||||
|
||||
from embedchain.config import BaseLlmConfig
|
||||
from embedchain.helpers.json_serializable import register_deserializable
|
||||
from embedchain.llm.base import BaseLlm
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class AnthropicLlm(BaseLlm):
|
||||
@@ -19,14 +26,12 @@ class AnthropicLlm(BaseLlm):
|
||||
|
||||
@staticmethod
|
||||
def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
|
||||
from langchain_community.chat_models import ChatAnthropic
|
||||
|
||||
chat = ChatAnthropic(
|
||||
anthropic_api_key=os.environ["ANTHROPIC_API_KEY"], temperature=config.temperature, model=config.model
|
||||
anthropic_api_key=os.environ["ANTHROPIC_API_KEY"], temperature=config.temperature, model_name=config.model
|
||||
)
|
||||
|
||||
if config.max_tokens and config.max_tokens != 1000:
|
||||
logging.warning("Config option `max_tokens` is not supported by this model.")
|
||||
logger.warning("Config option `max_tokens` is not supported by this model.")
|
||||
|
||||
messages = BaseLlm._get_messages(prompt, system_prompt=config.system_prompt)
|
||||
|
||||
|
||||
@@ -38,7 +38,8 @@ class AWSBedrockLlm(BaseLlm):
|
||||
}
|
||||
|
||||
if config.stream:
|
||||
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
||||
from langchain.callbacks.streaming_stdout import \
|
||||
StreamingStdOutCallbackHandler
|
||||
|
||||
callbacks = [StreamingStdOutCallbackHandler()]
|
||||
llm = Bedrock(**kwargs, streaming=config.stream, callbacks=callbacks)
|
||||
|
||||
@@ -5,6 +5,8 @@ from embedchain.config import BaseLlmConfig
|
||||
from embedchain.helpers.json_serializable import register_deserializable
|
||||
from embedchain.llm.base import BaseLlm
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class AzureOpenAILlm(BaseLlm):
|
||||
@@ -31,7 +33,7 @@ class AzureOpenAILlm(BaseLlm):
|
||||
)
|
||||
|
||||
if config.top_p and config.top_p != 1:
|
||||
logging.warning("Config option `top_p` is not supported by this model.")
|
||||
logger.warning("Config option `top_p` is not supported by this model.")
|
||||
|
||||
messages = BaseLlm._get_messages(prompt, system_prompt=config.system_prompt)
|
||||
|
||||
|
||||
+12
-13
@@ -5,13 +5,13 @@ from typing import Any, Optional
|
||||
from langchain.schema import BaseMessage as LCBaseMessage
|
||||
|
||||
from embedchain.config import BaseLlmConfig
|
||||
from embedchain.config.llm.base import (DEFAULT_PROMPT,
|
||||
DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE,
|
||||
DOCS_SITE_PROMPT_TEMPLATE)
|
||||
from embedchain.config.llm.base import DEFAULT_PROMPT, DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE, DOCS_SITE_PROMPT_TEMPLATE
|
||||
from embedchain.helpers.json_serializable import JSONSerializable
|
||||
from embedchain.memory.base import ChatHistory
|
||||
from embedchain.memory.message import ChatMessage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BaseLlm(JSONSerializable):
|
||||
def __init__(self, config: Optional[BaseLlmConfig] = None):
|
||||
@@ -27,7 +27,6 @@ class BaseLlm(JSONSerializable):
|
||||
|
||||
self.memory = ChatHistory()
|
||||
self.is_docs_site_instance = False
|
||||
self.online = False
|
||||
self.history: Any = None
|
||||
|
||||
def get_llm_model_answer(self):
|
||||
@@ -108,7 +107,7 @@ class BaseLlm(JSONSerializable):
|
||||
)
|
||||
else:
|
||||
# If we can't swap in the default, we still proceed but tell users that the history is ignored.
|
||||
logging.warning(
|
||||
logger.warning(
|
||||
"Your bot contains a history, but prompt does not include `$history` key. History is ignored."
|
||||
)
|
||||
prompt = self.config.prompt.substitute(context=context_string, query=input_query)
|
||||
@@ -159,7 +158,7 @@ class BaseLlm(JSONSerializable):
|
||||
'Searching requires extra dependencies. Install with `pip install --upgrade "embedchain[dataloaders]"`'
|
||||
) from None
|
||||
search = DuckDuckGoSearchRun()
|
||||
logging.info(f"Access search to get answers for {input_query}")
|
||||
logger.info(f"Access search to get answers for {input_query}")
|
||||
return search.run(input_query)
|
||||
|
||||
@staticmethod
|
||||
@@ -175,7 +174,7 @@ class BaseLlm(JSONSerializable):
|
||||
for chunk in answer:
|
||||
streamed_answer = streamed_answer + chunk
|
||||
yield chunk
|
||||
logging.info(f"Answer: {streamed_answer}")
|
||||
logger.info(f"Answer: {streamed_answer}")
|
||||
|
||||
def query(self, input_query: str, contexts: list[str], config: BaseLlmConfig = None, dry_run=False):
|
||||
"""
|
||||
@@ -211,16 +210,16 @@ class BaseLlm(JSONSerializable):
|
||||
self.config.prompt = DOCS_SITE_PROMPT_TEMPLATE
|
||||
self.config.number_documents = 5
|
||||
k = {}
|
||||
if self.online:
|
||||
if self.config.online:
|
||||
k["web_search_result"] = self.access_search_and_get_results(input_query)
|
||||
prompt = self.generate_prompt(input_query, contexts, **k)
|
||||
logging.info(f"Prompt: {prompt}")
|
||||
logger.info(f"Prompt: {prompt}")
|
||||
if dry_run:
|
||||
return prompt
|
||||
|
||||
answer = self.get_answer_from_llm(prompt)
|
||||
if isinstance(answer, str):
|
||||
logging.info(f"Answer: {answer}")
|
||||
logger.info(f"Answer: {answer}")
|
||||
return answer
|
||||
else:
|
||||
return self._stream_response(answer)
|
||||
@@ -266,18 +265,18 @@ class BaseLlm(JSONSerializable):
|
||||
self.config.prompt = DOCS_SITE_PROMPT_TEMPLATE
|
||||
self.config.number_documents = 5
|
||||
k = {}
|
||||
if self.online:
|
||||
if self.config.online:
|
||||
k["web_search_result"] = self.access_search_and_get_results(input_query)
|
||||
|
||||
prompt = self.generate_prompt(input_query, contexts, **k)
|
||||
logging.info(f"Prompt: {prompt}")
|
||||
logger.info(f"Prompt: {prompt}")
|
||||
|
||||
if dry_run:
|
||||
return prompt
|
||||
|
||||
answer = self.get_answer_from_llm(prompt)
|
||||
if isinstance(answer, str):
|
||||
logging.info(f"Answer: {answer}")
|
||||
logger.info(f"Answer: {answer}")
|
||||
return answer
|
||||
else:
|
||||
# this is a streamed response and needs to be handled differently.
|
||||
|
||||
@@ -10,6 +10,8 @@ from embedchain.config import BaseLlmConfig
|
||||
from embedchain.helpers.json_serializable import register_deserializable
|
||||
from embedchain.llm.base import BaseLlm
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@register_deserializable
|
||||
class GoogleLlm(BaseLlm):
|
||||
@@ -36,7 +38,7 @@ class GoogleLlm(BaseLlm):
|
||||
|
||||
def _get_answer(self, prompt: str) -> Union[str, Generator[Any, Any, None]]:
|
||||
model_name = self.config.model or "gemini-pro"
|
||||
logging.info(f"Using Google LLM model: {model_name}")
|
||||
logger.info(f"Using Google LLM model: {model_name}")
|
||||
model = genai.GenerativeModel(model_name=model_name)
|
||||
|
||||
generation_config_params = {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user