Compare commits

...

115 Commits

Author SHA1 Message Date
Dev Khant 8a9088ea9d Version bump (#1438) 2024-06-21 09:11:24 -07:00
Prashant Dixit 48b24f6f12 Lancedb Integration (#1411) 2024-06-21 08:59:22 -07:00
Dev Khant f6ddd5ffc5 Add HF endpoint in embedder (#1436) 2024-06-21 08:57:21 -07:00
Dev Khant b43a116b3c Add vector dimension to Ollama embedder (#1435) 2024-06-21 08:56:46 -07:00
Dev Khant 50512a5f03 Doc fix for embedders (#1433) 2024-06-19 10:08:31 -07:00
Dev Khant e3e107b31d Raise import error if Ollama and Google not found (#1432) 2024-06-18 21:46:48 -07:00
Dev Khant 21a04541ea poetry fix (#1430) 2024-06-18 10:45:37 -07:00
Dev Khant cdd5d8ac76 Version bump (#1426) 2024-06-18 09:13:52 -07:00
Dev Khant 11094f504e Fix Ollama test (#1428) 2024-06-18 09:10:43 -07:00
mogith-pn 5acaae5f56 Clarifai : Added Clarifai as LLM and embedding model provider. (#1311)
Co-authored-by: Deshraj Yadav <deshraj@gatech.edu>
2024-06-17 08:48:18 -07:00
Pranav Puranik 4547d870af azure openai features and bugs solve - openai_version, docs (#1425) 2024-06-17 08:47:27 -07:00
Aditya Veer Parmar dc0d8e0932 Allow ollama llm to take custom callback for handling streaming (#1376) 2024-06-17 08:44:52 -07:00
patcher9 c558eae9ce [Docs]: Fix the Title and Description for OpenLIT Integration (#1424) 2024-06-14 00:09:31 -07:00
patcher9 abb9af66a6 [Docs]: Add Integration for OpenLIT (OpenTelemetry-native LLM Application O11y) (#1377) 2024-06-13 23:06:04 -07:00
Ananto Joyoadikusumo 4800e0344c Added language detection for non-english youtube videos (#1362) 2024-06-13 23:02:37 -07:00
Dev Khant 439b425c61 Version bump (#1423) 2024-06-13 22:28:35 -07:00
Dev Khant 2855f1635b Add support for loading api_key from config or env variable (#1421) 2024-06-13 11:19:54 -07:00
Dev Khant 08b67b4a78 Support for Audio Files (#1416) 2024-06-12 10:25:58 -07:00
Dev Khant 1bddd46ed2 Verion bump, chromadb_version change and doc update (#1407) 2024-06-12 08:46:00 -07:00
Pranav Puranik 6ecdadfd97 Add model_kwargs to OpenAI call (#1402) 2024-06-11 11:20:04 -07:00
Dimitra Gerontaki 4119040005 Add documentation for text_file data type (#1410) 2024-06-10 21:34:28 -07:00
Taranjeet Singh 873eef6ef8 Remove: EC deployment docs, and js links (#1409) 2024-06-11 02:34:15 +05:30
Taranjeet Singh 445fed4d3f Remove embedchain js (#1408) 2024-06-11 01:54:56 +05:30
Dev Khant 52fd3e0dd4 Update contributing doc (#1404) 2024-06-10 10:14:52 -07:00
Saurabh Misra 8fd0e1f3b0 ⚡️ Speed up read_env_file() in embedchain/utils/cli.py (#1260) 2024-06-09 09:11:15 -07:00
golemus 11fc4a8451 Update llms card to properly use local ollama (#1395) 2024-06-09 09:09:49 -07:00
shuo e22293294e Delete embedchain/embedder/.ollama.py.swp (#1398) 2024-06-09 09:02:38 -07:00
Dev Khant 73e53aaff1 Download Ollama model if not present (#1397) 2024-06-08 23:43:03 -07:00
Deshraj Yadav 6fa946557f Update package version to 0.1.108 (#1396) 2024-06-08 10:34:15 -07:00
Youbin Choi fb0852f585 [Bug Fix] Fix issue of loading other languages in csv file (#1225) 2024-06-08 10:09:29 -07:00
Dev Khant 4070fc1bf0 Fix ollama embeddings for remote machine (#1394) 2024-06-08 10:08:15 -07:00
Dev Khant 00c1fa1ec7 Fix OpenAI Assistant (#1393) 2024-06-08 10:07:52 -07:00
Dev Khant 04e77ef34e version bump (#1389) 2024-06-07 10:30:22 -07:00
Dev Khant 827d63d115 Fix skipped tests (#1385) 2024-06-07 10:26:54 -07:00
Anu e0d0f6e94c Change list[str] -> str for vectordbs (#1388) 2024-06-07 09:15:40 -07:00
Dev Khant fd07513004 Fix online feat and add docs (#1387) 2024-06-06 23:33:16 -07:00
Dev Khant b0e436d9c4 Poetry fixes (#1382) 2024-06-06 10:41:46 -07:00
Dev Khant a4bfd9cfc6 Version bump (#1386) 2024-06-06 10:40:38 -07:00
Dev Khant 8ca01918e5 Ollama embeddings tested and Docs ready (#1384) 2024-06-06 10:29:01 -07:00
Deshraj Yadav a5b2381458 Update version to 0.1.105 (#1383) 2024-06-05 10:53:34 -07:00
Anu 26c771503b Doc string fix for embedchain.py (#1381) 2024-06-05 10:44:09 -07:00
Saurabh Misra 622ed4a7c9 Speed up _auto_encoder() by 15% in embedchain/helpers/json_serializable.py (#1265) 2024-06-05 10:40:46 -07:00
Saurabh Misra 940f0128d5 Speed up docs site loader (#1266) 2024-06-05 10:39:30 -07:00
Saurabh Misra 1354747ca8 ⚡️ Speed up get_word_count() by 6% in embedchain/chunkers/base_chunker.py (#1268) 2024-06-05 10:36:00 -07:00
Deshraj Yadav 9544c69c55 [Improvements] Upgrade langchain-openai package and other improvements (#1372) 2024-05-21 23:42:50 -07:00
LeonieFreisinger 9ba445e623 Fix cohere embedder (#1353) 2024-05-21 22:55:10 -07:00
Abdur Rahman Nawaz ebc5e25f98 Add support for http clients in config (#1355) 2024-05-06 10:32:46 -07:00
Esparon1 78301ee63d Add feature to extract timestamps from youtube videos (#1345) 2024-05-06 10:31:04 -07:00
Niv Hertz 797dea1dca Support supplying custom headers to OpenAI requests (#1356) 2024-05-06 10:26:12 -07:00
Deshraj Yadav a0ff764f0a [Misc] Update package version for chroma and pypdf (#1352) 2024-05-01 22:24:49 -07:00
Colin O'Brien a795798156 Add Ollama as a supported embedding provider (#1344) 2024-05-01 22:08:47 -07:00
Jesús Ferretti 1a66f961f4 Docs: fix typo (#1350) 2024-05-01 22:06:22 -07:00
Deshraj Yadav 6fb2048af0 [Bug fix] Remove duplicate constants (#1342) 2024-04-19 09:50:37 -07:00
Deshraj Yadav ba9f186fc5 [Improvement] Make embedchain home dir configurable (#1341) 2024-04-18 11:20:01 -07:00
Dev Khant 6c32d287b5 Support for Excel files (#1319) 2024-04-15 22:03:43 -07:00
Deshraj Yadav 536f85b78a [Improvements] Improve logging and fix insertion in data_sources table (#1337) 2024-04-11 15:00:04 -07:00
neilbhutada f8619870ad Update llms.mdx (#1336) 2024-04-10 16:03:03 -07:00
Deshraj Yadav d00a2085d5 [Bug Fix] Make claude-3-opus model work (#1331) 2024-03-28 00:56:14 -07:00
Deshraj Yadav 85ec61335a Update package version to 0.1.98 (#1327) 2024-03-20 19:29:51 -07:00
Flyfoxs 9b48a12c27 [Bug fix] Avoid saving the duplicated docs (#1326) 2024-03-20 09:58:11 -07:00
Deshraj Yadav c181ccbe42 Update requirements.txt (#1325) 2024-03-19 21:27:21 -07:00
Deshraj Yadav 8520033d44 [Bug fix] Fix issues related to logging configuration (#1318) 2024-03-14 00:45:37 -07:00
Deshraj Yadav ebdce87fde [Version] Update version to 0.1.96 (#1317) 2024-03-14 00:02:51 -07:00
Abhishek Sharma f2122ed696 [Fix] Added missing provider for 'vllm' (#1316) 2024-03-14 00:01:30 -07:00
Deshraj Yadav 3616eaadb4 [Refactor] Improve logging package wide (#1315) 2024-03-13 17:13:30 -07:00
berwin joule ef69c91b60 [Bug fix]: fix Cannot add documents to chromadb with inconsistent sizes. (#1314) 2024-03-13 11:01:46 -07:00
Dev Khant 117824b32c Add folder and branch to GitHub (#1308) 2024-03-12 12:15:37 -07:00
Dev Khant f77f5b996e Support for Cohere Embeddings (#1310) 2024-03-12 12:14:45 -07:00
Deshraj Yadav a4d32aec24 [Docs] Update docs and readme (#1309) 2024-03-10 00:23:21 -08:00
Uzair Naeem 9111495fae Enhance code readability and documentation clarity (#1307) 2024-03-07 08:12:31 -08:00
Hardik Jindal ee1e3f0957 [docs] update langsmith.mdx (#1306) 2024-03-07 08:10:11 -08:00
Deshraj Yadav 4dc5c7348f [Bug fix]: Fix issue of OPENAI_API_BASE env variable being mandatory (#1305) 2024-03-05 14:07:44 -08:00
Deshraj Yadav 4428768eaa [Bug Fix]: Fix test cases and update version to 0.1.93 (#1303) 2024-03-04 18:35:01 -08:00
Joe 11f4ce8fb6 #1155: Add support for OpenAI-compatible endpoint in LLM and Embed (#1197) 2024-03-04 18:17:20 -08:00
Felipe Amaral 6078738d34 Feature: Custom Ollama endpoint base_url (#1301) 2024-03-04 18:09:45 -08:00
Deshraj Yadav faacfeb891 [Improvement] Set a default app id if not provided in the app configuration (#1300) 2024-03-02 15:10:34 -08:00
Deshraj Yadav 8d7e8b6fb9 [Docs] Update pinecone integration docs (#1296) 2024-03-01 16:49:43 -08:00
Deshraj Yadav 7e1d2ffdd7 [Bug fix] Fix search API for pinecone vector db 2024-03-01 16:44:42 -08:00
Deshraj Yadav 91044ec591 [Bug fix] Fix issue related to get_data_sources() method (#1295) 2024-03-01 11:54:36 -08:00
Deshraj Yadav c77a75dfb5 [Feature] Add support for NVIDIA AI LLMs and embedding models (#1293) 2024-02-29 23:56:25 -08:00
Deshraj Yadav 6518c0c06b [Docs] Update docs for resetting vector database (#1289) 2024-02-28 12:19:47 -08:00
Deshraj Yadav 09cdaff9a2 [Improvement] Fix deprecation warnings (#1288) 2024-02-27 15:10:41 -08:00
Deshraj Yadav 56bf33ab7f [Feature] Add support for running huggingface models locally (#1287) 2024-02-27 15:05:17 -08:00
Deshraj Yadav 752f638cfc [Feature/Improvements] Delete data sources from metadata db when using app.delete() (#1286) 2024-02-26 13:18:42 -08:00
Deshraj Yadav 92dd7edb57 [Feature] Add support for Groq LLMs (#1284) 2024-02-25 11:58:03 -08:00
Deshraj Yadav b4bb4cf053 [Bug fix] Fix issue for using any metadata db apart from sqlite (#1282) 2024-02-22 09:52:40 -08:00
Deshraj Yadav f0400e928a [Bug fix] Fix issue related to initalizing the local database engine (#1281) 2024-02-22 02:40:06 -08:00
Deshraj Yadav aa5ad625af Add support for supplying custom db params (#1276) 2024-02-21 16:15:57 -08:00
Deshraj Yadav f8f69eab03 [Feature] Add support for python 3.13 and other migration related fixes (#1279) 2024-02-21 13:04:03 -08:00
João Moura 2b2263acaa Updating python version to including <=3.13 (#1278) 2024-02-21 11:48:13 -08:00
Deshraj Yadav 5e2e7fb639 [Feature] Add support to use any sql database as the metadata storage for embedchain apps (#1273) 2024-02-19 13:04:18 -08:00
Deshraj Yadav 6c12bc9044 [Improvements] Improve the default prompt and data loader util functions (#1272) 2024-02-18 14:06:32 -08:00
Saurabh Misra 9a11683003 ⚡️ Speed up is_readable by 101% in embedchain/utils/misc.py (#1258)
Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
2024-02-15 23:18:53 -08:00
Deshraj Yadav 38b4e06963 [Feature] Add support for hybrid search for pinecone vector database (#1259) 2024-02-15 13:20:14 -08:00
Deshraj Yadav 0766a44ccf [Bug fix] Fix vertex ai integration issue (#1257) 2024-02-14 11:19:32 -08:00
Deshraj Yadav 036bf3a161 Update version to 0.1.78 (#1256) 2024-02-12 17:23:14 -08:00
UnMonsieur 41bd258b93 [Feature] OpenAI Function Calling (#1224) 2024-02-11 17:58:11 -08:00
Deshraj Yadav 38e212c721 [Bug fix] Fix test (#1255) 2024-02-11 17:57:14 -08:00
Deshraj Yadav 2f285ea00a [Bug fix] Fix history sequence in prompt (#1254) 2024-02-11 16:07:36 -08:00
Dhravya Shah d38120c839 [Docs] Added documentation to deploy to Railway.app (#1250) 2024-02-11 15:58:42 -08:00
Michael d94aee812b [Improvements] Fixes to null data results and OpenAI embedding limits (#1238) 2024-02-11 15:45:02 -08:00
Rishiraj2594 68d650ec40 [Docs] Typo fixed youtube-video.mdx (#1253) 2024-02-09 16:34:08 -08:00
Rishiraj2594 769d926f5a [Docs] Typo fixed in youtube-channel.mdx (#1252) 2024-02-09 16:33:48 -08:00
Oskar 9478bab04e Fix links to the Discourse docs in the Discourse Loader (#1251) 2024-02-09 08:21:52 -08:00
Deshraj Yadav 7ad4af250f [Feature] Add support for optionally fetch all chat history for app (#1249) 2024-02-07 14:52:39 -08:00
Deshraj Yadav 9fa368b114 [Refactor] Remove usage of 'Pipeline' in favor of 'App' (#1246) 2024-02-06 19:00:33 -08:00
Deshraj Yadav 4afef04f26 [Feature] Add support for metadata filtering on search API (#1245) 2024-02-06 15:42:51 -08:00
Thomas T 8fe2c3effc [Bug Fix] Add support for AWS_REGION override (#1237) 2024-02-06 11:25:58 -08:00
Deshraj Yadav fa78c972be [Bug Fix] Fix issue related to using embedding model from huggingface (#1242) 2024-02-06 10:54:58 -08:00
Deshraj Yadav 0e66261644 Update docs (#1240) 2024-02-05 18:56:05 -08:00
Juanan Pereira 819650a254 Update URL Validation Regex to Support IP Addresses and Port Numbers (#1233) 2024-02-02 09:06:56 +05:30
Taranjeet Singh 34c41c87dc Docs: Update full stack docs (#1230) 2024-01-30 09:51:32 +05:30
Deshraj Yadav 2985b667b0 [Bug fix] Fix issue with gmail loader (#1228) 2024-01-29 18:36:02 +05:30
Taranjeet Singh 31bb0e7f0f Bump version to 0.1.71 (#1223) 2024-01-27 13:34:34 +05:30
Taranjeet Singh 8f28264aec feat: add UA header for pdf and sitemap (#1222) 2024-01-27 13:29:09 +05:30
256 changed files with 8495 additions and 26108 deletions
+1 -1
View File
@@ -39,7 +39,7 @@ jobs:
path: .venv
key: venv-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
- name: Install dependencies
run: poetry install --all-extras
run: make install_all
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
- name: Lint with ruff
run: make lint
+1
View File
@@ -165,6 +165,7 @@ cython_debug/
# Database
db
test-db
!embedchain/core/db/
.vscode
.idea/
+1 -1
View File
@@ -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
+4
View File
@@ -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
+7
View File
@@ -11,6 +11,7 @@ install:
install_all:
poetry install --all-extras
poetry run pip install pinecone-text pinecone-client langchain-anthropic "unstructured[local-inference, all-docs]" ollama deepgram-sdk==3.2.7
install_es:
poetry install --extras elasticsearch
@@ -37,6 +38,12 @@ clean:
lint:
poetry run ruff .
build:
poetry build
publish:
poetry publish
# for example: make test file=tests/test_factory.py
test:
poetry run pytest $(file)
+9 -16
View File
@@ -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">
@@ -32,14 +28,11 @@
<hr />
> ### Checkout our latest [Sadhguru AI app](https://sadhguru-ai.streamlit.app/) built using Embedchain.
## 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,18 +57,18 @@ For example, you can create an Elon Musk bot using the following code:
```python
import os
from embedchain import Pipeline as App
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.
```
+12
View File
@@ -0,0 +1,12 @@
llm:
provider: clarifai
config:
model: "https://clarifai.com/mistralai/completion/models/mistral-7B-Instruct"
model_kwargs:
temperature: 0.5
max_tokens: 1000
embedder:
provider: clarifai
config:
model: "https://clarifai.com/clarifai/main/models/BAAI-bge-base-en-v15"
+4 -2
View File
@@ -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
+1 -1
View File
@@ -1,6 +1,6 @@
<p>If you can't find the specific vector database, please feel free to request through one of the following channels and help us prioritize.</p>
<p>If you can't find specific feature or run into issues, please feel free to reach out through one of the following channels.</p>
<CardGroup cols={2}>
<Card title="Slack" icon="slack" href="https://embedchain.ai/slack" color="#4A154B">
+12 -4
View File
@@ -26,6 +26,10 @@ llm:
top_p: 1
stream: false
api_key: sk-xxx
model_kwargs:
response_format:
type: json_object
api_version: 2024-02-01
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 +87,9 @@ 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"}},
"api_version": "2024-02-01"
}
},
"vectordb": {
@@ -143,7 +149,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 +205,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.
@@ -215,8 +222,9 @@ Alright, let's dive into what each key means in the yaml config above:
- `provider` (String): The provider for the embedder, set to 'openai'. You can find the full list of embedding model providers in [our docs](/components/embedding-models).
- `config`:
- `model` (String): The specific model used for text embedding, 'text-embedding-ada-002'.
- `vector_dimension` (Integer): The vector dimension of the embedding model. [Defaults](https://github.com/embedchain/embedchain/blob/e572b5a3dc1b66f1e9b3357d11a88c63b5ce06e3/embedchain/models/vector_dimensions.py)
- `vector_dimension` (Integer): The vector dimension of the embedding model. [Defaults](https://github.com/embedchain/embedchain/blob/main/embedchain/models/vector_dimensions.py)
- `api_key` (String): The API key for the embedding model.
- `endpoint` (String): The endpoint for the HuggingFace embedding model.
- `deployment_name` (String): The deployment name for the embedding model.
- `title` (String): The title for the embedding model for Google Embedder.
- `task_type` (String): The task type for the embedding model for Google Embedder.
+15
View File
@@ -129,3 +129,18 @@ app.chat("What is the net worth of Bill Gates?", session_id="user2")
app.chat("What was my last question", session_id="user1")
# 'Your last question was "What is the net worth of Elon Musk?"'
```
### With custom context window
If you want to customize the context window that you want to use during chat (default context window is 3 document chunks), you can do using the following code snippet:
```python with custom chunks size
from embedchain import App
from embedchain.config import BaseLlmConfig
app = App()
app.add("https://www.forbes.com/profile/elon-musk")
query_config = BaseLlmConfig(number_documents=5)
app.chat("What is the net worth of Elon Musk?", config=query_config)
```
+1 -27
View File
@@ -2,30 +2,4 @@
title: 🚀 deploy
---
Using the `deploy()` method, Embedchain allows developers to easily launch their LLM-powered applications on the [Embedchain Platform](https://app.embedchain.ai). This platform facilitates seamless access to your data's context via a free and user-friendly REST API. Once your pipeline is deployed, you can update your data sources at any time.
The `deploy()` method not only deploys your pipeline but also efficiently manages LLMs, vector databases, embedding models, and data syncing, enabling you to focus on querying, chatting, or searching without the hassle of infrastructure management.
## Usage
```python
from embedchain import App
# Initialize app
app = App()
# Add data source
app.add("https://www.forbes.com/profile/elon-musk")
# Deploy your pipeline to Embedchain Platform
app.deploy()
# 🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/
# ec-xxxxxx
# 🛠️ Creating pipeline on the platform...
# 🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/xxxxx
# 🛠️ Adding data to your pipeline...
# ✅ Data of type: web_page, value: https://www.forbes.com/profile/elon-musk added successfully.
```
The `deploy()` method 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.
+77 -23
View File
@@ -12,6 +12,13 @@ title: '🔍 search'
<ParamField path="num_documents" type="int" optional>
Number of relevant documents to fetch. Defaults to `3`
</ParamField>
<ParamField path="where" type="dict" optional>
Key value pair for metadata filtering.
</ParamField>
<ParamField path="raw_filter" type="dict" optional>
Pass raw filter query based on your vector database.
Currently, `raw_filter` param is only supported for Pinecone vector database.
</ParamField>
### Returns
@@ -21,37 +28,84 @@ title: '🔍 search'
## Usage
### Basic
Refer to the following example on how to use the search api:
```python Code example
from embedchain import App
# Initialize app
app = App()
# Add data source
app.add("https://www.forbes.com/profile/elon-musk")
# Get relevant context using semantic search
context = app.search("What is the net worth of Elon?", num_documents=2)
print(context)
# Context:
# [
# {
# 'context': 'Elon Musk PROFILEElon MuskCEO, Tesla$221.9BReal Time Net Worth ...',
# 'metadata': {
# 'source': 'https://www.forbes.com/profile/elon-musk',
# 'document_id': 'some_document_id',
# 'score': 0.404,
# }
# },
# {
# 'context': 'company, which is now called X.Wealth HistoryHOVER TO REVEAL NET WORTH ...',
# 'metadata': {
# 'source': 'https://www.forbes.com/profile/elon-musk',
# 'document_id': 'some_document_id',
# 'score': 0.435,
# }
# }
# ]
```
### Advanced
#### Metadata filtering using `where` params
Here is an advanced example of `search()` API with metadata filtering on pinecone database:
```python
import os
from embedchain import App
os.environ["PINECONE_API_KEY"] = "xxx"
config = {
"vectordb": {
"provider": "pinecone",
"config": {
"metric": "dotproduct",
"vector_dimension": 1536,
"index_name": "ec-test",
"serverless_config": {"cloud": "aws", "region": "us-west-2"},
},
}
}
app = App.from_config(config=config)
app.add("https://www.forbes.com/profile/bill-gates", metadata={"type": "forbes", "person": "gates"})
app.add("https://en.wikipedia.org/wiki/Bill_Gates", metadata={"type": "wiki", "person": "gates"})
results = app.search("What is the net worth of Bill Gates?", where={"person": "gates"})
print("Num of search results: ", len(results))
```
#### Metadata filtering using `raw_filter` params
Following is an example of metadata filtering by passing the raw filter query that pinecone vector database follows:
```python
import os
from embedchain import App
os.environ["PINECONE_API_KEY"] = "xxx"
config = {
"vectordb": {
"provider": "pinecone",
"config": {
"metric": "dotproduct",
"vector_dimension": 1536,
"index_name": "ec-test",
"serverless_config": {"cloud": "aws", "region": "us-west-2"},
},
}
}
app = App.from_config(config=config)
app.add("https://www.forbes.com/profile/bill-gates", metadata={"year": 2022, "person": "gates"})
app.add("https://en.wikipedia.org/wiki/Bill_Gates", metadata={"year": 2024, "person": "gates"})
print("Filter with person: gates and year > 2023")
raw_filter = {"$and": [{"person": "gates"}, {"year": {"$gt": 2023}}]}
results = app.search("What is the net worth of Bill Gates?", raw_filter=raw_filter)
print("Num of search results: ", len(results))
```
+25
View File
@@ -0,0 +1,25 @@
---
title: "🎤 Audio"
---
To use an audio as data source, just add `data_type` as `audio` and pass in the path of the audio (local or hosted).
We use [Deepgram](https://developers.deepgram.com/docs/introduction) to transcribe the audiot to text, and then use the generated text as the data source.
You would require an Deepgram API key which is available [here](https://console.deepgram.com/signup?jump=keys) to use this feature.
### Without customization
```python
import os
from embedchain import App
os.environ["DEEPGRAM_API_KEY"] = "153xxx"
app = App()
app.add("introduction.wav", data_type="audio")
response = app.query("What is my name and how old am I?")
print(response)
# Answer: Your name is Dave and you are 21 years old.
```
+4 -3
View File
@@ -7,11 +7,12 @@ When we say "custom", we mean that you can customize the loader and chunker to y
```python
from embedchain import App
import your_loader
import your_chunker
from my_module import CustomLoader
from my_module import CustomChunker
app = App()
loader = your_loader()
chunker = your_chunker()
loader = CustomLoader()
chunker = CustomChunker()
app.add("source", data_type="custom", loader=loader, chunker=chunker)
```
@@ -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()
```
+1 -1
View File
@@ -22,7 +22,7 @@ Following is an example of how to use the dropbox loader:
```python
import os
from embedchain import Pipeline as App
from embedchain import App
os.environ["DROPBOX_ACCESS_TOKEN"] = "sl.xxx"
os.environ["OPENAI_API_KEY"] = "sk-xxx"
@@ -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.")
```
+3 -1
View File
@@ -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>
@@ -19,10 +19,10 @@ The first time you use the loader, you will be prompted to enter your Google acc
```python
from embedchain import Pipeline as App
from embedchain import App
app = App()
url = "https://drive.google.com/drive/u/0/folders/xxx-xxx"
app.add(url, data_type="google_drive")
```
```
+31 -28
View File
@@ -5,34 +5,37 @@ title: Overview
Embedchain comes with built-in support for various data sources. We handle the complexity of loading unstructured data from these data sources, allowing you to easily customize your app through a user-friendly interface.
<CardGroup cols={4}>
<Card title="📰 PDF file" href="/components/data-sources/pdf-file"></Card>
<Card title="📊 CSV file" href="/components/data-sources/csv"></Card>
<Card title="📃 JSON file" href="/components/data-sources/json"></Card>
<Card title="📝 Text" href="/components/data-sources/text"></Card>
<Card title="📁 Directory/ Folder" href="/components/data-sources/directory"></Card>
<Card title="🌐 HTML Web page" href="/components/data-sources/web-page"></Card>
<Card title="📽️ Youtube Channel" href="/components/data-sources/youtube-channel"></Card>
<Card title="📺 Youtube Video" href="/components/data-sources/youtube-video"></Card>
<Card title="📚 Docs website" href="/components/data-sources/docs-site"></Card>
<Card title="📝 MDX file" href="/components/data-sources/mdx"></Card>
<Card title="📄 DOCX file" href="/components/data-sources/docx"></Card>
<Card title="📓 Notion" href="/components/data-sources/notion"></Card>
<Card title="🗺️ Sitemap" href="/components/data-sources/sitemap"></Card>
<Card title="🧾 XML file" href="/components/data-sources/xml"></Card>
<Card title="❓💬 Q&A pair" href="/components/data-sources/qna"></Card>
<Card title="🙌 OpenAPI" href="/components/data-sources/openapi"></Card>
<Card title="📬 Gmail" href="/components/data-sources/gmail"></Card>
<Card title="📝 Github" href="/components/data-sources/github"></Card>
<Card title="🐘 Postgres" href="/components/data-sources/postgres"></Card>
<Card title="🐬 MySQL" href="/components/data-sources/mysql"></Card>
<Card title="🤖 Slack" href="/components/data-sources/slack"></Card>
<Card title="💬 Discord" href="/components/data-sources/discord"></Card>
<Card title="🗨️ Discourse" href="/components/data-sources/discourse"></Card>
<Card title="📝 Substack" href="/components/data-sources/substack"></Card>
<Card title="🐝 Beehiiv" href="/components/data-sources/beehiiv"></Card>
<Card title="💾 Dropbox" href="/components/data-sources/dropbox"></Card>
<Card title="🖼️ Image" href="/components/data-sources/image"></Card>
<Card title="⚙️ Custom" href="/components/data-sources/custom"></Card>
<Card title="PDF file" href="/components/data-sources/pdf-file"></Card>
<Card title="CSV file" href="/components/data-sources/csv"></Card>
<Card title="JSON file" href="/components/data-sources/json"></Card>
<Card title="Text" href="/components/data-sources/text"></Card>
<Card title="Text File" href="/components/data-sources/text-file"></Card>
<Card title="Directory" href="/components/data-sources/directory"></Card>
<Card title="Web page" href="/components/data-sources/web-page"></Card>
<Card title="Youtube Channel" href="/components/data-sources/youtube-channel"></Card>
<Card title="Youtube Video" href="/components/data-sources/youtube-video"></Card>
<Card title="Docs website" href="/components/data-sources/docs-site"></Card>
<Card title="MDX file" href="/components/data-sources/mdx"></Card>
<Card title="DOCX file" href="/components/data-sources/docx"></Card>
<Card title="Notion" href="/components/data-sources/notion"></Card>
<Card title="Sitemap" href="/components/data-sources/sitemap"></Card>
<Card title="XML file" href="/components/data-sources/xml"></Card>
<Card title="Q&A pair" href="/components/data-sources/qna"></Card>
<Card title="OpenAPI" href="/components/data-sources/openapi"></Card>
<Card title="Gmail" href="/components/data-sources/gmail"></Card>
<Card title="Google Drive" href="/components/data-sources/google-drive"></Card>
<Card title="GitHub" href="/components/data-sources/github"></Card>
<Card title="Postgres" href="/components/data-sources/postgres"></Card>
<Card title="MySQL" href="/components/data-sources/mysql"></Card>
<Card title="Slack" href="/components/data-sources/slack"></Card>
<Card title="Discord" href="/components/data-sources/discord"></Card>
<Card title="Discourse" href="/components/data-sources/discourse"></Card>
<Card title="Substack" href="/components/data-sources/substack"></Card>
<Card title="Beehiiv" href="/components/data-sources/beehiiv"></Card>
<Card title="Dropbox" href="/components/data-sources/dropbox"></Card>
<Card title="Image" href="/components/data-sources/image"></Card>
<Card title="Audio" href="/components/data-sources/audio"></Card>
<Card title="Custom" href="/components/data-sources/custom"></Card>
</CardGroup>
<br/ >
+2 -2
View File
@@ -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")
```
@@ -7,7 +7,7 @@ title: '📽️ Youtube Channel'
Make sure you have all the required packages installed before using this data type. You can install them by running the following command in your terminal.
```bash
pip install -u "embedchain[youtube]"
pip install -U "embedchain[youtube]"
```
## Usage
@@ -7,7 +7,7 @@ title: '📺 Youtube Video'
Make sure you have all the required packages installed before using this data type. You can install them by running the following command in your terminal.
```bash
pip install -u "embedchain[youtube]"
pip install -U "embedchain[youtube]"
```
## Usage
+214
View File
@@ -13,6 +13,10 @@ 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>
<Card title="Clarifai" href="#clarifai"></Card>
</CardGroup>
## OpenAI
@@ -220,3 +224,213 @@ 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>
## Clarifai
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[clarifai]'
```
set the `CLARIFAI_PAT` as environment variable which you can find in the [security page](https://clarifai.com/settings/security). Optionally you can also pass the PAT key as parameters in LLM/Embedder class.
Now you are all set with exploring Embedchain.
<CodeGroup>
```python main.py
import os
from embedchain import App
os.environ["CLARIFAI_PAT"] = "XXX"
# load llm and embedder configuration from config.yaml file
app = App.from_config(config_path="config.yaml")
#Now let's add some data.
app.add("https://www.forbes.com/profile/elon-musk")
#Query the app
response = app.query("what college degrees does elon musk have?")
```
Head to [Clarifai Platform](https://clarifai.com/explore/models?page=1&perPage=24&filterData=%5B%7B%22field%22%3A%22output_fields%22%2C%22value%22%3A%5B%22embeddings%22%5D%7D%5D) to explore all the State of the Art embedding models available to use.
For passing LLM model inference parameters use `model_kwargs` argument in the config file. Also you can use `api_key` argument to pass `CLARIFAI_PAT` in the config.
```yaml config.yaml
llm:
provider: clarifai
config:
model: "https://clarifai.com/mistralai/completion/models/mistral-7B-Instruct"
model_kwargs:
temperature: 0.5
max_tokens: 1000
embedder:
provider: clarifai
config:
model: "https://clarifai.com/clarifai/main/models/BAAI-bge-base-en-v15"
```
</CodeGroup>
+2 -1
View File
@@ -9,4 +9,5 @@ You can configure following components
* [Data Source](/components/data-sources/overview)
* [LLM](/components/llms)
* [Embedding Model](/components/embedding-models)
* [Vector Database](/components/vector-databases)
* [Vector Database](/components/vector-databases)
* [Evaluation](/components/evaluation)
+284 -144
View File
@@ -15,6 +15,7 @@ Embedchain comes with built-in support for various popular large language models
<Card title="Together" href="#together"></Card>
<Card title="Ollama" href="#ollama"></Card>
<Card title="vLLM" href="#vllm"></Card>
<Card title="Clarifai" href="#clarifai"></Card>
<Card title="GPT4All" href="#gpt4all"></Card>
<Card title="JinaChat" href="#jinachat"></Card>
<Card title="Hugging Face" href="#hugging-face"></Card>
@@ -22,6 +23,8 @@ Embedchain comes with built-in support for various popular large language models
<Card title="Vertex AI" href="#vertex-ai"></Card>
<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
@@ -68,125 +71,75 @@ llm:
</CodeGroup>
### Function Calling
To enable [function calling](https://platform.openai.com/docs/guides/function-calling) in your application using embedchain and OpenAI, you need to pass functions into `OpenAILlm` class as an array of functions. Here are several ways in which you can achieve that:
Embedchain supports OpenAI [Function calling](https://platform.openai.com/docs/guides/function-calling) with a single function. It accepts inputs in accordance with the [Langchain interface](https://python.langchain.com/docs/modules/model_io/chat/function_calling#legacy-args-functions-and-function_call).
Examples:
<Accordion title="Using Pydantic Models">
<Accordion title="Pydantic Model">
```python
import os
from embedchain import App
from embedchain.llm.openai import OpenAILlm
import requests
from pydantic import BaseModel, Field, ValidationError, field_validator
from pydantic import BaseModel
os.environ["OPENAI_API_KEY"] = "sk-xxx"
class multiply(BaseModel):
"""Multiply two integers together."""
class QA(BaseModel):
"""
A question and answer pair.
"""
question: str = Field(
..., description="The question.", example="What is a mountain?"
)
answer: str = Field(
..., description="The answer.", example="A mountain is a hill."
)
person_who_is_asking: str = Field(
..., description="The person who is asking the question.", example="John"
)
@field_validator("question")
def question_must_end_with_a_question_mark(cls, v):
"""
Validate that the question ends with a question mark.
"""
if not v.endswith("?"):
raise ValueError("question must end with a question mark")
return v
@field_validator("answer")
def answer_must_end_with_a_period(cls, v):
"""
Validate that the answer ends with a period.
"""
if not v.endswith("."):
raise ValueError("answer must end with a period")
return v
llm = OpenAILlm(config=None,functions=[QA])
app = App(llm=llm)
result = app.query("Hey I am Sid. What is a mountain? A mountain is a hill.")
print(result)
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
```
</Accordion>
<Accordion title="Using OpenAI JSON schema">
</Accordion>
<Accordion title="Python function">
```python
def multiply(a: int, b: int) -> int:
"""Multiply two integers together.
Args:
a: First integer
b: Second integer
"""
return a * b
```
</Accordion>
<Accordion title="OpenAI tool dictionary">
```python
multiply = {
"type": "function",
"function": {
"name": "multiply",
"description": "Multiply two integers together.",
"parameters": {
"type": "object",
"properties": {
"a": {
"description": "First integer",
"type": "integer"
},
"b": {
"description": "Second integer",
"type": "integer"
}
},
"required": [
"a",
"b"
]
}
}
}
```
</Accordion>
With any of the previous inputs, the OpenAI LLM can be queried to provide the appropriate arguments for the function.
```python
import os
from embedchain import App
from embedchain.llm.openai import OpenAILlm
import requests
from pydantic import BaseModel, Field, ValidationError, field_validator
os.environ["OPENAI_API_KEY"] = "sk-xxx"
json_schema = {
"name": "get_qa",
"description": "A question and answer pair and the user who is asking the question.",
"parameters": {
"type": "object",
"properties": {
"question": {"type": "string", "description": "The question."},
"answer": {"type": "string", "description": "The answer."},
"person_who_is_asking": {
"type": "string",
"description": "The person who is asking the question.",
}
},
"required": ["question", "answer", "person_who_is_asking"],
},
}
llm = OpenAILlm(config=None,functions=[json_schema])
llm = OpenAILlm(tools=multiply)
app = App(llm=llm)
result = app.query("Hey I am Sid. What is a mountain? A mountain is a hill.")
print(result)
```
</Accordion>
<Accordion title="Using actual python functions">
```python
import os
from embedchain import App
from embedchain.llm.openai import OpenAILlm
import requests
from pydantic import BaseModel, Field, ValidationError, field_validator
os.environ["OPENAI_API_KEY"] = "sk-xxx"
def find_info_of_pokemon(pokemon: str):
"""
Find the information of the given pokemon.
Args:
pokemon: The pokemon.
"""
req = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}")
if req.status_code == 404:
raise ValueError("pokemon not found")
return req.json()
llm = OpenAILlm(config=None,functions=[find_info_of_pokemon])
app = App(llm=llm)
result = app.query("Tell me more about the pokemon pikachu.")
print(result)
result = app.query("What is the result of 125 multiplied by fifteen?")
```
</Accordion>
## Google AI
@@ -241,8 +194,8 @@ import os
from embedchain import App
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https://xxx.openai.azure.com/"
os.environ["OPENAI_API_KEY"] = "xxx"
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://xxx.openai.azure.com/"
os.environ["AZURE_OPENAI_KEY"] = "xxx"
os.environ["OPENAI_API_VERSION"] = "xxx"
app = App.from_config(config_path="config.yaml")
@@ -378,6 +331,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
@@ -392,6 +346,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>
@@ -425,6 +386,54 @@ llm:
</CodeGroup>
## Clarifai
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[clarifai]'
```
set the `CLARIFAI_PAT` as environment variable which you can find in the [security page](https://clarifai.com/settings/security). Optionally you can also pass the PAT key as parameters in LLM/Embedder class.
Now you are all set with exploring Embedchain.
<CodeGroup>
```python main.py
import os
from embedchain import App
os.environ["CLARIFAI_PAT"] = "XXX"
# load llm configuration from config.yaml file
app = App.from_config(config_path="config.yaml")
#Now let's add some data.
app.add("https://www.forbes.com/profile/elon-musk")
#Query the app
response = app.query("what college degrees does elon musk have?")
```
Head to [Clarifai Platform](https://clarifai.com/explore/models?page=1&perPage=24&filterData=%5B%7B%22field%22%3A%22use_cases%22%2C%22value%22%3A%5B%22llm%22%5D%7D%5D) to browse various State-of-the-Art LLM models for your use case.
For passing model inference parameters use `model_kwargs` argument in the config file. Also you can use `api_key` argument to pass `CLARIFAI_PAT` in the config.
```yaml config.yaml
llm:
provider: clarifai
config:
model: "https://clarifai.com/mistralai/completion/models/mistral-7B-Instruct"
model_kwargs:
temperature: 0.5
max_tokens: 1000
embedder:
provider: clarifai
config:
model: "https://clarifai.com/clarifai/main/models/BAAI-bge-base-en-v15"
```
</CodeGroup>
## GPT4ALL
Install related dependencies using the following command:
@@ -500,7 +509,15 @@ pip install --upgrade 'embedchain[huggingface-hub]'
First, set `HUGGINGFACE_ACCESS_TOKEN` in environment variable which you can obtain from [their platform](https://huggingface.co/settings/tokens).
Once you have the token, load the app using the config yaml file:
You can load the LLMs from Hugging Face using three ways:
- [Hugging Face Hub](#hugging-face-hub)
- [Hugging Face Local Pipelines](#hugging-face-local-pipelines)
- [Hugging Face Inference Endpoint](#hugging-face-inference-endpoint)
### Hugging Face Hub
To load the model from Hugging Face Hub, use the following code:
<CodeGroup>
@@ -510,24 +527,49 @@ from embedchain import App
os.environ["HUGGINGFACE_ACCESS_TOKEN"] = "xxx"
# load llm configuration from config.yaml file
app = App.from_config(config_path="config.yaml")
```
config = {
"app": {"config": {"id": "my-app"}},
"llm": {
"provider": "huggingface",
"config": {
"model": "bigscience/bloom-1b7",
"top_p": 0.5,
"max_length": 200,
"temperature": 0.1,
},
},
}
```yaml config.yaml
llm:
provider: huggingface
config:
model: 'google/flan-t5-xxl'
temperature: 0.5
max_tokens: 1000
top_p: 0.5
stream: false
app = App.from_config(config=config)
```
</CodeGroup>
### Custom Endpoints
### Hugging Face Local Pipelines
If you want to load the locally downloaded model from Hugging Face, you can do so by following the code provided below:
<CodeGroup>
```python main.py
from embedchain import App
config = {
"app": {"config": {"id": "my-app"}},
"llm": {
"provider": "huggingface",
"config": {
"model": "Trendyol/Trendyol-LLM-7b-chat-v0.1",
"local": True, # Necessary if you want to run model locally
"top_p": 0.5,
"max_tokens": 1000,
"temperature": 0.1,
},
}
}
app = App.from_config(config=config)
```
</CodeGroup>
### Hugging Face Inference Endpoint
You can also use [Hugging Face Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index#-inference-endpoints) to access custom endpoints. First, set the `HUGGINGFACE_ACCESS_TOKEN` as above.
@@ -536,35 +578,23 @@ Then, load the app using the config yaml file:
<CodeGroup>
```python main.py
import os
from embedchain import App
os.environ["HUGGINGFACE_ACCESS_TOKEN"] = "xxx"
config = {
"app": {"config": {"id": "my-app"}},
"llm": {
"provider": "huggingface",
"config": {
"endpoint": "https://api-inference.huggingface.co/models/gpt2",
"model_params": {"temprature": 0.1, "max_new_tokens": 100}
},
},
}
app = App.from_config(config=config)
# load llm configuration from config.yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
llm:
provider: huggingface
config:
endpoint: https://api-inference.huggingface.co/models/gpt2 # replace with your personal endpoint
```
</CodeGroup>
If your endpoint requires additional parameters, you can pass them in the `model_kwargs` field:
```
llm:
provider: huggingface
config:
endpoint: <YOUR_ENDPOINT_URL_HERE>
model_kwargs:
max_new_tokens: 100
temperature: 0.5
```
Currently only supports `text-generation` and `text2text-generation` for now [[ref](https://api.python.langchain.com/en/latest/llms/langchain_community.llms.huggingface_endpoint.HuggingFaceEndpoint.html?highlight=huggingfaceendpoint#)].
See langchain's [hugging face endpoint](https://python.langchain.com/docs/integrations/chat/huggingface#huggingfaceendpoint) for more information.
@@ -666,7 +696,8 @@ embedder:
### Setup
- Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess).
- You will also need `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` to authenticate the API with AWS. You can find these in your [AWS Console](https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/users).
- You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials)
- You can optionally export an `AWS_REGION`
### Usage
@@ -679,6 +710,7 @@ from embedchain import App
os.environ["AWS_ACCESS_KEY_ID"] = "xxx"
os.environ["AWS_SECRET_ACCESS_KEY"] = "xxx"
os.environ["AWS_REGION"] = "us-west-2"
app = App.from_config(config_path="config.yaml")
```
@@ -702,4 +734,112 @@ llm:
</Note>
<br/ >
## Groq
[Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine.
### Usage
In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key.
Set the API key as `GROQ_API_KEY` environment variable or pass in your app configuration to use the model as given below in the example.
<CodeGroup>
```python main.py
import os
from embedchain import App
# Set your API key here or pass as the environment variable
groq_api_key = "gsk_xxxx"
config = {
"llm": {
"provider": "groq",
"config": {
"model": "mixtral-8x7b-32768",
"api_key": groq_api_key,
"stream": True
}
}
}
app = App.from_config(config=config)
# Add your data source here
app.add("https://docs.embedchain.ai/sitemap.xml", data_type="sitemap")
app.query("Write a poem about Embedchain")
# In the realm of data, vast and wide,
# Embedchain stands with knowledge as its guide.
# A platform open, for all to try,
# Building bots that can truly fly.
# With REST API, data in reach,
# Deployment a breeze, as easy as a speech.
# Updating data sources, anytime, anyday,
# Embedchain's power, never sway.
# A knowledge base, an assistant so grand,
# Connecting to platforms, near and far.
# Discord, WhatsApp, Slack, and more,
# Embedchain's potential, never a bore.
```
</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" />
-238
View File
@@ -17,242 +17,4 @@ Utilizing a vector database alongside Embedchain is a seamless process. All you
<Card title="Weaviate" href="#weaviate"></Card>
</CardGroup>
## ChromaDB
<CodeGroup>
```python main.py
from embedchain import App
# load chroma configuration from yaml file
app = App.from_config(config_path="config1.yaml")
```
```yaml config1.yaml
vectordb:
provider: chroma
config:
collection_name: 'my-collection'
dir: db
allow_reset: true
```
```yaml config2.yaml
vectordb:
provider: chroma
config:
collection_name: 'my-collection'
host: localhost
port: 5200
allow_reset: true
```
</CodeGroup>
## Elasticsearch
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[elasticsearch]'
```
<Note>
You can configure the Elasticsearch connection by providing either `es_url` or `cloud_id`. If you are using the Elasticsearch Service on Elastic Cloud, you can find the `cloud_id` on the [Elastic Cloud dashboard](https://cloud.elastic.co/deployments).
</Note>
You can authorize the connection to Elasticsearch by providing either `basic_auth`, `api_key`, or `bearer_auth`.
<CodeGroup>
```python main.py
from embedchain import App
# load elasticsearch configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: elasticsearch
config:
collection_name: 'es-index'
cloud_id: 'deployment-name:xxxx'
basic_auth:
- elastic
- <your_password>
verify_certs: false
```
</CodeGroup>
## OpenSearch
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[opensearch]'
```
<CodeGroup>
```python main.py
from embedchain import App
# load opensearch configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: opensearch
config:
collection_name: 'my-app'
opensearch_url: 'https://localhost:9200'
http_auth:
- admin
- admin
vector_dimension: 1536
use_ssl: false
verify_certs: false
```
</CodeGroup>
## Zilliz
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[milvus]'
```
Set the Zilliz environment variables `ZILLIZ_CLOUD_URI` and `ZILLIZ_CLOUD_TOKEN` which you can find it on their [cloud platform](https://cloud.zilliz.com/).
<CodeGroup>
```python main.py
import os
from embedchain import App
os.environ['ZILLIZ_CLOUD_URI'] = 'https://xxx.zillizcloud.com'
os.environ['ZILLIZ_CLOUD_TOKEN'] = 'xxx'
# load zilliz configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: zilliz
config:
collection_name: 'zilliz_app'
uri: https://xxxx.api.gcp-region.zillizcloud.com
token: xxx
vector_dim: 1536
metric_type: L2
```
</CodeGroup>
## LanceDB
_Coming soon_
## Pinecone
Install pinecone related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[pinecone]'
```
In order to use Pinecone as vector database, set the environment variable `PINECONE_API_KEY` which you can find on [Pinecone dashboard](https://app.pinecone.io/).
<CodeGroup>
```python main.py
from embedchain import App
# load pinecone configuration from yaml file
app = App.from_config(config_path="pod_config.yaml")
# or
app = App.from_config(config_path="serverless_config.yaml")
```
```yaml pod_config.yaml
vectordb:
provider: pinecone
config:
metric: cosine
vector_dimension: 1536
collection_name: my-pinecone-index
pod_config:
environment: gcp-starter
metadata_config:
indexed:
- "url"
- "hash"
```
```yaml serverless_config.yaml
vectordb:
provider: pinecone
config:
metric: cosine
vector_dimension: 1536
collection_name: my-pinecone-index
serverless_config:
cloud: aws
region: us-west-2
```
</CodeGroup>
<br />
<Note>
You can find more information about Pinecone configuration [here](https://docs.pinecone.io/docs/manage-indexes#create-a-pod-based-index).
You can also optionally provide `index_name` as a config param in yaml file to specify the index name. If not provided, the index name will be `{collection_name}-{vector_dimension}`.
</Note>
## Qdrant
In order to use Qdrant as a vector database, set the environment variables `QDRANT_URL` and `QDRANT_API_KEY` which you can find on [Qdrant Dashboard](https://cloud.qdrant.io/).
<CodeGroup>
```python main.py
from embedchain import App
# load qdrant configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: qdrant
config:
collection_name: my_qdrant_index
```
</CodeGroup>
## Weaviate
In order to use Weaviate as a vector database, set the environment variables `WEAVIATE_ENDPOINT` and `WEAVIATE_API_KEY` which you can find on [Weaviate dashboard](https://console.weaviate.cloud/dashboard).
<CodeGroup>
```python main.py
from embedchain import App
# load weaviate configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: weaviate
config:
collection_name: my_weaviate_index
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,35 @@
---
title: ChromaDB
---
<CodeGroup>
```python main.py
from embedchain import App
# load chroma configuration from yaml file
app = App.from_config(config_path="config1.yaml")
```
```yaml config1.yaml
vectordb:
provider: chroma
config:
collection_name: 'my-collection'
dir: db
allow_reset: true
```
```yaml config2.yaml
vectordb:
provider: chroma
config:
collection_name: 'my-collection'
host: localhost
port: 5200
allow_reset: true
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,39 @@
---
title: Elasticsearch
---
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[elasticsearch]'
```
<Note>
You can configure the Elasticsearch connection by providing either `es_url` or `cloud_id`. If you are using the Elasticsearch Service on Elastic Cloud, you can find the `cloud_id` on the [Elastic Cloud dashboard](https://cloud.elastic.co/deployments).
</Note>
You can authorize the connection to Elasticsearch by providing either `basic_auth`, `api_key`, or `bearer_auth`.
<CodeGroup>
```python main.py
from embedchain import App
# load elasticsearch configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: elasticsearch
config:
collection_name: 'es-index'
cloud_id: 'deployment-name:xxxx'
basic_auth:
- elastic
- <your_password>
verify_certs: false
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,48 @@
---
title: LanceDB
---
## Install Embedchain with LanceDB
Install Embedchain, LanceDB and related dependencies using the following command:
```bash
pip install "embedchain[lancedb]"
```
LanceDB is a developer-friendly, open source database for AI. From hyper scalable vector search and advanced retrieval for RAG, to streaming training data and interactive exploration of large scale AI datasets.
In order to use LanceDB as vector database, not need to set any key for local use.
<CodeGroup>
```python main.py
import os
from embedchain import App
# set OPENAI_API_KEY as env variable
os.environ["OPENAI_API_KEY"] = "sk-xxx"
# Create Embedchain App and set config
app = App.from_config(config={
"vectordb": {
"provider": "lancedb",
"config": {
"collection_name": "lancedb-index"
}
}
}
)
# Add data source and start queryin
app.add("https://www.forbes.com/profile/elon-musk")
# query continuously
while(True):
question = input("Enter question: ")
if question in ['q', 'exit', 'quit']:
break
answer = app.query(question)
print(answer)
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,36 @@
---
title: OpenSearch
---
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[opensearch]'
```
<CodeGroup>
```python main.py
from embedchain import App
# load opensearch configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: opensearch
config:
collection_name: 'my-app'
opensearch_url: 'https://localhost:9200'
http_auth:
- admin
- admin
vector_dimension: 1536
use_ssl: false
verify_certs: false
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,109 @@
---
title: Pinecone
---
## Overview
Install pinecone related dependencies using the following command:
```bash
pip install --upgrade 'pinecone-client pinecone-text'
```
In order to use Pinecone as vector database, set the environment variable `PINECONE_API_KEY` which you can find on [Pinecone dashboard](https://app.pinecone.io/).
<CodeGroup>
```python main.py
from embedchain import App
# Load pinecone configuration from yaml file
app = App.from_config(config_path="pod_config.yaml")
# Or
app = App.from_config(config_path="serverless_config.yaml")
```
```yaml pod_config.yaml
vectordb:
provider: pinecone
config:
metric: cosine
vector_dimension: 1536
index_name: my-pinecone-index
pod_config:
environment: gcp-starter
metadata_config:
indexed:
- "url"
- "hash"
```
```yaml serverless_config.yaml
vectordb:
provider: pinecone
config:
metric: cosine
vector_dimension: 1536
index_name: my-pinecone-index
serverless_config:
cloud: aws
region: us-west-2
```
</CodeGroup>
<br />
<Note>
You can find more information about Pinecone configuration [here](https://docs.pinecone.io/docs/manage-indexes#create-a-pod-based-index).
You can also optionally provide `index_name` as a config param in yaml file to specify the index name. If not provided, the index name will be `{collection_name}-{vector_dimension}`.
</Note>
## Usage
### Hybrid search
Here is an example of how you can do hybrid search using Pinecone as a vector database through Embedchain.
```python
import os
from embedchain import App
config = {
'app': {
"config": {
"id": "ec-docs-hybrid-search"
}
},
'vectordb': {
'provider': 'pinecone',
'config': {
'metric': 'dotproduct',
'vector_dimension': 1536,
'index_name': 'my-index',
'serverless_config': {
'cloud': 'aws',
'region': 'us-west-2'
},
'hybrid_search': True, # Remember to set this for hybrid search
}
}
}
# Initialize app
app = App.from_config(config=config)
# Add documents
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.
If you have questions on how pinecone hybrid search works, please refer to their [offical documentation here](https://docs.pinecone.io/docs/hybrid-search).
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,23 @@
---
title: Qdrant
---
In order to use Qdrant as a vector database, set the environment variables `QDRANT_URL` and `QDRANT_API_KEY` which you can find on [Qdrant Dashboard](https://cloud.qdrant.io/).
<CodeGroup>
```python main.py
from embedchain import App
# load qdrant configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: qdrant
config:
collection_name: my_qdrant_index
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,24 @@
---
title: Weaviate
---
In order to use Weaviate as a vector database, set the environment variables `WEAVIATE_ENDPOINT` and `WEAVIATE_API_KEY` which you can find on [Weaviate dashboard](https://console.weaviate.cloud/dashboard).
<CodeGroup>
```python main.py
from embedchain import App
# load weaviate configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: weaviate
config:
collection_name: my_weaviate_index
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
@@ -0,0 +1,39 @@
---
title: Zilliz
---
Install related dependencies using the following command:
```bash
pip install --upgrade 'embedchain[milvus]'
```
Set the Zilliz environment variables `ZILLIZ_CLOUD_URI` and `ZILLIZ_CLOUD_TOKEN` which you can find it on their [cloud platform](https://cloud.zilliz.com/).
<CodeGroup>
```python main.py
import os
from embedchain import App
os.environ['ZILLIZ_CLOUD_URI'] = 'https://xxx.zillizcloud.com'
os.environ['ZILLIZ_CLOUD_TOKEN'] = 'xxx'
# load zilliz configuration from yaml file
app = App.from_config(config_path="config.yaml")
```
```yaml config.yaml
vectordb:
provider: zilliz
config:
collection_name: 'zilliz_app'
uri: https://xxxx.api.gcp-region.zillizcloud.com
token: xxx
vector_dim: 1536
metric_type: L2
```
</CodeGroup>
<Snippet file="missing-vector-db-tip.mdx" />
-4
View File
@@ -1,4 +0,0 @@
---
title: ' 🟨 Javascript'
url: https://github.com/embedchain/embedchain/tree/main/embedchain-js
---
View File
View File
-38
View File
@@ -1,38 +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](https://app.embedchain.ai). The platform offers free access to context on your data through its REST API. Once the pipeline is deployed, you can update your data sources anytime after deployment.
See the example below on how to use the deploy your app (for free):
```python
from embedchain import App
# Initialize app
app = App()
# Add data source
app.add("https://www.forbes.com/profile/elon-musk")
# Deploy your pipeline to Embedchain Platform
app.deploy()
# 🔑 Enter your Embedchain API key. You can find the API key at https://app.embedchain.ai/settings/keys/
# ec-xxxxxx
# 🛠️ Creating pipeline on the platform...
# 🎉🎉🎉 Pipeline created successfully! View your pipeline: https://app.embedchain.ai/pipelines/xxxxx
# 🛠️ Adding data to your pipeline...
# ✅ Data of type: web_page, value: https://www.forbes.com/profile/elon-musk added successfully.
```
## 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" />
+86
View File
@@ -0,0 +1,86 @@
---
title: 'Railway.app'
description: 'Deploy your RAG application to railway.app'
---
It's easy to host your Embedchain-powered apps and APIs on railway.
Follow the instructions given below to deploy your first application quickly:
## Step-1: Create RAG app
```bash Install embedchain
pip install embedchain
```
<Tip>
**Create a full stack app using Embedchain CLI**
To use your hosted embedchain RAG app, you can easily set up a FastAPI server that can be used anywhere.
To easily set up a FastAPI server, check out [Get started with Full stack](https://docs.embedchain.ai/get-started/full-stack) page.
Hosting this server on railway is super easy!
</Tip>
## Step-2: Set up your project
### With Docker
You can create a `Dockerfile` in the root of the project, with all the instructions. However, this method is sometimes slower in deployment.
### Without Docker
By default, Railway uses Python 3.7. Embedchain requires the python version to be >3.9 in order to install.
To fix this, create a `.python-version` file in the root directory of your project and specify the correct version
```bash .python-version
3.10
```
You also need to create a `requirements.txt` file to specify the requirements.
```bash requirements.txt
python-dotenv
embedchain
fastapi==0.108.0
uvicorn==0.25.0
embedchain
beautifulsoup4
sentence-transformers
```
## Step-3: Deploy to Railway 🚀
1. Go to https://railway.app and create an account.
2. Create a project by clicking on the "Start a new project" button
### With Github
Select `Empty Project` or `Deploy from Github Repo`.
You should be all set!
### Without Github
You can also use the railway CLI to deploy your apps from the terminal, if you don't want to connect a git repository.
To do this, just run this command in your terminal
```bash Install and set up railway CLI
npm i -g @railway/cli
railway login
railway link [projectID]
```
Finally, run `railway up` to deploy your app.
```bash Deploy
railway up
```
## 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" />
+1 -1
View File
@@ -9,10 +9,10 @@ After successfully setting up and testing your RAG app locally, the next step is
<Card title="Fly.io" href="/deployment/fly_io"></Card>
<Card title="Modal.com" href="/deployment/modal_com"></Card>
<Card title="Render.com" href="/deployment/render_com"></Card>
<Card title="Railway.app" href="/deployment/railway"></Card>
<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?
+19
View File
@@ -8,6 +8,9 @@ Get started with full-stack RAG applications using Embedchain's easy-to-use CLI
Choose your setup method:
* [Without docker](#without-docker)
* [With Docker](#with-docker)
### Without Docker
Ensure these are installed:
@@ -21,6 +24,14 @@ Install Docker from [Docker's official website](https://docs.docker.com/engine/i
## Quick Start Guide
### Install the package
Before proceeding, make sure you have the Embedchain package installed.
```bash
pip install embedchain -U
```
### Setting Up
For the purpose of the demo, you have to set `OPENAI_API_KEY` to start with but you can choose any llm by changing the configuration easily.
@@ -60,3 +71,11 @@ Open http://localhost:3000 to view the chat UI.
Check out the Embedchain admin panel to see the document chunks for your RAG application.
![full stack chunks](/images/fullstack-chunks.png)
### API Server
If you want to access the API server, you can do so at http://localhost:8000/docs.
![API Server](/images/fullstack-api-server.png)
You can customize the UI and code as per your requirements.
+6 -6
View File
@@ -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
+24 -18
View File
@@ -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")
Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

+29 -9
View File
@@ -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?")
```
+50
View File
@@ -0,0 +1,50 @@
---
title: '🔭 OpenLIT'
description: 'OpenTelemetry-native Observability and Evals for LLMs & GPUs'
---
Embedchain now supports integration with [OpenLIT](https://github.com/openlit/openlit).
## Getting Started
### 1. Set environment variables
```bash
# Setting environment variable for OpenTelemetry destination and authetication.
export OTEL_EXPORTER_OTLP_ENDPOINT = "YOUR_OTEL_ENDPOINT"
export OTEL_EXPORTER_OTLP_HEADERS = "YOUR_OTEL_ENDPOINT_AUTH"
```
### 2. Install the OpenLIT SDK
Open your terminal and run:
```shell
pip install openlit
```
### 3. Setup Your Application for Monitoring
Now create an app using Embedchain and initialize OpenTelemetry monitoring
```python
from embedchain import App
import OpenLIT
# Initialize OpenLIT Auto Instrumentation for monitoring.
openlit.init()
# 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?")
```
### 4. Visualize
Once you've set up data collection with OpenLIT, you can visualize and analyze this information to better understand your application's performance:
- **Using OpenLIT UI:** Connect to OpenLIT's UI to start exploring performance metrics. Visit the OpenLIT [Quickstart Guide](https://docs.openlit.io/latest/quickstart) for step-by-step details.
- **Integrate with existing Observability Tools:** If you use tools like Grafana or DataDog, you can integrate the data collected by OpenLIT. For instructions on setting up these connections, check the OpenLIT [Connections Guide](https://docs.openlit.io/latest/connections/intro).
+18 -8
View File
@@ -69,7 +69,8 @@
"pages": [
"integration/langsmith",
"integration/chainlit",
"integration/streamlit-mistral"
"integration/streamlit-mistral",
"integration/openlit"
]
}
]
@@ -88,9 +89,8 @@
"pages": [
"components/introduction",
{
"group": "Data sources",
"group": "🗂️ Data sources",
"pages": [
"components/data-sources/overview",
{
"group": "Data types",
@@ -129,8 +129,19 @@
"components/data-sources/data-type-handling"
]
},
{
"group": "🗄️ Vector databases",
"pages": [
"components/vector-databases/chromadb",
"components/vector-databases/elasticsearch",
"components/vector-databases/pinecone",
"components/vector-databases/opensearch",
"components/vector-databases/qdrant",
"components/vector-databases/weaviate",
"components/vector-databases/zilliz"
]
},
"components/llms",
"components/vector-databases",
"components/embedding-models",
"components/evaluation"
]
@@ -142,10 +153,10 @@
"deployment/fly_io",
"deployment/modal_com",
"deployment/render_com",
"deployment/railway",
"deployment/streamlit_io",
"deployment/gradio_app",
"deployment/huggingface_spaces",
"deployment/embedchain_ai"
"deployment/huggingface_spaces"
]
},
{
@@ -225,8 +236,7 @@
"contribution/guidelines",
"contribution/dev",
"contribution/docs",
"contribution/python",
"contribution/javascript"
"contribution/python"
]
},
{
-3
View File
@@ -1,3 +0,0 @@
---
title: 'FAQs'
---
-3
View File
@@ -1,3 +0,0 @@
---
title: 'Overview'
---
-3
View File
@@ -1,3 +0,0 @@
---
title: 'Quickstart'
---
-3
View File
@@ -1,3 +0,0 @@
---
title: 'Roadmap'
---
-3
View File
@@ -1,3 +0,0 @@
---
title: 'Security'
---
-2
View File
@@ -1,2 +0,0 @@
node_modules
dist
-56
View File
@@ -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
View File
@@ -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}}
-138
View File
@@ -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
-4
View File
@@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no -- commitlint --edit $1
-5
View File
@@ -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
-8
View File
@@ -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"
-201
View File
@@ -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.
-254
View File
@@ -1,254 +0,0 @@
# embedchainjs
[![Discord](https://dcbadge.vercel.app/api/server/CUU9FPhRNt?style=flat)](https://discord.gg/CUU9FPhRNt)
[![Twitter](https://img.shields.io/twitter/follow/embedchain)](https://twitter.com/embedchain)
[![Substack](https://img.shields.io/badge/Substack-%23006f5c.svg?logo=substack)](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
View File
@@ -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 };
-317
View File
@@ -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 };
-7
View File
@@ -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];
-7
View File
@@ -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];
-21
View File
@@ -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,
};
-26
View File
@@ -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 };
-9
View File
@@ -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 };
-5
View File
@@ -1,5 +0,0 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['.d.ts'],
};
-5
View File
@@ -1,5 +0,0 @@
module.exports = {
'*.{js,ts}': ['eslint --fix', 'eslint'],
'**/*.ts?(x)': () => 'npm run check-types',
'*.json': ['prettier --write'],
};
-18457
View File
File diff suppressed because it is too large Load Diff
-53
View File
@@ -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"
}
}
-4
View File
@@ -1,4 +0,0 @@
{
"extends": "./tsconfig.json",
"exclude": ["embedchain/__tests__"]
}

Some files were not shown because too many files have changed in this diff Show More