forked from langchain-ai/chat-langchain
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add streaming example code (langchain-ai#11)
* add streaming example code * cleanup * add gif to readme * update readme * update readme * update readme * consolidate * consolidate * fix readme * address comments * format * update requirements
- Loading branch information
Showing
18 changed files
with
635 additions
and
106 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
pip-wheel-metadata/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
*.py,cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
db.sqlite3-journal | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
.python-version | ||
|
||
# pipenv | ||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
# However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
# having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
# install all needed dependencies. | ||
#Pipfile.lock | ||
|
||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow | ||
__pypackages__/ | ||
|
||
# Celery stuff | ||
celerybeat-schedule | ||
celerybeat.pid | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# JetBrains | ||
.idea | ||
|
||
*.db | ||
|
||
.DS_Store | ||
|
||
vectorstore.pkl | ||
langchain.readthedocs.io/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
.PHONY: start | ||
start: | ||
uvicorn main:app --reload --port 9000 | ||
|
||
.PHONY: format | ||
format: | ||
black . | ||
isort . |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
"""Load html from files, clean up, split, ingest into Weaviate.""" | ||
import os | ||
from pathlib import Path | ||
|
||
import weaviate | ||
from bs4 import BeautifulSoup | ||
from langchain.text_splitter import CharacterTextSplitter | ||
|
||
|
||
def clean_data(data): | ||
soup = BeautifulSoup(data) | ||
text = soup.find_all("main", {"id": "main-content"})[0].get_text() | ||
return "\n".join([t for t in text.split("\n") if t]) | ||
|
||
|
||
docs = [] | ||
metadatas = [] | ||
for p in Path("langchain.readthedocs.io/en/latest/").rglob("*"): | ||
if p.is_dir(): | ||
continue | ||
with open(p) as f: | ||
docs.append(clean_data(f.read())) | ||
metadatas.append({"source": p}) | ||
|
||
|
||
text_splitter = CharacterTextSplitter( | ||
separator="\n", | ||
chunk_size=1000, | ||
chunk_overlap=200, | ||
length_function=len, | ||
) | ||
|
||
documents = text_splitter.create_documents(docs, metadatas=metadatas) | ||
|
||
|
||
WEAVIATE_URL = os.environ["WEAVIATE_URL"] | ||
client = weaviate.Client( | ||
url=WEAVIATE_URL, | ||
additional_headers={"X-OpenAI-Api-Key": os.environ["OPENAI_API_KEY"]}, | ||
) | ||
|
||
client.schema.delete_class("Paragraph") | ||
client.schema.get() | ||
schema = { | ||
"classes": [ | ||
{ | ||
"class": "Paragraph", | ||
"description": "A written paragraph", | ||
"vectorizer": "text2vec-openai", | ||
"moduleConfig": { | ||
"text2vec-openai": { | ||
"model": "ada", | ||
"modelVersion": "002", | ||
"type": "text", | ||
} | ||
}, | ||
"properties": [ | ||
{ | ||
"dataType": ["text"], | ||
"description": "The content of the paragraph", | ||
"moduleConfig": { | ||
"text2vec-openai": { | ||
"skip": False, | ||
"vectorizePropertyName": False, | ||
} | ||
}, | ||
"name": "content", | ||
}, | ||
{ | ||
"dataType": ["text"], | ||
"description": "The link", | ||
"moduleConfig": { | ||
"text2vec-openai": { | ||
"skip": True, | ||
"vectorizePropertyName": False, | ||
} | ||
}, | ||
"name": "source", | ||
}, | ||
], | ||
}, | ||
] | ||
} | ||
|
||
client.schema.create(schema) | ||
|
||
with client.batch as batch: | ||
for text in documents: | ||
batch.add_data_object( | ||
{"content": text.page_content, "source": str(text.metadata["source"])}, | ||
"Paragraph", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
# Bash script to ingest data | ||
# This involves scraping the data from the web and then cleaning up and putting in Weaviate. | ||
!set -eu | ||
wget -r -A.html https://langchain.readthedocs.io/en/latest/ | ||
python3 ingest.py | ||
python3 ingest_examples.py |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
langchain==0.0.64 | ||
beautifulsoup4 | ||
weaviate-client | ||
openai | ||
black | ||
isort | ||
Flask | ||
transformers | ||
gradio |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
"""Callback handlers used in the app.""" | ||
from typing import Any, Dict, List | ||
|
||
from langchain.callbacks.base import AsyncCallbackHandler | ||
|
||
from schemas import ChatResponse | ||
|
||
|
||
class StreamingLLMCallbackHandler(AsyncCallbackHandler): | ||
"""Callback handler for streaming LLM responses.""" | ||
|
||
def __init__(self, websocket): | ||
self.websocket = websocket | ||
|
||
async def on_llm_new_token(self, token: str, **kwargs: Any) -> None: | ||
resp = ChatResponse(sender="bot", message=token, type="stream") | ||
await self.websocket.send_json(resp.dict()) | ||
|
||
|
||
class QuestionGenCallbackHandler(AsyncCallbackHandler): | ||
"""Callback handler for question generation.""" | ||
|
||
def __init__(self, websocket): | ||
self.websocket = websocket | ||
|
||
async def on_llm_start( | ||
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any | ||
) -> None: | ||
"""Run when LLM starts running.""" | ||
resp = ChatResponse( | ||
sender="bot", message="Synthesizing question...", type="info" | ||
) | ||
await self.websocket.send_json(resp.dict()) |
Oops, something went wrong.