mirror of
https://github.com/run-llama/llama_cloud_services.git
synced 2026-07-16 05:29:59 -04:00
Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe9668dbd3 | |||
| 478142e509 | |||
| e76d5ba679 | |||
| 23dc9c0f68 | |||
| 8b96176d8a | |||
| 1bbf5f4823 | |||
| 2f57682035 | |||
| 4c05160f98 | |||
| 3e9ad64a7f | |||
| 21fa19c73b | |||
| 58257d546b | |||
| 5e99d810fd | |||
| a2dc717d85 | |||
| 87062e6ca8 | |||
| ae3a21c5ff | |||
| ccebb8a2fa | |||
| 2d21d6e688 | |||
| 270d96b7e3 | |||
| ea21daa96f | |||
| 42845f8d07 | |||
| 8b63ae9c46 | |||
| 173060dc50 | |||
| d19b35cd48 | |||
| 0c83fbd679 | |||
| 6ae9c1d9cb | |||
| 27523b657a | |||
| 56d73c1a3f | |||
| 0d2ad9faab | |||
| 4572f00657 | |||
| 9ed208131f | |||
| 91b03b2ea7 | |||
| 70b5dc3a63 | |||
| d6ab0aa232 | |||
| f679e1c76b | |||
| b91f86ba3d | |||
| 0f2302fda4 | |||
| ff729c05af | |||
| 76a6821fb8 | |||
| 97c7a38a69 | |||
| 5d398a8a64 | |||
| 4252f6186b | |||
| 22148ade9f | |||
| b8332fe8e1 | |||
| e40e92a133 | |||
| ba8f345f80 | |||
| 2ddbf1ba0d | |||
| 23567c8f98 | |||
| 8d39ae7763 | |||
| a2edc41fc7 | |||
| 591b6fc44d | |||
| f8a3d92ce0 |
@@ -0,0 +1,48 @@
|
||||
name: Build Package
|
||||
|
||||
# Build package on its own without additional pip install
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
# You can use PyPy versions in python-version.
|
||||
# For example, pypy-2.7 and pypy-3.8
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
python-version: ["3.9"]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- name: Install deps
|
||||
shell: bash
|
||||
run: poetry install
|
||||
- name: Ensure lock works
|
||||
shell: bash
|
||||
run: poetry lock
|
||||
- name: Build
|
||||
shell: bash
|
||||
run: poetry build
|
||||
- name: Test installing built package
|
||||
shell: bash
|
||||
run: python -m pip install .
|
||||
- name: Test import
|
||||
shell: bash
|
||||
working-directory: ${{ vars.RUNNER_TEMP }}
|
||||
run: python -c "import llama_parse"
|
||||
@@ -0,0 +1,81 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: ["main"]
|
||||
schedule:
|
||||
- cron: "30 16 * * 4"
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
# Runner size impacts CodeQL analysis time. To learn more, please see:
|
||||
# - https://gh.io/recommended-hardware-resources-for-running-codeql
|
||||
# - https://gh.io/supported-runners-and-hardware-resources
|
||||
# - https://gh.io/using-larger-runners
|
||||
# Consider using larger runners for possible analysis time improvements.
|
||||
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
|
||||
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ["python"]
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby', 'swift' ]
|
||||
# Use only 'java' to analyze code written in Java, Kotlin or both
|
||||
# Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
|
||||
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
|
||||
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||
# queries: security-extended,security-and-quality
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
|
||||
# If the Autobuild fails above, remove it and uncomment the following three lines.
|
||||
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
|
||||
|
||||
# - run: |
|
||||
# echo "Run, Build Application using script"
|
||||
# ./location_of_script_within_repo/buildscript.sh
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v2
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Linting
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
# You can use PyPy versions in python-version.
|
||||
# For example, pypy-2.7 and pypy-3.8
|
||||
matrix:
|
||||
python-version: ["3.9"]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- name: Install pre-commit
|
||||
shell: bash
|
||||
run: poetry run pip install pre-commit
|
||||
- name: Run linter
|
||||
shell: bash
|
||||
run: poetry run make lint
|
||||
@@ -0,0 +1,64 @@
|
||||
name: Publish llama-parse to PyPI / GitHub
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
PYTHON_VERSION: "3.9"
|
||||
|
||||
jobs:
|
||||
build-n-publish:
|
||||
name: Build and publish to PyPI
|
||||
if: github.repository == 'run-llama/llama_parse'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up python ${{ env.PYTHON_VERSION }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- name: Install deps
|
||||
shell: bash
|
||||
run: pip install -e .
|
||||
- name: Build and publish to pypi
|
||||
uses: JRubics/poetry-publish@v1.17
|
||||
with:
|
||||
pypi_token: ${{ secrets.LLAMA_PARSE_PYPI_TOKEN }}
|
||||
ignore_dev_requirements: "yes"
|
||||
|
||||
- name: Create GitHub Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: Get Asset name
|
||||
run: |
|
||||
export PKG=$(ls dist/ | grep tar)
|
||||
set -- $PKG
|
||||
echo "name=$1" >> $GITHUB_ENV
|
||||
- name: Upload Release Asset (sdist) to GitHub
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: dist/${{ env.name }}
|
||||
asset_name: ${{ env.name }}
|
||||
asset_content_type: application/zip
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Unit Testing
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
LLAMA_CLOUD_API_KEY: ${{ secrets.LLAMA_CLOUD_API_KEY }}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
# You can use PyPy versions in python-version.
|
||||
# For example, pypy-2.7 and pypy-3.8
|
||||
matrix:
|
||||
python-version: ["3.8", "3.10", "3.11"]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- name: Install deps
|
||||
shell: bash
|
||||
run: poetry install --with dev
|
||||
- name: Run testing
|
||||
env:
|
||||
CI: true
|
||||
shell: bash
|
||||
run: poetry run pytest tests
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
.git
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
default_language_version:
|
||||
python: python3
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.5.0
|
||||
hooks:
|
||||
- id: check-byte-order-marker
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
- id: check-toml
|
||||
- id: check-yaml
|
||||
- id: detect-private-key
|
||||
- id: end-of-file-fixer
|
||||
- id: mixed-line-ending
|
||||
- id: trailing-whitespace
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.1.5
|
||||
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
exclude: ".*poetry.lock"
|
||||
- repo: https://github.com/psf/black-pre-commit-mirror
|
||||
rev: 23.10.1
|
||||
hooks:
|
||||
- id: black-jupyter
|
||||
name: black-src
|
||||
alias: black
|
||||
exclude: ".*poetry.lock"
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.0.1
|
||||
hooks:
|
||||
- id: mypy
|
||||
additional_dependencies:
|
||||
[
|
||||
"types-requests",
|
||||
"types-Deprecated",
|
||||
"types-redis",
|
||||
"types-setuptools",
|
||||
"types-PyYAML",
|
||||
"types-protobuf==4.24.0.4",
|
||||
]
|
||||
args:
|
||||
[
|
||||
--disallow-untyped-defs,
|
||||
--ignore-missing-imports,
|
||||
--python-version=3.8,
|
||||
]
|
||||
- repo: https://github.com/adamchainz/blacken-docs
|
||||
rev: 1.16.0
|
||||
hooks:
|
||||
- id: blacken-docs
|
||||
name: black-docs-text
|
||||
alias: black
|
||||
types_or: [rst, markdown, tex]
|
||||
additional_dependencies: [black==23.10.1]
|
||||
# Using PEP 8's line length in docs prevents excess left/right scrolling
|
||||
args: [--line-length=79]
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v3.0.3
|
||||
hooks:
|
||||
- id: prettier
|
||||
exclude: poetry.lock
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.2.6
|
||||
hooks:
|
||||
- id: codespell
|
||||
additional_dependencies: [tomli]
|
||||
exclude: ^(poetry.lock|examples)
|
||||
args:
|
||||
[
|
||||
"--ignore-words-list",
|
||||
"astroid,gallary,momento,narl,ot,rouge,nin,gere,te,inh,vor",
|
||||
]
|
||||
- repo: https://github.com/srstevenson/nb-clean
|
||||
rev: 3.1.0
|
||||
hooks:
|
||||
- id: nb-clean
|
||||
args: [--preserve-cell-outputs, --remove-empty-cells]
|
||||
- repo: https://github.com/pappasam/toml-sort
|
||||
rev: v0.23.1
|
||||
hooks:
|
||||
- id: toml-sort-fix
|
||||
exclude: ".*poetry.lock"
|
||||
@@ -0,0 +1,14 @@
|
||||
GIT_ROOT ?= $(shell git rev-parse --show-toplevel)
|
||||
|
||||
help: ## Show all Makefile targets.
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[33m%-30s\033[0m %s\n", $$1, $$2}'
|
||||
|
||||
format: ## Run code autoformatters (black).
|
||||
pre-commit install
|
||||
git ls-files | xargs pre-commit run black --files
|
||||
|
||||
lint: ## Run linters: pre-commit (black, ruff, codespell) and mypy
|
||||
pre-commit install && git ls-files | xargs pre-commit run --show-diff-on-failure --files
|
||||
|
||||
test: ## Run tests via pytest
|
||||
pytest tests
|
||||
@@ -4,12 +4,13 @@ LlamaParse is an API created by LlamaIndex to efficiently parse and represent fi
|
||||
|
||||
LlamaParse directly integrates with [LlamaIndex](https://github.com/run-llama/llama_index).
|
||||
|
||||
|
||||
Free plan is up to 1000 pages a day. Paid plan is free 7k pages per week + 0.3c per additional page.
|
||||
|
||||
Read below for some quickstart information, or see the [full documentation](https://docs.cloud.llamaindex.ai/).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, login and get an api-key from `https://cloud.llamaindex.ai`.
|
||||
First, login and get an api-key from [**https://cloud.llamaindex.ai ↗**](https://cloud.llamaindex.ai).
|
||||
|
||||
Then, make sure you have the latest LlamaIndex version installed.
|
||||
|
||||
@@ -28,6 +29,7 @@ Now you can run the following to parse your first PDF file:
|
||||
|
||||
```python
|
||||
import nest_asyncio
|
||||
|
||||
nest_asyncio.apply()
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
@@ -35,9 +37,9 @@ from llama_parse import LlamaParse
|
||||
parser = LlamaParse(
|
||||
api_key="llx-...", # can also be set in your env as LLAMA_CLOUD_API_KEY
|
||||
result_type="markdown", # "markdown" and "text" are available
|
||||
num_workers=4, # if multiple files passed, split in `num_workers` API calls
|
||||
num_workers=4, # if multiple files passed, split in `num_workers` API calls
|
||||
verbose=True,
|
||||
language="en" # Optionaly you can define a language, default=en
|
||||
language="en", # Optionally you can define a language, default=en
|
||||
)
|
||||
|
||||
# sync
|
||||
@@ -53,12 +55,41 @@ documents = await parser.aload_data("./my_file.pdf")
|
||||
documents = await parser.aload_data(["./my_file1.pdf", "./my_file2.pdf"])
|
||||
```
|
||||
|
||||
## Using with file object
|
||||
|
||||
You can parse a file object directly:
|
||||
|
||||
```python
|
||||
import nest_asyncio
|
||||
|
||||
nest_asyncio.apply()
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
parser = LlamaParse(
|
||||
api_key="llx-...", # can also be set in your env as LLAMA_CLOUD_API_KEY
|
||||
result_type="markdown", # "markdown" and "text" are available
|
||||
num_workers=4, # if multiple files passed, split in `num_workers` API calls
|
||||
verbose=True,
|
||||
language="en", # Optionally you can define a language, default=en
|
||||
)
|
||||
|
||||
with open("./my_file1.pdf", "rb") as f:
|
||||
documents = parser.load_data(f)
|
||||
|
||||
# you can also pass file bytes directly
|
||||
with open("./my_file1.pdf", "rb") as f:
|
||||
file_bytes = f.read()
|
||||
documents = parser.load_data(file_bytes)
|
||||
```
|
||||
|
||||
## Using with `SimpleDirectoryReader`
|
||||
|
||||
You can also integrate the parser as the default PDF loader in `SimpleDirectoryReader`:
|
||||
|
||||
```python
|
||||
import nest_asyncio
|
||||
|
||||
nest_asyncio.apply()
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
@@ -67,11 +98,13 @@ from llama_index.core import SimpleDirectoryReader
|
||||
parser = LlamaParse(
|
||||
api_key="llx-...", # can also be set in your env as LLAMA_CLOUD_API_KEY
|
||||
result_type="markdown", # "markdown" and "text" are available
|
||||
verbose=True
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
file_extractor = {".pdf": parser}
|
||||
documents = SimpleDirectoryReader("./data", file_extractor=file_extractor).load_data()
|
||||
documents = SimpleDirectoryReader(
|
||||
"./data", file_extractor=file_extractor
|
||||
).load_data()
|
||||
```
|
||||
|
||||
Full documentation for `SimpleDirectoryReader` can be found on the [LlamaIndex Documentation](https://docs.llamaindex.ai/en/stable/module_guides/loading/simpledirectoryreader.html).
|
||||
@@ -84,6 +117,10 @@ Several end-to-end indexing examples can be found in the examples folder
|
||||
- [Advanced RAG Example](examples/demo_advanced.ipynb)
|
||||
- [Raw API Usage](examples/demo_api.ipynb)
|
||||
|
||||
## Documentation
|
||||
|
||||
[https://docs.cloud.llamaindex.ai/](https://docs.cloud.llamaindex.ai/)
|
||||
|
||||
## Terms of Service
|
||||
|
||||
See the [Terms of Service Here](./TOS.pdf).
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LlamaParse Agent\n",
|
||||
"\n",
|
||||
"This demo walks through using an OpenAI Agent with [LlamaParse](https://cloud.llamaindex.ai)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install llama-parse llama-index llama-index-postprocessor-sbert-rerank"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-...\"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"sk-...\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import Settings\n",
|
||||
"from llama_index.embeddings.openai import OpenAIEmbedding\n",
|
||||
"from llama_index.llms.openai import OpenAI\n",
|
||||
"\n",
|
||||
"Settings.embed_model = OpenAIEmbedding(model=\"text-embedding-3-small\")\n",
|
||||
"Settings.llm = OpenAI(model=\"gpt-3.5-turbo\", temperature=0.2)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Parsing \n",
|
||||
"\n",
|
||||
"For parsing, lets use a [recent paper](https://huggingface.co/papers/2403.09611) on Multi-Modal pretraining"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!wget https://arxiv.org/pdf/2403.09611.pdf -O paper.pdf"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Below, we can tell the parser to skip content we don't want. In this case, the references section will just add noise to a RAG system."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"parser = LlamaParse(\n",
|
||||
" result_type=\"markdown\",\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id 81251f39-01be-434e-99e8-1c1b83b82098\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"documents = await parser.aload_data(\"paper.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Embeddings have been explicitly disabled. Using MockEmbedding.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"41it [00:00, 26765.21it/s]\n",
|
||||
"100%|██████████| 41/41 [00:13<00:00, 2.98it/s]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"from llama_index.core.node_parser import (\n",
|
||||
" MarkdownElementNodeParser,\n",
|
||||
" SentenceSplitter,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# explicitly extract tables with the MarkdownElementNodeParser\n",
|
||||
"node_parser = MarkdownElementNodeParser(num_workers=8)\n",
|
||||
"nodes = node_parser.get_nodes_from_documents(documents)\n",
|
||||
"nodes, objects = node_parser.get_nodes_and_objects(nodes)\n",
|
||||
"\n",
|
||||
"# Chain splitters to ensure chunk size requirements are met\n",
|
||||
"nodes = SentenceSplitter(chunk_size=512, chunk_overlap=20).get_nodes_from_documents(\n",
|
||||
" nodes\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Chat over the paper, lets find out what it is about!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import VectorStoreIndex, SummaryIndex\n",
|
||||
"\n",
|
||||
"vector_index = VectorStoreIndex(nodes=nodes)\n",
|
||||
"summary_index = SummaryIndex(nodes=nodes)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.agent.openai import OpenAIAgent\n",
|
||||
"from llama_index.core.tools import QueryEngineTool, ToolMetadata\n",
|
||||
"from llama_index.postprocessor.colbert_rerank import ColbertRerank\n",
|
||||
"\n",
|
||||
"tools = [\n",
|
||||
" QueryEngineTool(\n",
|
||||
" vector_index.as_query_engine(\n",
|
||||
" similarity_top_k=8, node_postprocessors=[ColbertRerank(top_n=3)]\n",
|
||||
" ),\n",
|
||||
" metadata=ToolMetadata(\n",
|
||||
" name=\"search\",\n",
|
||||
" description=\"Search the document, pass the entire user message in the query\",\n",
|
||||
" ),\n",
|
||||
" ),\n",
|
||||
" QueryEngineTool(\n",
|
||||
" summary_index.as_query_engine(),\n",
|
||||
" metadata=ToolMetadata(\n",
|
||||
" name=\"summarize\",\n",
|
||||
" description=\"Summarize the document using the user message\",\n",
|
||||
" ),\n",
|
||||
" ),\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"agent = OpenAIAgent.from_tools(tools=tools, verbose=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Added user message to memory: What is the summary of the paper?\n",
|
||||
"=== Calling Function ===\n",
|
||||
"Calling function: summarize with args: {\"input\":\"summary\"}\n",
|
||||
"Got output: The research focuses on developing Multimodal Large Language Models (MLLMs) by incorporating image-caption, interleaved image-text, and text-only data for pre-training. It highlights the importance of factors like the image encoder, resolution, and token count, while downplaying the design of the vision-language connector. With models scaling up to 30B parameters, the MM1 family demonstrates impressive performance in pre-training metrics and competitive outcomes on diverse multimodal benchmarks. It demonstrates abilities such as in-context learning and multi-image reasoning, aiming to provide valuable insights for creating MLLMs that benefit the research community.\n",
|
||||
"========================\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# note -- this will take a while with local LLMs, its sending every node in the document to the LLM\n",
|
||||
"resp = agent.chat(\"What is the summary of the paper?\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The summary of the paper highlights the development of Multimodal Large Language Models (MLLMs) by incorporating image-caption, interleaved image-text, and text-only data for pre-training. The research emphasizes factors like the image encoder, resolution, and token count, while de-emphasizing the design of the vision-language connector. The MM1 family of models, scaling up to 30B parameters, shows impressive performance in pre-training metrics and competitive outcomes on various multimodal benchmarks. These models demonstrate capabilities such as in-context learning and multi-image reasoning, aiming to provide valuable insights for creating MLLMs that benefit the research community.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(resp))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Added user message to memory: How do the authors evaluate their work?\n",
|
||||
"=== Calling Function ===\n",
|
||||
"Calling function: search with args: {\"input\":\"evaluation methods\"}\n",
|
||||
"Got output: The evaluation methods involve synthesizing all benchmark results into a single meta-average number to simplify comparisons. This is achieved by normalizing the evaluation metrics with respect to a baseline configuration, standardizing the results for each task, adjusting every metric by dividing it by its respective baseline, and then averaging across all metrics.\n",
|
||||
"========================\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"resp = agent.chat(\"How do the authors evaluate their work?\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The authors evaluate their work by synthesizing all benchmark results into a single meta-average number to simplify comparisons. They normalize the evaluation metrics with respect to a baseline configuration, standardize the results for each task, adjust every metric by dividing it by its respective baseline, and then average across all metrics for evaluation.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(resp))"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama-parse-aNC435Vv-py3.10",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,529 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "c148b65e-e8a6-476e-86ba-bf6a73d479c7",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# RAG over the Caltrain Weekend Schedule \n",
|
||||
"\n",
|
||||
"<a href=\"https://colab.research.google.com/github/run-llama/llama_parse/blob/main/examples/caltrain/caltrain_text_mode.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
|
||||
"\n",
|
||||
"This example shows off LlamaParse parsing capabilities to build a functioning query pipeline over the Caltrain weekend schedule, a big timetable containing all trains northbound and southbound and their stops in various cities.\n",
|
||||
"\n",
|
||||
"Naive parsing solutions mess up in representing this tabular representation, leading to LLM hallucinations. In contrast, LlamaParse text-mode spatially lays out the table in a neat format, enabling more sophisticated LLMs like gpt-4-turbo to understand the spacing and reason over all the numbers.\n",
|
||||
"\n",
|
||||
"**NOTE**: LlamaParse markdown mode doesn't quite work yet - it's in development!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "ef115dbe-b834-4639-828e-e2c11aef710b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup\n",
|
||||
"\n",
|
||||
"Download the data."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e6ae2e38-30c9-4865-aa13-47780bc3848f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "335ce1d0-757a-4f09-846e-21c409768871",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!wget \"https://www.caltrain.com/media/31602/download?inline?inline\" -O caltrain_schedule_weekend.pdf"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "45fa9120-65bb-4772-9db7-53e7cecf9adc",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Initialize LlamaParse\n",
|
||||
"\n",
|
||||
"Initialize LlamaParse in `text` mode which will represent complex documents incl. text, tables, and figures as nicely formatted text."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "54aa9579-84d4-49bc-ab54-5474e69c1188",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"/Users/jerryliu/Programming/llama_parse/.venv/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
||||
" from .autonotebook import tqdm as notebook_tqdm\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id 5f73353a-1f4b-480d-9eea-58d1d22b75f6\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"docs = LlamaParse(result_type=\"text\").load_data(\"./caltrain_schedule_weekend.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "602756b2-9ea1-4519-a8e3-c773ec624205",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Take a look at the below text (and zoom out from the browser to really get the effect!). You'll see that the entire table is nicely laid out."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "4928281a-591a-4653-b451-b2b8112a7101",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"ZONE 2ZONE 3ZONE 4ZONE 4 ZONE 3ZONE 2ZONE 1ZONE 1\n",
|
||||
" Printer-Friendly Caltrain Schedule\n",
|
||||
" Northbound – WEEKEND SERVICE to SAN FRANCISCO 2XX Local\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" Train No. 221 225 229 233 237 241 245 249 253 257 261 265 269 273 *277 *281\n",
|
||||
" Service Types L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2\n",
|
||||
" Tamien 7:12a 9:05a 10:05a 11:05a 1:05p 3:05p 5:05p 7:05p 9:05p 11:05p\n",
|
||||
" San Jose Diridon 7:19a 9:12a 10:12a 11:12a 12:12p 1:12p 2:12p 3:12p 4:12p 5:12p 6:12p 7:12p 8:12p 9:12p 10:19p 11:12p\n",
|
||||
" Santa Clara 7:25a 9:18a 10:18a 11:18a 12:18p 1:18p 2:18p 3:18p 4:18p 5:18p 6:18p 7:18p 8:18p 9:18p 10:25p 11:18p\n",
|
||||
" Lawrence 7:31a 9:24a 10:24a 11:24a 12:24p 1:24p 2:24p 3:24p 4:24p 5:24p 6:24p 7:24p 8:24p 9:24p 10:31p 11:24p\n",
|
||||
" Sunnyvale 7:35a 9:28a 10:28a 11:28a 12:28p 1:28p 2:28p 3:28p 4:28p 5:28p 6:28p 7:28p 8:28p 9:28p 10:35p 11:28p\n",
|
||||
" Mountain View 7:40a 9:34a 10:34a 11:34a 12:34p 1:34p 2:34p 3:34p 4:34p 5:34p 6:34p 7:34p 8:34p 9:34p 10:40p 11:34p\n",
|
||||
" San Antonio 7:43a 9:37a 10:37a 11:37a 12:37p 1:37p 2:37p 3:37p 4:37p 5:37p 6:37p 7:37p 8:37p 9:37p 10:44p 11:37p\n",
|
||||
" California Ave 7:48a 9:42a 10:42a 11:42a 12:42p 1:42p 2:42p 3:42p 4:42p 5:42p 6:42p 7:42p 8:42p 9:42p 10:48p 11:42p\n",
|
||||
" Palo Alto 7:52a 9:46a 10:46a 11:46a 12:46p 1:46p 2:46p 3:46p 4:46p 5:46p 6:46p 7:46p 8:46p 9:46p 10:53p 11:46p\n",
|
||||
" Menlo Park 7:55a 9:50a 10:50a 11:50a 12:50p 1:50p 2:50p 3:50p 4:50p 5:50p 6:50p 7:50p 8:50p 9:50p 10:56p 11:50p\n",
|
||||
" Redwood City 8:01a 9:56a 10:56a 11:56a 12:56p 1:56p 2:56p 3:56p 4:56p 5:56p 6:56p 7:56p 8:56p 9:56p 11:02p 11:56p\n",
|
||||
" San Carlos 8:05a 10:01a 11:01a 12:01p 1:01p 2:01p 3:01p 4:01p 5:01p 6:01p 7:01p 8:01p 9:01p 10:01p 11:07p 12:01a\n",
|
||||
" Belmont 8:09a 10:04a 11:04a 12:04p 1:04p 2:04p 3:04p 4:04p 5:04p 6:04p 7:04p 8:04p 9:04p 10:04p 11:10p 12:04a\n",
|
||||
" Hillsdale 8:12a 10:08a 11:08a 12:08p 1:08p 2:08p 3:08p 4:08p 5:08p 6:08p 7:08p 8:08p 9:08p 10:08p 11:14p 12:08a\n",
|
||||
" Hayward Park 8:15a 10:11a 11:11a 12:11p 1:11p 2:11p 3:11p 4:11p 5:11p 6:11p 7:11p 8:11p 9:11p 10:11p 11:17p 12:11a\n",
|
||||
" San Mateo 8:19a 10:15a 11:15a 12:15p 1:15p 2:15p 3:15p 4:15p 5:15p 6:15p 7:15p 8:15p 9:15p 10:15p 11:21p 12:15a\n",
|
||||
" Burlingame 8:22a 10:19a 11:19a 12:19p 1:19p 2:19p 3:19p 4:19p 5:19p 6:19p 7:19p 8:19p 9:19p 10:19p 11:25p 12:19a\n",
|
||||
" Broadway 8:25a 10:22a 11:22a 12:22p 1:22p 2:22p 3:22p 4:22p 5:22p 6:22p 7:22p 8:22p 9:22p 10:22p 11:28p 12:22a\n",
|
||||
" Millbrae 8:29a 10:26a 11:26a 12:26p 1:26p 2:26p 3:26p 4:26p 5:26p 6:26p 7:26p 8:26p 9:26p 10:26p 11:32p 12:26a\n",
|
||||
" San Bruno 8:34a 10:30a 11:30a 12:30p 1:30p 2:30p 3:30p 4:30p 5:30p 6:30p 7:30p 8:30p 9:30p 10:30p 11:37p 12:30a\n",
|
||||
" S. San Francisco 8:38a 10:34a 11:34a 12:34p 1:34p 2:34p 3:34p 4:34p 5:34p 6:34p 7:34p 8:34p 9:34p 10:34p 11:41p 12:34a\n",
|
||||
" Bayshore 8:44a 10:41a 11:41a 12:41p 1:41p 2:41p 3:41p 4:41p 5:41p 6:41p 7:41p 8:41p 9:41p 10:41p 11:47p 12:41a\n",
|
||||
" 22 ndStreet 8:50a 10:46a 11:46a 12:46p 1:46p 2:46p 3:46p 4:46p 5:46p 6:46p 7:46p 8:46p 9:46p 10:46p 11:53p 12:46a\n",
|
||||
" San Francisco 8:56a 10:52a 11:53a 12:53p 1:52p 2:52p 3:52p 4:52p 5:52p 6:52p 7:52p 8:52p 9:52p 10:52p 11:59p 12:52a\n",
|
||||
" *On SAP Center event days, Train 277 or Train 281departure from San Jose Diridon station may be delayed and will depart no later than 10:30p or 11:30p respectively.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" Southbound – WEEKEND SERVICE to SAN JOSE 2XX Local\n",
|
||||
" Train No. 224 228 232 236 240 244 248 252 256 260 264 268 272 276 280 284\n",
|
||||
" Service Types L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2\n",
|
||||
" San Francisco 8:28a 9:58a 10:58a 11:58a 12:58p 1:58p 2:58p 3:58p 4:58p 5:58p 6:58p 7:58p 8:58p 9:58p 10:58p 12:05a\n",
|
||||
" 22 ndStreet 8:33a 10:03a 11:03a 12:03p 1:03p 2:03p 3:03p 4:03p 5:03p 6:03p 7:03p 8:03p 9:03p 10:03p 11:03p 12:10a\n",
|
||||
" Bayshore 8:38a 10:08a 11:08a 12:08p 1:08p 2:08p 3:08p 4:08p 5:08p 6:08p 7:08p 8:08p 9:08p 10:08p 11:08p 12:15a\n",
|
||||
" S. San Francisco 8:45a 10:15a 11:15a 12:15p 1:15p 2:15p 3:15p 4:15p 5:15p 6:15p 7:15p 8:15p 9:15p 10:15p 11:15p 12:22a\n",
|
||||
" San Bruno 8:49a 10:19a 11:19a 12:19p 1:19p 2:19p 3:19p 4:19p 5:19p 6:19p 7:19p 8:19p 9:19p 10:19p 11:19p 12:26a\n",
|
||||
" Millbrae 8:53a 10:24a 11:24a 12:24p 1:24p 2:24p 3:24p 4:24p 5:24p 6:24p 7:24p 8:24p 9:24p 10:24p 11:24p 12:31a\n",
|
||||
" Broadway 8:57a 10:27a 11:27a 12:27p 1:27p 2:27p 3:27p 4:27p 5:27p 6:27p 7:27p 8:27p 9:27p 10:27p 11:27p 12:35a\n",
|
||||
" Burlingame 9:00a 10:31a 11:31a 12:31p 1:31p 2:31p 3:31p 4:31p 5:31p 6:31p 7:31p 8:31p 9:31p 10:31p 11:31p 12:38a\n",
|
||||
" San Mateo 9:04a 10:34a 11:34a 12:34p 1:34p 2:34p 3:34p 4:34p 5:34p 6:34p 7:34p 8:34p 9:34p 10:34p 11:34p 12:41a\n",
|
||||
" Hayward Park 9:07a 10:37a 11:37a 12:37p 1:37p 2:37p 3:37p 4:37p 5:37p 6:37p 7:37p 8:37p 9:37p 10:37p 11:37p 12:45a\n",
|
||||
" Hillsdale 9:10a 10:41a 11:41a 12:41p 1:41p 2:41p 3:41p 4:41p 5:41p 6:41p 7:41p 8:41p 9:41p 10:41p 11:41p 12:48a\n",
|
||||
" Belmont 9:14a 10:44a 11:44a 12:44p 1:44p 2:44p 3:44p 4:44p 5:44p 6:44p 7:44p 8:44p 9:44p 10:44p 11:44p 12:52a\n",
|
||||
" San Carlos 9:17a 10:48a 11:48a 12:48p 1:48p 2:48p 3:48p 4:48p 5:48p 6:48p 7:48p 8:48p 9:48p 10:48p 11:48p 12:55a\n",
|
||||
" Redwood City 9:21a 10:52a 11:52a 12:52p 1:52p 2:52p 3:52p 4:52p 5:52p 6:52p 7:52p 8:52p 9:52p 10:52p 11:52p 12:59a\n",
|
||||
" Menlo Park 9:28a 10:58a 11:58a 12:58p 1:58p 2:58p 3:58p 4:58p 5:58p 6:58p 7:58p 8:58p 9:58p 10:58p 11:58p 1:05a\n",
|
||||
" Palo Alto 9:32a 11:02a 12:02p 1:02p 2:02p 3:02p 4:02p 5:02p 6:02p 7:02p 8:02p 9:02p 10:02p 11:02p 12:02a 1:09a\n",
|
||||
" California Avenue 9:36a 11:06a 12:06p 1:06p 2:06p 3:06p 4:06p 5:06p 6:06p 7:06p 8:06p 9:06p 10:06p 11:06p 12:06a 1:12a\n",
|
||||
" San Antonio 9:41a 11:11a 12:11p 1:11p 2:11p 3:11p 4:11p 5:11p 6:11p 7:11p 8:11p 9:11p 10:11p 11:11p 12:10a 1:17a\n",
|
||||
" Mountain View 9:45a 11:16a 12:16p 1:16p 2:16p 3:16p 4:16p 5:16p 6:16p 7:16p 8:16p 9:16p 10:16p 11:16p 12:15a 1:21a\n",
|
||||
" Sunnyvale 9:51a 11:21a 12:21p 1:21p 2:21p 3:21p 4:21p 5:21p 6:21p 7:21p 8:21p 9:21p 10:21p 11:21p 12:20a 1:26a\n",
|
||||
" Lawrence 9:55a 11:26a 12:26p 1:26p 2:26p 3:26p 4:26p 5:26p 6:26p 7:26p 8:26p 9:26p 10:26p 11:26p 12:25a 1:31a\n",
|
||||
" Santa Clara 10:01a 11:32a 12:32p 1:32p 2:32p 3:32p 4:32p 5:32p 6:32p 7:32p 8:32p 9:32p 10:32p 11:32p 12:31a 1:37a\n",
|
||||
" San Jose Diridon 10:10a 11:40a 12:40p 1:38p 2:40p 3:38p 4:40p 5:38p 6:40p 7:38p 8:40p 9:38p 10:40p 11:38p 12:39a 1:44a\n",
|
||||
" Tamien 10:15a 11:45a 12:45p 2:45p 4:45p 6:45p 8:45p 10:45p 12:44a 1:49a\n",
|
||||
" EFFECTIVE September 12, 2022 Timetable subject to change without notice.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(docs[0].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8f5064d4-3e33-4f67-9b2e-46787161538f",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Initialize Query Engine\n",
|
||||
"\n",
|
||||
"We now initialize a query engine over this data. Here we use a baseline summary index, which doesn't do vector indexing/chunking and instead dumps the entire text into the prompt.\n",
|
||||
"\n",
|
||||
"We see that the LLM (gpt-4-turbo) is able to provide all the stops for train no 225 northbound."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b3e985b6-9d38-449f-9cf9-aae166824eed",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SummaryIndex\n",
|
||||
"from llama_index.llms.openai import OpenAI\n",
|
||||
"\n",
|
||||
"llm = OpenAI(model=\"gpt-4o\")\n",
|
||||
"index = SummaryIndex.from_documents(docs)\n",
|
||||
"query_engine = index.as_query_engine(llm=llm)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "66eb0976-2cd6-4b14-9083-124baae9ed5d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = query_engine.query(\n",
|
||||
" \"What are the stops (and times) for train no 237 northbound?\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7dc6f275-07f4-429e-9335-f50982fe974c",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The stops and times for train no. 237 northbound are as follows:\n",
|
||||
"\n",
|
||||
"- San Jose Diridon: 12:12 PM\n",
|
||||
"- Santa Clara: 12:18 PM\n",
|
||||
"- Lawrence: 12:24 PM\n",
|
||||
"- Sunnyvale: 12:28 PM\n",
|
||||
"- Mountain View: 12:34 PM\n",
|
||||
"- San Antonio: 12:37 PM\n",
|
||||
"- California Ave: 12:42 PM\n",
|
||||
"- Palo Alto: 12:46 PM\n",
|
||||
"- Menlo Park: 12:50 PM\n",
|
||||
"- Redwood City: 12:56 PM\n",
|
||||
"- San Carlos: 1:01 PM\n",
|
||||
"- Belmont: 1:04 PM\n",
|
||||
"- Hillsdale: 1:08 PM\n",
|
||||
"- Hayward Park: 1:11 PM\n",
|
||||
"- San Mateo: 1:15 PM\n",
|
||||
"- Burlingame: 1:19 PM\n",
|
||||
"- Broadway: 1:22 PM\n",
|
||||
"- Millbrae: 1:26 PM\n",
|
||||
"- San Bruno: 1:30 PM\n",
|
||||
"- S. San Francisco: 1:34 PM\n",
|
||||
"- Bayshore: 1:41 PM\n",
|
||||
"- 22nd Street: 1:46 PM\n",
|
||||
"- San Francisco: 1:52 PM\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "229c4cb0-cf94-4a9f-bc7c-590388f50c1f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = query_engine.query(\n",
|
||||
" \"What are all the trains (and times) that end at Tamien going Southbound?\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6cf9fce0-5067-48f6-a7ef-62aa9e2edc3d",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"It gets most of the answers correct (to be fair it misses two trains)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "51cf03ff-7728-4815-ab72-3bf54fc4a2c0",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The trains that end at Tamien going Southbound are:\n",
|
||||
"\n",
|
||||
"- Train 224 at 10:15a\n",
|
||||
"- Train 228 at 11:45a\n",
|
||||
"- Train 240 at 2:45p\n",
|
||||
"- Train 248 at 4:45p\n",
|
||||
"- Train 256 at 6:45p\n",
|
||||
"- Train 264 at 8:45p\n",
|
||||
"- Train 272 at 10:45p\n",
|
||||
"- Train 284 at 1:49a\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e51e7feb-b74f-4101-8963-933ac7ec9763",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Try Baseline\n",
|
||||
"\n",
|
||||
"In contrast, we try a baseline approach with the default PDF reader (PyPDF) in `SimpleDirectoryReader`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "364e5155-cc75-4302-a754-9444ae28e6b1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SimpleDirectoryReader\n",
|
||||
"from llama_index.core import SummaryIndex\n",
|
||||
"from llama_index.llms.openai import OpenAI\n",
|
||||
"\n",
|
||||
"llm = OpenAI(model=\"gpt-4o\")\n",
|
||||
"input_file = \"caltrain_schedule_weekend.pdf\"\n",
|
||||
"reader = SimpleDirectoryReader(input_files=[input_file])\n",
|
||||
"base_docs = reader.load_data()\n",
|
||||
"index = SummaryIndex.from_documents(base_docs)\n",
|
||||
"base_query_engine = index.as_query_engine(llm=llm)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "a4011389-2d27-4a1a-bf8d-7309da28ab15",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Southbound – WEEKEND SERVICE to SAN JOSE\n",
|
||||
"Train No. 224 228 232 236 240 244 248 252 256 260 264 268 272 276 280 284\n",
|
||||
"Service Types L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2\n",
|
||||
"San Francisco 8:28a 9:58a 10:58a 11:58a 12:58p 1:58p 2:58p 3:58p 4:58p 5:58p 6:58p 7:58p 8:58p 9:58p 10:58p 12:05a\n",
|
||||
"22nd Street 8:33a 10:03a 11:03a 12:03p 1:03p 2:03p 3:03p 4:03p 5:03p 6:03p 7:03p 8:03p 9:03p 10:03p 11:03p 12:10a\n",
|
||||
"Bayshore 8:38a 10:08a 11:08a 12:08p 1:08p 2:08p 3:08p 4:08p 5:08p 6:08p 7:08p 8:08p 9:08p 10:08p 11:08p 12:15a\n",
|
||||
"S. San Francisco 8:45a 10:15a 11:15a 12:15p 1:15p 2:15p 3:15p 4:15p 5:15p 6:15p 7:15p 8:15p 9:15p 10:15p 11:15p 12:22a\n",
|
||||
"San Bruno 8:49a 10:19a 11:19a 12:19p 1:19p 2:19p 3:19p 4:19p 5:19p 6:19p 7:19p 8:19p 9:19p 10:19p 11:19p 12:26a\n",
|
||||
"Millbrae 8:53a 10:24a 11:24a 12:24p 1:24p 2:24p 3:24p 4:24p 5:24p 6:24p 7:24p 8:24p 9:24p 10:24p 11:24p 12:31a\n",
|
||||
"Broadway 8:57a 10:27a 11:27a 12:27p 1:27p 2:27p 3:27p 4:27p 5:27p 6:27p 7:27p 8:27p 9:27p 10:27p 11:27p 12:35a\n",
|
||||
"Burlingame 9:00a 10:31a 11:31a 12:31p 1:31p 2:31p 3:31p 4:31p 5:31p 6:31p 7:31p 8:31p 9:31p 10:31p 11:31p 12:38a\n",
|
||||
"San Mateo 9:04a 10:34a 11:34a 12:34p 1:34p 2:34p 3:34p 4:34p 5:34p 6:34p 7:34p 8:34p 9:34p 10:34p 11:34p 12:41a\n",
|
||||
"Hayward Park 9:07a 10:37a 11:37a 12:37p 1:37p 2:37p 3:37p 4:37p 5:37p 6:37p 7:37p 8:37p 9:37p 10:37p 11:37p 12:45a\n",
|
||||
"Hillsdale 9:10a 10:41a 11:41a 12:41p 1:41p 2:41p 3:41p 4:41p 5:41p 6:41p 7:41p 8:41p 9:41p 10:41p 11:41p 12:48a\n",
|
||||
"Belmont 9:14a 10:44a 11:44a 12:44p 1:44p 2:44p 3:44p 4:44p 5:44p 6:44p 7:44p 8:44p 9:44p 10:44p 11:44p 12:52a\n",
|
||||
"San Carlos 9:17a 10:48a 11:48a 12:48p 1:48p 2:48p 3:48p 4:48p 5:48p 6:48p 7:48p 8:48p 9:48p 10:48p 11:48p 12:55a\n",
|
||||
"Redwood City 9:21a 10:52a 11:52a 12:52p 1:52p 2:52p 3:52p 4:52p 5:52p 6:52p 7:52p 8:52p 9:52p 10:52p 11:52p 12:59a\n",
|
||||
"Menlo Park 9:28a 10:58a 11:58a 12:58p 1:58p 2:58p 3:58p 4:58p 5:58p 6:58p 7:58p 8:58p 9:58p 10:58p 11:58p 1:05a\n",
|
||||
"Palo Alto 9:32a 11:02a 12:02p 1:02p 2:02p 3:02p 4:02p 5:02p 6:02p 7:02p 8:02p 9:02p 10:02p 11:02p 12:02a 1:09a\n",
|
||||
"California Avenue 9:36a 11:06a 12:06p 1:06p 2:06p 3:06p 4:06p 5:06p 6:06p 7:06p 8:06p 9:06p 10:06p 11:06p 12:06a 1:12a\n",
|
||||
"San Antonio 9:41a 11:11a 12:11p 1:11p 2:11p 3:11p 4:11p 5:11p 6:11p 7:11p 8:11p 9:11p 10:11p 11:11p 12:10a 1:17a\n",
|
||||
"Mountain View 9:45a 11:16a 12:16p 1:16p 2:16p 3:16p 4:16p 5:16p 6:16p 7:16p 8:16p 9:16p 10:16p 11:16p 12:15a 1:21a\n",
|
||||
"Sunnyvale 9:51a 11:21a 12:21p 1:21p 2:21p 3:21p 4:21p 5:21p 6:21p 7:21p 8:21p 9:21p 10:21p 11:21p 12:20a 1:26a\n",
|
||||
"Lawrence 9:55a 11:26a 12:26p 1:26p 2:26p 3:26p 4:26p 5:26p 6:26p 7:26p 8:26p 9:26p 10:26p 11:26p 12:25a 1:31a\n",
|
||||
"Santa Clara 10:01a 11:32a 12:32p 1:32p 2:32p 3:32p 4:32p 5:32p 6:32p 7:32p 8:32p 9:32p 10:32p 11:32p 12:31a 1:37a\n",
|
||||
"San Jose Diridon 10:10a 11:40a 12:40p 1:38p 2:40p 3:38p 4:40p 5:38p 6:40p 7:38p 8:40p 9:38p 10:40p 11:38p 12:39a 1:44a\n",
|
||||
"Tamien 10:15a 11:45a 12:45p 2:45p 4:45p 6:45p 8:45p 10:45p 12:44a 1:49aPrinter-Friendly Caltrain Schedule\n",
|
||||
"Northbound – WEEKEND SERVICE to SAN FRANCISCO\n",
|
||||
"Train No. 221 225 229 233 237 241 245 249 253 257 261 265 269 273 *277 *281\n",
|
||||
"Service Types L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2 L2\n",
|
||||
"Tamien 7:12a 9:05a 10:05a 11:05a 1:05p 3:05p 5:05p 7:05p 9:05p 11:05p\n",
|
||||
"San Jose Diridon 7:19a 9:12a 10:12a 11:12a 12:12p 1:12p 2:12p 3:12p 4:12p 5:12p 6:12p 7:12p 8:12p 9:12p 10:19p 11:12p\n",
|
||||
"Santa Clara 7:25a 9:18a 10:18a 11:18a 12:18p 1:18p 2:18p 3:18p 4:18p 5:18p 6:18p 7:18p 8:18p 9:18p 10:25p 11:18p\n",
|
||||
"Lawrence 7:31a 9:24a 10:24a 11:24a 12:24p 1:24p 2:24p 3:24p 4:24p 5:24p 6:24p 7:24p 8:24p 9:24p 10:31p 11:24p\n",
|
||||
"Sunnyvale 7:35a 9:28a 10:28a 11:28a 12:28p 1:28p 2:28p 3:28p 4:28p 5:28p 6:28p 7:28p 8:28p 9:28p 10:35p 11:28p\n",
|
||||
"Mountain View 7:40a 9:34a 10:34a 11:34a 12:34p 1:34p 2:34p 3:34p 4:34p 5:34p 6:34p 7:34p 8:34p 9:34p 10:40p 11:34p\n",
|
||||
"San Antonio 7:43a 9:37a 10:37a 11:37a 12:37p 1:37p 2:37p 3:37p 4:37p 5:37p 6:37p 7:37p 8:37p 9:37p 10:44p 11:37p\n",
|
||||
"California Ave 7:48a 9:42a 10:42a 11:42a 12:42p 1:42p 2:42p 3:42p 4:42p 5:42p 6:42p 7:42p 8:42p 9:42p 10:48p 11:42p\n",
|
||||
"Palo Alto 7:52a 9:46a 10:46a 11:46a 12:46p 1:46p 2:46p 3:46p 4:46p 5:46p 6:46p 7:46p 8:46p 9:46p 10:53p 11:46p\n",
|
||||
"Menlo Park 7:55a 9:50a 10:50a 11:50a 12:50p 1:50p 2:50p 3:50p 4:50p 5:50p 6:50p 7:50p 8:50p 9:50p 10:56p 11:50p\n",
|
||||
"Redwood City 8:01a 9:56a 10:56a 11:56a 12:56p 1:56p 2:56p 3:56p 4:56p 5:56p 6:56p 7:56p 8:56p 9:56p 11:02p 11:56p\n",
|
||||
"San Carlos 8:05a 10:01a 11:01a 12:01p 1:01p 2:01p 3:01p 4:01p 5:01p 6:01p 7:01p 8:01p 9:01p 10:01p 11:07p 12:01a\n",
|
||||
"Belmont 8:09a 10:04a 11:04a 12:04p 1:04p 2:04p 3:04p 4:04p 5:04p 6:04p 7:04p 8:04p 9:04p 10:04p 11:10p 12:04a\n",
|
||||
"Hillsdale 8:12a 10:08a 11:08a 12:08p 1:08p 2:08p 3:08p 4:08p 5:08p 6:08p 7:08p 8:08p 9:08p 10:08p 11:14p 12:08a\n",
|
||||
"Hayward Park 8:15a 10:11a 11:11a 12:11p 1:11p 2:11p 3:11p 4:11p 5:11p 6:11p 7:11p 8:11p 9:11p 10:11p 11:17p 12:11a\n",
|
||||
"San Mateo 8:19a 10:15a 11:15a 12:15p 1:15p 2:15p 3:15p 4:15p 5:15p 6:15p 7:15p 8:15p 9:15p 10:15p 11:21p 12:15a\n",
|
||||
"Burlingame 8:22a 10:19a 11:19a 12:19p 1:19p 2:19p 3:19p 4:19p 5:19p 6:19p 7:19p 8:19p 9:19p 10:19p 11:25p 12:19a\n",
|
||||
"Broadway 8:25a 10:22a 11:22a 12:22p 1:22p 2:22p 3:22p 4:22p 5:22p 6:22p 7:22p 8:22p 9:22p 10:22p 11:28p 12:22a\n",
|
||||
"Millbrae 8:29a 10:26a 11:26a 12:26p 1:26p 2:26p 3:26p 4:26p 5:26p 6:26p 7:26p 8:26p 9:26p 10:26p 11:32p 12:26a\n",
|
||||
"San Bruno 8:34a 10:30a 11:30a 12:30p 1:30p 2:30p 3:30p 4:30p 5:30p 6:30p 7:30p 8:30p 9:30p 10:30p 11:37p 12:30a\n",
|
||||
"S. San Francisco 8:38a 10:34a 11:34a 12:34p 1:34p 2:34p 3:34p 4:34p 5:34p 6:34p 7:34p 8:34p 9:34p 10:34p 11:41p 12:34a\n",
|
||||
"Bayshore 8:44a 10:41a 11:41a 12:41p 1:41p 2:41p 3:41p 4:41p 5:41p 6:41p 7:41p 8:41p 9:41p 10:41p 11:47p 12:41a\n",
|
||||
"22nd Street 8:50a 10:46a 11:46a 12:46p 1:46p 2:46p 3:46p 4:46p 5:46p 6:46p 7:46p 8:46p 9:46p 10:46p 11:53p 12:46a\n",
|
||||
"San Francisco 8:56a 10:52a 11:53a 12:53p 1:52p 2:52p 3:52p 4:52p 5:52p 6:52p 7:52p 8:52p 9:52p 10:52p 11:59p 12:52aZONE 2 ZONE 3 ZONE 4 ZONE 4 ZONE 3 ZONE 2 ZONE 1 ZONE 12XX Local\n",
|
||||
"2XX Local\n",
|
||||
"EFFECTIVE September 12, 2022 Timetable subject to change without notice. *On SAP Center event days, Train 277 or Train 281departure from San Jose Diridon station may be delayed and will depart no later than 10:30p or 11:30p respectively.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(base_docs[0].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "42203c70-7ca7-4200-bf47-6282eefca3bf",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"base_response = base_query_engine.query(\n",
|
||||
" \"What are the stops (and times) for train no 237 northbound?\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "06aa47b6-0f31-4b2d-90f0-bf6c74befd38",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Train No. 237 northbound stops at the following stations and times:\n",
|
||||
"\n",
|
||||
"- Tamien: 1:05p\n",
|
||||
"- San Jose Diridon: 1:12p\n",
|
||||
"- Santa Clara: 1:18p\n",
|
||||
"- Lawrence: 1:24p\n",
|
||||
"- Sunnyvale: 1:28p\n",
|
||||
"- Mountain View: 1:34p\n",
|
||||
"- San Antonio: 1:37p\n",
|
||||
"- California Ave: 1:42p\n",
|
||||
"- Palo Alto: 1:46p\n",
|
||||
"- Menlo Park: 1:50p\n",
|
||||
"- Redwood City: 1:56p\n",
|
||||
"- San Carlos: 2:01p\n",
|
||||
"- Belmont: 2:04p\n",
|
||||
"- Hillsdale: 2:08p\n",
|
||||
"- Hayward Park: 2:11p\n",
|
||||
"- San Mateo: 2:15p\n",
|
||||
"- Burlingame: 2:19p\n",
|
||||
"- Broadway: 2:22p\n",
|
||||
"- Millbrae: 2:26p\n",
|
||||
"- San Bruno: 2:30p\n",
|
||||
"- S. San Francisco: 2:34p\n",
|
||||
"- Bayshore: 2:41p\n",
|
||||
"- 22nd Street: 2:46p\n",
|
||||
"- San Francisco: 2:52p\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(base_response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "4f3c1de7-3351-4cd8-991c-34a777952194",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"base_response = base_query_engine.query(\n",
|
||||
" \"What are all the trains (and times) that end at Tamien going Southbound?\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "513b1007-7508-4fb1-836c-de9353433a67",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Note that the trains don't line up with the times!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "108edb92-76af-406b-a139-8b9e7c6528f2",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The trains that end at Tamien going Southbound are:\n",
|
||||
"\n",
|
||||
"- Train 224 at 10:15a\n",
|
||||
"- Train 228 at 11:45a\n",
|
||||
"- Train 240 at 2:45p\n",
|
||||
"- Train 252 at 4:45p\n",
|
||||
"- Train 264 at 6:45p\n",
|
||||
"- Train 276 at 8:45p\n",
|
||||
"- Train 284 at 10:45p\n",
|
||||
"- Train 284 at 12:44a\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(base_response))"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama_parse",
|
||||
"language": "python",
|
||||
"name": "llama_parse"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
Binary file not shown.
+476
-228
File diff suppressed because one or more lines are too long
@@ -17,13 +17,13 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install llama-index\n",
|
||||
"!pip install llama-index-core==0.10.6.post1\n",
|
||||
"!pip install llama-index-embeddings-openai\n",
|
||||
"!pip install llama-index-postprocessor-flag-embedding-reranker\n",
|
||||
"!pip install git+https://github.com/FlagOpen/FlagEmbedding.git\n",
|
||||
"!pip install llama-parse\n",
|
||||
"!pip install llama-index-vector-stores-astra-db"
|
||||
"%pip install llama-index\n",
|
||||
"%pip install llama-index-core==0.10.6.post1\n",
|
||||
"%pip install llama-index-embeddings-openai\n",
|
||||
"%pip install llama-index-postprocessor-flag-embedding-reranker\n",
|
||||
"%pip install git+https://github.com/FlagOpen/FlagEmbedding.git\n",
|
||||
"%pip install llama-parse\n",
|
||||
"%pip install llama-index-vector-stores-astra-db"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -32,7 +32,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_march_2022.pdf' -O './uber_10q_march_2022.pdf'"
|
||||
"!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/10q/uber_10q_march_2022.pdf' -O './uber_10q_march_2022.pdf'"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -44,15 +44,17 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# llama-parse is async-first, running the async code in a notebook requires the use of nest_asyncio\n",
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# API access to llama-cloud\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-\"\n",
|
||||
"\n",
|
||||
@@ -66,7 +68,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -75,7 +77,7 @@
|
||||
"from llama_index.core import VectorStoreIndex\n",
|
||||
"from llama_index.core import Settings\n",
|
||||
"\n",
|
||||
"embed_model=OpenAIEmbedding(model=\"text-embedding-3-small\")\n",
|
||||
"embed_model = OpenAIEmbedding(model=\"text-embedding-3-small\")\n",
|
||||
"llm = OpenAI(model=\"gpt-3.5-turbo-0125\")\n",
|
||||
"\n",
|
||||
"Settings.llm = llm\n",
|
||||
@@ -93,7 +95,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -107,12 +109,12 @@
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"documents = LlamaParse(result_type=\"markdown\").load_data('./uber_10q_march_2022.pdf')"
|
||||
"documents = LlamaParse(result_type=\"markdown\").load_data(\"./uber_10q_march_2022.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -168,7 +170,7 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(documents[0].text[:1000] + '...')"
|
||||
"print(documents[0].text[:1000] + \"...\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -180,29 +182,27 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.vector_stores.astra_db import AstraDBVectorStore\n",
|
||||
"\n",
|
||||
"# define two storage classes representing two collections (to compare advanced approach vs. baseline) \n",
|
||||
"# define two storage classes representing two collections (to compare advanced approach vs. baseline)\n",
|
||||
"\n",
|
||||
"astra_db_store_advanced = AstraDBVectorStore(\n",
|
||||
" token=ASTRA_TOKEN,\n",
|
||||
" api_endpoint=ASTRA_API_ENDPOINT,\n",
|
||||
" namespace=ASTRA_NAMESPACE,\n",
|
||||
" collection_name=\"astra_v_table_llamaparse_advanced\",\n",
|
||||
" embedding_dimension=1536\n",
|
||||
" embedding_dimension=1536,\n",
|
||||
")\n",
|
||||
"astra_db_store_base = AstraDBVectorStore(\n",
|
||||
" token=ASTRA_TOKEN,\n",
|
||||
" api_endpoint=ASTRA_API_ENDPOINT,\n",
|
||||
" namespace=ASTRA_NAMESPACE,\n",
|
||||
" collection_name=\"astra_v_table_llamaparse_base\",\n",
|
||||
" embedding_dimension=1536\n",
|
||||
" embedding_dimension=1536,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
@@ -219,13 +219,15 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core.node_parser import MarkdownElementNodeParser\n",
|
||||
"\n",
|
||||
"node_parser = MarkdownElementNodeParser(llm=OpenAI(model=\"gpt-3.5-turbo-0125\"), num_workers=8)"
|
||||
"node_parser = MarkdownElementNodeParser(\n",
|
||||
" llm=OpenAI(model=\"gpt-3.5-turbo-0125\"), num_workers=8\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -239,7 +241,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -248,17 +250,23 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import StorageContext\n",
|
||||
"\n",
|
||||
"storage_context_advanced = StorageContext.from_defaults(vector_store=astra_db_store_advanced)\n",
|
||||
"storage_context_advanced = StorageContext.from_defaults(\n",
|
||||
" vector_store=astra_db_store_advanced\n",
|
||||
")\n",
|
||||
"storage_context_base = StorageContext.from_defaults(vector_store=astra_db_store_base)\n",
|
||||
"\n",
|
||||
"recursive_index = VectorStoreIndex(nodes=base_nodes+objects, storage_context=storage_context_advanced)\n",
|
||||
"raw_index = VectorStoreIndex.from_documents(documents, storage_context=storage_context_base)"
|
||||
"recursive_index = VectorStoreIndex(\n",
|
||||
" nodes=base_nodes + objects, storage_context=storage_context_advanced\n",
|
||||
")\n",
|
||||
"raw_index = VectorStoreIndex.from_documents(\n",
|
||||
" documents, storage_context=storage_context_base\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -267,7 +275,9 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.postprocessor.flag_embedding_reranker import FlagEmbeddingReranker\n",
|
||||
"from llama_index.postprocessor.flag_embedding_reranker import (\n",
|
||||
" FlagEmbeddingReranker,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"reranker = FlagEmbeddingReranker(\n",
|
||||
" top_n=5,\n",
|
||||
@@ -275,12 +285,12 @@
|
||||
")\n",
|
||||
"\n",
|
||||
"recursive_query_engine = recursive_index.as_query_engine(\n",
|
||||
" similarity_top_k=15, \n",
|
||||
" node_postprocessors=[reranker], \n",
|
||||
" verbose=True\n",
|
||||
" similarity_top_k=15, node_postprocessors=[reranker], verbose=True\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"raw_query_engine = raw_index.as_query_engine(similarity_top_k=15, node_postprocessors=[reranker])"
|
||||
"raw_query_engine = raw_index.as_query_engine(\n",
|
||||
" similarity_top_k=15, node_postprocessors=[reranker]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -300,7 +310,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -341,7 +351,7 @@
|
||||
"\n",
|
||||
"response_2 = recursive_query_engine.query(query)\n",
|
||||
"print(\"\\n***********New LlamaParse+ Recursive Retriever Query Engine***********\")\n",
|
||||
"print(response_2)\n"
|
||||
"print(response_2)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -358,7 +368,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 13,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -422,7 +432,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -478,7 +488,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -554,8 +564,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.8"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -11,7 +11,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -38,7 +38,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -47,7 +47,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -88,7 +88,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -128,10 +128,8 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.5"
|
||||
},
|
||||
"orig_nbformat": 4
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
|
||||
+22
-23
@@ -23,12 +23,12 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# First, install the required dependencies\n",
|
||||
"!pip install --quiet llama-index llama-parse llama-index-vector-stores-astra-db llama-index-llms-openai"
|
||||
"%pip install --quiet llama-index llama-parse llama-index-vector-stores-astra-db llama-index-llms-openai"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -40,7 +40,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -53,7 +53,9 @@
|
||||
"llama_cloud_api_key = getpass(\"Enter your Llama Index Cloud API Key: \")\n",
|
||||
"api_endpoint = input(\"Enter your Astra DB API Endpoint: \")\n",
|
||||
"token = getpass(\"Enter your Astra DB Token: \")\n",
|
||||
"namespace = input(\"Enter your Astra DB namespace (optional, must exist on Astra): \") or None\n",
|
||||
"namespace = (\n",
|
||||
" input(\"Enter your Astra DB namespace (optional, must exist on Astra): \") or None\n",
|
||||
")\n",
|
||||
"openai_api_key = getpass(\"Enter your OpenAI API Key: \")\n",
|
||||
"\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = llama_cloud_api_key\n",
|
||||
@@ -62,7 +64,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -81,7 +83,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -94,7 +96,7 @@
|
||||
],
|
||||
"source": [
|
||||
"# Grab a PDF from Arxiv for indexing\n",
|
||||
"import requests \n",
|
||||
"import requests\n",
|
||||
"\n",
|
||||
"# The URL of the file you want to download\n",
|
||||
"url = \"https://arxiv.org/pdf/1706.03762.pdf\"\n",
|
||||
@@ -116,7 +118,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -135,7 +137,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -144,7 +146,7 @@
|
||||
"'rmer - model architecture.\\nThe Transformer follows this overall architecture using stacked self-attention and point-wise, fully\\nconnected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\\nrespectively.\\n3.1 Encoder and Decoder Stacks\\nEncoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two\\nsub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-\\nwise fully connected feed-forward network. We employ a residual connection [11] around each of\\nthe two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is\\nLayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\\nitself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\\nlayers, produce outputs of dimension dmodel = 512.\\nDecoder: The decoder is also composed of a stack of N = 6 identical layers. In addition '"
|
||||
]
|
||||
},
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
@@ -163,7 +165,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -174,16 +176,14 @@
|
||||
" api_endpoint=api_endpoint,\n",
|
||||
" namespace=namespace,\n",
|
||||
" collection_name=\"astra_v_table_llamaparse\",\n",
|
||||
" embedding_dimension=1536\n",
|
||||
" embedding_dimension=1536,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core.node_parser import SimpleNodeParser\n",
|
||||
@@ -195,7 +195,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -220,7 +220,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -252,7 +252,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -261,7 +261,7 @@
|
||||
"'We used beam search as described in the previous section, but no\\ncheckpoint averaging. We present these results in Table 3.\\nIn Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions,\\nkeeping the amount of computation constant, as described in Section 3.2.2. While single-head\\nattention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.\\nIn Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This\\nsuggests that determining compatibility is not easy and that a more sophisticated compatibility\\nfunction than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected,\\nbigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our\\nsinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical\\nresults to the base model.\\n6.3 English Constituency Parsing\\nTo evaluate if the Transformer can generalize to other tasks we performed experiments on English\\nconstituency parsing. This task presents specific challenges: the output is subject to strong structural\\nconstraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence\\nmodels have not been able to attain state-of-the-art results in small-data regimes [37].\\nWe trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the\\nPenn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting,\\nusing the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences\\n[37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens\\nfor the semi-supervised setting.\\nWe performed only a small number of experiments to select the dropout, both attention and residual\\n(section 5.4), learning rates and beam size on the Section 22 development set, all other parameters\\nremained unchanged from the English-to-German base translation model. During inference, we\\n 9\\n---\\nTable 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23\\nof WSJ)\\n Parser Training WSJ 23 F1\\n Vinyals & Kaiser el al. (2014) [37] WSJ only, discriminative 88.3\\n Petrov et al. (2006) [29] WSJ only, discriminative 90.4\\n Zhu et al. (2013) [40] WSJ only, discriminative 90.4\\n Dyer et al. (2016) [8] WSJ only, discriminative 91.7\\n Transformer (4 layers) WSJ only, discriminative 91.3\\n Zhu et al. (2013) [40] semi-supervised 91.3\\n Huang & Harper (2009) [14] semi-supervised 91.3\\n McClosky et al. (2006) [26] semi-supervised 92.1\\n Vinyals & Kaiser el al. (2014) [37] semi-supervised 92.1\\n Transformer (4 layers) semi-supervised 92.7\\n Luong et al. (2015) [23] multi-task 93.0\\n Dyer et al. (2016) [8] generative 93.3\\nincreased the maximum output length to input length + 300. We used a beam size of 21 and α = 0.3\\nfor both WSJ only and the semi-supervised setting.\\nOur results in Table 4 show that despite the lack of task-specific tuning our model performs sur-\\nprisingly well, yielding better results than all previously reported models with the exception of the\\nRecurrent Neural Network Grammar [8].\\nIn contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley-\\nParser [29] even when training only on the WSJ training set of 40K sentences.\\n7 Conclusion\\nIn this work, we presented the Transformer, the first sequence transduction model based entirely on\\nattention, replacing the recurrent layers most commonly used in encoder-decoder architectures with\\nmulti-headed self-attention.\\nFor translation tasks, the Transformer can be trained significantly faster than architectures based\\non recurrent or convolutional layers.'"
|
||||
]
|
||||
},
|
||||
"execution_count": 12,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
@@ -287,8 +287,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.6"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
+10
-18
@@ -13,12 +13,12 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install llama-index llama-parse"
|
||||
"%pip install llama-index llama-parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -55,12 +55,13 @@
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-...\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -79,7 +80,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -107,7 +108,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -126,7 +127,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -157,13 +158,6 @@
|
||||
"source": [
|
||||
"print(documents[0].text[20000:21000] + \"...\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
@@ -181,10 +175,8 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.12"
|
||||
},
|
||||
"orig_nbformat": 4
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,531 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LlamaParse - Fast checking Insurance Contract for Coverage\n",
|
||||
"\n",
|
||||
"<a href=\"https://colab.research.google.com/github/run-llama/llama_parse/blob/main/examples/demo_insurance.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
|
||||
"\n",
|
||||
"In this notebook we will look at how LlamaParse can be used to extract structured coverage information from an insurance policy."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Installation of required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install llama-index llama-parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Download an insurance policy fron IRDAI\n",
|
||||
"\n",
|
||||
"The Insurance Regulatory and Development Authority of India (IRDAI) maintains a great resource: https://policyholder.gov.in/web/guest/non-life-insurance-products where all insurance policies available in India are publicly available for download! Let's download a complex health insurance policy as an example."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!wget \"https://policyholder.gov.in/documents/37343/931203/NBHTGBP22011V012223.pdf/c392bcc1-f6a8-cadd-ab84-495b3273d2c3?version=1.0&t=1669350459879&download=true\" -O \"./policy.pdf\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Initializing LlamaIndex and LlamaParse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# llama-parse is async-first, running the sync code in a notebook requires the use of nest_asyncio\n",
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-...\"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"sk-...\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.llms.openai import OpenAI\n",
|
||||
"from llama_index.embeddings.openai import OpenAIEmbedding\n",
|
||||
"from llama_index.core import VectorStoreIndex\n",
|
||||
"from llama_index.core import Settings\n",
|
||||
"\n",
|
||||
"# for the purpose of this example, we will use the small model embedding and gpt3.5\n",
|
||||
"embed_model = OpenAIEmbedding(model=\"text-embedding-3-small\")\n",
|
||||
"llm = OpenAI(model=\"gpt-3.5-turbo-0125\")\n",
|
||||
"\n",
|
||||
"Settings.llm = llm"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Vanilla Approach - Parse the Policy with LlamaParse into Markdown"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id b8946573-c911-4e00-8921-1bad1cda3d64\n",
|
||||
"......"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"documents = LlamaParse(result_type=\"markdown\").load_data(\"./policy.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"## Preamble\n",
|
||||
"\n",
|
||||
"This ‘Travel Infinity’ Policy is a contract of insurance between You and Us which is subject to payment of full premium in advance and the terms, conditions and exclusions of this Policy. Expense incurred outside the policy period will NOT be covered. Unutilized Sum Insured will expire at the end of the policy year. All applicable benefits, details and limits are mentioned in your Certificate of insurance. We will cover only allopathic treatments in this policy.\n",
|
||||
"\n",
|
||||
"## Defined Terms\n",
|
||||
"\n",
|
||||
"The terms listed below in this Section and used elsewhere in the Policy in Initial Capitals shall have the meaning set out against them in this Section.\n",
|
||||
"\n",
|
||||
"### Standard Definitions\n",
|
||||
"\n",
|
||||
"|2.1|Accident or Accidental|means sudden, unforeseen and involuntary event caused by external, visible and violent means.|\n",
|
||||
"|---|---|---|\n",
|
||||
"|2.2|Co-payment|means a cost sharing requirement under a health insurance policy that provides that the policyholder/insured will bear a specified percentage of the admissible claims a\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(documents[0].text[0:1000])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Markdown Element Node Parser\n",
|
||||
"Our markdown element node parser works well for parsing the markdown output of LlamaParse into a set of table and text nodes."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core.node_parser import MarkdownElementNodeParser\n",
|
||||
"\n",
|
||||
"node_parser = MarkdownElementNodeParser(\n",
|
||||
" llm=OpenAI(model=\"gpt-3.5-turbo-0125\"), num_workers=8\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"nodes = node_parser.get_nodes_from_documents(documents)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"base_nodes, objects = node_parser.get_nodes_and_objects(nodes)\n",
|
||||
"\n",
|
||||
"recursive_index = VectorStoreIndex(nodes=base_nodes + objects)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_engine = recursive_index.as_query_engine(similarity_top_k=25)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Querying the model for coverage"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"You are covered for the expenses incurred on any alternate travel booking under any mode of transport, up to the limit of the Sum Insured as mentioned in the Certificate of insurance, if the delay of the airlines was caused due to specific reasons outlined in the policy. The amount you are covered for will depend on the specific terms and conditions of your policy, including the maximum coverage limit specified in the Certificate of insurance.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"query_1 = \"My trip was delay and I paid 45, how much am I cover for?\"\n",
|
||||
"\n",
|
||||
"response_1 = query_engine.query(query_1)\n",
|
||||
"print(str(response_1))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The information is split across the document which leads to retrieval issues. Let's try some parsing instructions to improve our result."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id ec9e77c9-6ad9-4c9b-9efb-c9f659b0d481\n",
|
||||
"....."
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"documents_with_instruction = LlamaParse(\n",
|
||||
" result_type=\"markdown\",\n",
|
||||
" parsing_instruction=\"\"\"\n",
|
||||
"This document is an insurance policy.\n",
|
||||
"When a benefits/coverage/exlusion is describe in the document ammend to it add a text in the follwing benefits string format (where coverage could be an exclusion).\n",
|
||||
"\n",
|
||||
"For {nameofrisk} and in this condition {whenDoesThecoverageApply} the coverage is {coverageDescription}. \n",
|
||||
" \n",
|
||||
"If the document contain a benefits TABLE that describe coverage amounts, do not ouput it as a table, but instead as a list of benefits string.\n",
|
||||
" \n",
|
||||
"\"\"\",\n",
|
||||
").load_data(\"./policy.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Let see how the 2 parsing compare (change target page to explore)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"## Inpatient treatment\n",
|
||||
"\n",
|
||||
"Claim Form (filled and signed by pe Insured)\n",
|
||||
"Hospital Daily Cash\n",
|
||||
"Release of Medical information Form (filled and signed by pe Insured)\n",
|
||||
"Waiver of Deductible\n",
|
||||
"Original papological and diagnostic reports, discharge summary indoor case papers (if any) and prescriptions issued by pe treating Medical practitioner or Network Provider\n",
|
||||
"Optional Co-payment\n",
|
||||
"Adventure Sports Cover\n",
|
||||
"Home to Home Cover\n",
|
||||
"Passport and Visa copy wip Entry Stamp of Country of Visit and exit Stamp from India\n",
|
||||
"Extension to in-patient care\n",
|
||||
"Ambulance Charge\n",
|
||||
"FIR report of police (if applicable)\n",
|
||||
"\n",
|
||||
"## Out-patient treatment\n",
|
||||
"\n",
|
||||
"Cancer Screening & Mammographic Examination\n",
|
||||
"Original bills and receipts for:\n",
|
||||
"1. Charges paid towards Hospital accommodation, nursing facilities, and oper medical services rendered\n",
|
||||
"2. Fees paid to pe Medical Practitioner and for special nursing charges\n",
|
||||
"3. Charges incurred towards any and all test and / or examinations rendered in connection wip pe treatment\n",
|
||||
"4. Charges incurred towards medicines or drugs purchased from a registered pharmacy oper pan pe Network provider duly supported by pe prescriptions of pe Medical Practitioner attending to pe Insured Person\n",
|
||||
"5. Any oper document as required by pe Company to assist pe Claim\n",
|
||||
"\n",
|
||||
"## Medical evacuation\n",
|
||||
"\n",
|
||||
"Medical reports and transportation details issued by the evacuation agency, prescriptions and medical report by the attending Medical Practitioner furnishing the name of the Insured Person and details of treatment rendered along with the statement confirming the necessity of evacuation.\n",
|
||||
"\n",
|
||||
"Documentary proof for expenses incurred towards the Medical Evacuation.\n",
|
||||
"\n",
|
||||
"## Compassionate visit\n",
|
||||
"\n",
|
||||
"A certificate from the Medical Practitioner recommending the presence in the form of special assistance to be rendered by an additional member during the entire period of hospitalization. The certificate shall also specify the minimum period in which person is admitted in the hospital.\n",
|
||||
"\n",
|
||||
"Discharge summary of the Hospital furnishing details including the date of admission and date of discharge.\n",
|
||||
"\n",
|
||||
"Stamped boarding pass with invoice used for the travel by the Immediate Family Member.\n",
|
||||
"\n",
|
||||
"Copy passport of Immediate Family Member with entry and exit stamp.\n",
|
||||
"\n",
|
||||
"## Escort of Minor Child\n",
|
||||
"\n",
|
||||
"A certificate from the Medical Practitioner specifying the minimum period of Hospitalization.\n",
|
||||
"\n",
|
||||
"Discharge summary of the Hospital furnishing details including the date of admission and date of discharge.\n",
|
||||
"\n",
|
||||
"Stamped Boarding pass used for the return travel of the child to the Country of Residence.\n",
|
||||
"\n",
|
||||
"Stamped Boarding pass of the attendant from the Country of Residence to the place of hospitalization (if attendant is necessary).\n",
|
||||
"\n",
|
||||
"Copy of passport of the child with entry and exit stamp.\n",
|
||||
"\n",
|
||||
"## Upgradation to Business Class\n",
|
||||
"\n",
|
||||
"A certificate from the Medical Practitioner specifying the minimum period of Hospitalization.\n",
|
||||
"\n",
|
||||
"Discharge summary of the Hospital furnishing the details including the date of admission and date of discharge.\n",
|
||||
"\n",
|
||||
"Product Name: Travel infinity | Product UIN: NBHTGBP22011V012223\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"=========================================================\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Insurance Policy\n",
|
||||
"\n",
|
||||
"## Benefits:\n",
|
||||
"\n",
|
||||
"- For Inpatient treatment and in this condition when admitted to a hospital, the coverage is reimbursement for medical expenses incurred.\n",
|
||||
"- For Hospital Daily Cash and in this condition when hospitalized, the coverage is daily cash benefit.\n",
|
||||
"- For Waiver of Deductible and in this condition when a deductible is applicable, the coverage is waiver of the deductible amount.\n",
|
||||
"- For Optional Co-payment and in this condition when a co-payment is required, the coverage is optional co-payment.\n",
|
||||
"- For Adventure Sports Cover and in this condition when participating in adventure sports, the coverage is coverage for injuries related to adventure sports.\n",
|
||||
"- For Home to Home Cover and in this condition when requiring medical evacuation, the coverage is assistance for repatriation to home country.\n",
|
||||
"- For Extension to in-patient care and in this condition when extended hospital stay is necessary, the coverage is extension of coverage for in-patient care.\n",
|
||||
"- For Ambulance Charge and in this condition when ambulance services are utilized, the coverage is reimbursement for ambulance charges.\n",
|
||||
"- For Out-patient treatment and in this condition when receiving outpatient medical care, the coverage is reimbursement for outpatient medical expenses.\n",
|
||||
"- For Cancer Screening & Mammographic Examination and in this condition when undergoing cancer screening or mammographic examination, the coverage is coverage for these preventive services.\n",
|
||||
"- For New Born baby Cover and in this condition when a newborn is covered under the policy, the coverage is medical expenses coverage for the newborn.\n",
|
||||
"- For Maternity and in this condition when maternity services are required, the coverage is coverage for maternity expenses.\n",
|
||||
"- For Complete pre-existing disease cover and in this condition when seeking treatment for pre-existing conditions, the coverage is coverage for pre-existing conditions.\n",
|
||||
"- For Medical sum insured replenishment in case of hospitalization due to accident and in this condition when hospitalized due to an accident, the coverage is replenishment of the sum insured.\n",
|
||||
"- For Waiver of sublimit for insured above 60 years of age and in this condition when the insured is above 60 years of age, the coverage is waiver of sublimits.\n",
|
||||
"- For Psychiatric Counseling and in this condition when seeking psychiatric counseling, the coverage is coverage for psychiatric counseling services.\n",
|
||||
"- For Physiotherapy and in this condition when undergoing physiotherapy, the coverage is coverage for physiotherapy sessions.\n",
|
||||
"- For Terrorism cover and in this condition when affected by terrorism, the coverage is coverage for medical expenses related to terrorism incidents.\n",
|
||||
"- For Medical tele-consultation and in this condition when consulting a medical practitioner remotely, the coverage is coverage for tele-consultation services.\n",
|
||||
"- For Medical evacuation and in this condition when requiring medical evacuation, the coverage is coverage for medical evacuation services.\n",
|
||||
"- For Compassionate visit and in this condition when requiring a compassionate visit, the coverage is coverage for travel expenses for a family member to visit.\n",
|
||||
"- For Escort of Minor Child and in this condition when escorting a minor child for medical treatment, the coverage is coverage for escort services for the child.\n",
|
||||
"- For Upgradation to Business Class and in this condition when requiring upgradation to business class for medical travel, the coverage is coverage for upgradation to business class.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"target_page = 45\n",
|
||||
"pages_vanilla = documents[0].text.split(\"\\n---\\n\")\n",
|
||||
"pages_with_instructions = documents_with_instruction[0].text.split(\"\\n---\\n\")\n",
|
||||
"\n",
|
||||
"print(pages_vanilla[target_page])\n",
|
||||
"print(\"\\n\\n=========================================================\\n\\n\")\n",
|
||||
"print(pages_with_instructions[target_page])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"node_parser_instruction = MarkdownElementNodeParser(\n",
|
||||
" llm=OpenAI(model=\"gpt-3.5-turbo-0125\"), num_workers=8\n",
|
||||
")\n",
|
||||
"nodes_instruction = node_parser.get_nodes_from_documents(documents_with_instruction)\n",
|
||||
"(\n",
|
||||
" base_nodes_instruction,\n",
|
||||
" objects_instruction,\n",
|
||||
") = node_parser_instruction.get_nodes_and_objects(nodes_instruction)\n",
|
||||
"\n",
|
||||
"recursive_index_instruction = VectorStoreIndex(\n",
|
||||
" nodes=base_nodes_instruction + objects_instruction\n",
|
||||
")\n",
|
||||
"query_engine_instruction = recursive_index_instruction.as_query_engine(\n",
|
||||
" similarity_top_k=25\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Comparing Instruction-Augmented Parsing vs. Vanilla Parsing\n",
|
||||
"\n",
|
||||
"When we parse the document with natural language instructions to add context on insurance coverage, we are able to correctly answer a wide range of queries in our RAG pipeline. In contrast, a RAG pipeline built with the vanilla method is not able to answer these queries."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Vanilla:\n",
|
||||
"You are covered for the amount you paid due to the trip delay, up to the limit specified in the certificate of insurance.\n",
|
||||
"With instructions:\n",
|
||||
"For Trip Delay coverage, you are covered for a fixed benefit amount as mentioned in the certificate of insurance for every block of hours of delay.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"query_1 = \"My trip was delayed and I paid 45, how much am I covered for?\"\n",
|
||||
"\n",
|
||||
"response_1 = query_engine.query(query_1)\n",
|
||||
"print(\"Vanilla:\")\n",
|
||||
"print(response_1)\n",
|
||||
"\n",
|
||||
"print(\"With instructions:\")\n",
|
||||
"response_1_i = query_engine_instruction.query(query_1)\n",
|
||||
"print(response_1_i)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Looking at the policy it says in list I that one expense not covered is Baby food"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Vanilla:\n",
|
||||
"Baby food is not explicitly mentioned in the provided context information regarding insurance coverages and benefits.\n",
|
||||
"With instructions:\n",
|
||||
"Baby food is excluded from coverage according to the policy terms.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"query_2 = \"I just had a baby, is baby food covered?\"\n",
|
||||
"\n",
|
||||
"response_2 = query_engine.query(query_2)\n",
|
||||
"print(\"Vanilla:\")\n",
|
||||
"print(response_2)\n",
|
||||
"\n",
|
||||
"print(\"With instructions:\")\n",
|
||||
"response_2_i = query_engine_instruction.query(query_2)\n",
|
||||
"print(response_2_i)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Vanilla:\n",
|
||||
"Gauze used in your operation would typically be covered under the \"Emergency In-patient Medical Treatment\" or \"Emergency In-patient Medical Treatment with OPD\" benefits of the policy.\n",
|
||||
"With instructions:\n",
|
||||
"Gauze is not covered for use in your operation as it falls under the category of items that are excluded from coverage in the insurance policy.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"query_3 = \"How is gauze used in my operation covered?\"\n",
|
||||
"\n",
|
||||
"response_3 = query_engine.query(query_3)\n",
|
||||
"print(\"Vanilla:\")\n",
|
||||
"print(response_3)\n",
|
||||
"\n",
|
||||
"print(\"With instructions:\")\n",
|
||||
"response_3_i = query_engine_instruction.query(query_3)\n",
|
||||
"print(response_3_i)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama_parse",
|
||||
"language": "python",
|
||||
"name": "llama_parse"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
+40
-75
@@ -40,18 +40,18 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": null,
|
||||
"id": "0879301c-ff91-4431-941a-6c0ef7cd8fe2",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# llama-parse is async-first, running the async code in a notebook requires the use of nest_asyncio\n",
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# API access to llama-cloud\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-\"\n",
|
||||
"\n",
|
||||
@@ -63,9 +63,7 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "391e2d95-5569-4d73-9f16-5b59d7326f8d",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.llms.anthropic import Anthropic\n",
|
||||
@@ -75,11 +73,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": null,
|
||||
"id": "700f48e8-8b52-41f3-90f9-144d5fdd5c52",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import Settings\n",
|
||||
@@ -102,12 +98,10 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c39d408f-e885-4940-85c7-b09ca3bc7cb7",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_march_2022.pdf' -O './uber_10q_march_2022.pdf'"
|
||||
"!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/10q/uber_10q_march_2022.pdf' -O './uber_10q_march_2022.pdf'"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -122,11 +116,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"id": "9c9cd670-8229-4ad6-99a9-845bd82b7ec1",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -146,11 +138,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"id": "b26d21d1-05b5-4f49-b937-c13106a84015",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core.schema import TextNode\n",
|
||||
@@ -160,23 +150,16 @@
|
||||
"def get_text_nodes(json_list: List[dict]):\n",
|
||||
" text_nodes = []\n",
|
||||
" for idx, page in enumerate(json_list):\n",
|
||||
" text_node = TextNode(\n",
|
||||
" text=page[\"text\"],\n",
|
||||
" metadata={\n",
|
||||
" \"page\": page[\"page\"]\n",
|
||||
" }\n",
|
||||
" )\n",
|
||||
" text_node = TextNode(text=page[\"text\"], metadata={\"page\": page[\"page\"]})\n",
|
||||
" text_nodes.append(text_node)\n",
|
||||
" return text_nodes"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": null,
|
||||
"id": "364a3276-d2db-4aee-9bc6-617ffd726d25",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"text_nodes = get_text_nodes(json_list)"
|
||||
@@ -194,7 +177,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"execution_count": null,
|
||||
"id": "36012145-5521-4ddb-a53e-df9ebd1ca8dd",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
@@ -223,13 +206,10 @@
|
||||
" for image_dict in image_dicts:\n",
|
||||
" image_doc = ImageDocument(image_path=image_dict[\"path\"])\n",
|
||||
" response = anthropic_mm_llm.complete(\n",
|
||||
" prompt=\"Describe the images as an alternative text\",\n",
|
||||
" prompt=\"Describe the images as alt text\",\n",
|
||||
" image_documents=[image_doc],\n",
|
||||
" )\n",
|
||||
" text_node = TextNode(\n",
|
||||
" text=str(response),\n",
|
||||
" metadata={\"path\": image_dict[\"path\"]}\n",
|
||||
" )\n",
|
||||
" text_node = TextNode(text=str(response), metadata={\"path\": image_dict[\"path\"]})\n",
|
||||
" img_text_nodes.append(text_node)\n",
|
||||
" return img_text_nodes"
|
||||
]
|
||||
@@ -238,9 +218,7 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "38f25045-6102-4920-9cd0-42b0ae6c872f",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"image_text_nodes = get_image_text_nodes(json_objs)"
|
||||
@@ -248,11 +226,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 60,
|
||||
"execution_count": null,
|
||||
"id": "4683c97a-da06-408a-9fe9-7e3c0aceb77d",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
@@ -260,7 +236,7 @@
|
||||
"'The image shows a bar graph titled \"Monthly Active Platform Consumers (in millions)\". The graph displays data from Q2 2020 to Q1 2022 over 8 quarters. The number of monthly active platform consumers starts at 55 million in Q2 2020 and steadily increases each quarter, reaching 115 million by Q1 2022. The graph illustrates consistent quarter-over-quarter growth in this metric over the nearly 2 year time period shown.'"
|
||||
]
|
||||
},
|
||||
"execution_count": 60,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
@@ -281,7 +257,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 68,
|
||||
"execution_count": null,
|
||||
"id": "939aec6c-064a-4319-b2dc-70cc4a304c06",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -293,7 +269,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 69,
|
||||
"execution_count": null,
|
||||
"id": "529340d5-9319-4cdf-8ee1-bbd01ed00226",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -303,11 +279,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 71,
|
||||
"execution_count": null,
|
||||
"id": "81d7ff30-5a87-44da-880d-4b1f41434d90",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -320,18 +294,18 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# ask question over image! \n",
|
||||
"response = query_engine.query(\"What does the bar graph titled 'Monthly Active Platform Consumers' show?\") \n",
|
||||
"print(str(response)) "
|
||||
"# ask question over image!\n",
|
||||
"response = query_engine.query(\n",
|
||||
" \"What does the bar graph titled 'Monthly Active Platform Consumers' show?\"\n",
|
||||
")\n",
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 72,
|
||||
"execution_count": null,
|
||||
"id": "c4f14ad8-6bfd-49d9-b3d5-7215cf0e4ac1",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -360,25 +334,17 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# ask question over text! \n",
|
||||
"response = query_engine.query(\"What are the main risk factors for Uber?\") \n",
|
||||
"print(str(response)) "
|
||||
"# ask question over text!\n",
|
||||
"response = query_engine.query(\"What are the main risk factors for Uber?\")\n",
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "82ea880b-a0c7-410c-94c7-8fb3ac96c30c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama_parse",
|
||||
"display_name": "llama-parse-aNC435Vv-py3.10",
|
||||
"language": "python",
|
||||
"name": "llama_parse"
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
@@ -389,8 +355,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.8"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -21,16 +21,14 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install llama-index llama-parse"
|
||||
"%pip install llama-index llama-parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"id": "87322210-c21c-43d6-b459-2e8a828ac576",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# llama-parse is async-first, running the sync code in a notebook requires the use of nest_asyncio\n",
|
||||
@@ -39,6 +37,7 @@
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-...\""
|
||||
]
|
||||
},
|
||||
@@ -56,9 +55,7 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e81e0a08-3a99-42e6-adcc-00bb4ce1c3d4",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!wget \"https://www.dropbox.com/scl/fi/fxg17log5ydwoflhxmgrb/treasury_report.pdf?rlkey=mdintk0o2uuzkple26vc4v6fd&dl=1\" -O treasury_report.pdf"
|
||||
@@ -66,11 +63,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"id": "ecfc578c-3c7f-4ec1-aa06-51565c28632b",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -84,20 +79,15 @@
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"parser = LlamaParse(\n",
|
||||
" result_type=\"text\",\n",
|
||||
" language=\"fr\"\n",
|
||||
")\n",
|
||||
"parser = LlamaParse(result_type=\"text\", language=\"fr\")\n",
|
||||
"documents = parser.load_data(\"./treasury_report.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"execution_count": null,
|
||||
"id": "0c37db27-3496-4a59-918b-701c9ad7706d",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -209,11 +199,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 24,
|
||||
"execution_count": null,
|
||||
"id": "ac332ea3-cfff-4216-b292-62410a26c336",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -248,11 +236,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 25,
|
||||
"execution_count": null,
|
||||
"id": "45235b17-08f0-48f1-92aa-06711225860b",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -266,20 +252,15 @@
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"parser = LlamaParse(\n",
|
||||
" result_type=\"text\",\n",
|
||||
" language=\"ch_sim\"\n",
|
||||
")\n",
|
||||
"parser = LlamaParse(result_type=\"text\", language=\"ch_sim\")\n",
|
||||
"documents = parser.load_data(\"./chinese_pdf.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 28,
|
||||
"execution_count": null,
|
||||
"id": "f0d546cc-6549-4cf5-8b37-0896f4e8d43d",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -401,9 +382,7 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "640f0679-7f7e-4b0a-a46d-b099ae382fe2",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# download another copy with a different name to avoid hitting pdf cache\n",
|
||||
@@ -412,11 +391,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 31,
|
||||
"execution_count": null,
|
||||
"id": "bfcacf90-ca67-4bfd-b023-be0af2cb18c5",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -429,10 +406,7 @@
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"base_parser = LlamaParse(\n",
|
||||
" result_type=\"text\",\n",
|
||||
" language=\"en\"\n",
|
||||
")\n",
|
||||
"base_parser = LlamaParse(result_type=\"text\", language=\"en\")\n",
|
||||
"base_documents = parser.load_data(\"./chinese_pdf2.pdf\")"
|
||||
]
|
||||
},
|
||||
@@ -440,21 +414,11 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b264ed4e-647a-4f51-9f79-fdf82b76762a",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(base_documents[0].get_content()[1000:10000])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d9f02762-bb97-4e0e-8268-ccc00612a974",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
@@ -472,8 +436,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.8"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LlamaParse With MongoDB\n",
|
||||
"\n",
|
||||
"<a href=\"https://colab.research.google.com/github/run-llama/llama_parse/blob/main/examples/demo_mongodb.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
|
||||
"\n",
|
||||
"In this notebook, we provide a straightforward example of using LlamaParse with MongoDB Atlas VectorSearch.\n",
|
||||
"\n",
|
||||
"We illustrate the process of using llama-parse to parse a PDF document, then index the document with a MongoDB vector store, and subsequently perform basic queries against this store.\n",
|
||||
"\n",
|
||||
"This notebook is structured similarly to quick start guides, aiming to introduce users to utilizing llama-parse in conjunction with a MongoDB Atlas VectorSearch."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Installation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install llama-index llama-parse\n",
|
||||
"%pip install llama-index-vector-stores-mongodb llama-index-llms-openai"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Setup API Keys"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\n",
|
||||
" \"LLAMA_CLOUD_API_KEY\"\n",
|
||||
"] = \"\" # Get it from https://cloud.llamaindex.ai/api-key\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"\" # Get it from https://platform.openai.com/api-keys"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# llama-parse is async-first, running the sync code in a notebook requires the use of nest_asyncio\n",
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"import requests\n",
|
||||
"import pymongo\n",
|
||||
"\n",
|
||||
"from llama_index.vector_stores.mongodb import MongoDBAtlasVectorSearch\n",
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"from llama_index.embeddings.openai import OpenAIEmbedding\n",
|
||||
"from llama_index.core import VectorStoreIndex, StorageContext\n",
|
||||
"from llama_index.core.node_parser import SimpleNodeParser"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Download Document\n",
|
||||
"\n",
|
||||
"We will use `Attention is all you need` paper."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Download complete.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# The URL of the file you want to download\n",
|
||||
"url = \"https://arxiv.org/pdf/1706.03762.pdf\"\n",
|
||||
"# The local path where you want to save the file\n",
|
||||
"file_path = \"./attention.pdf\"\n",
|
||||
"\n",
|
||||
"# Perform the HTTP request\n",
|
||||
"response = requests.get(url)\n",
|
||||
"\n",
|
||||
"# Check if the request was successful\n",
|
||||
"if response.status_code == 200:\n",
|
||||
" # Open the file in binary write mode and save the content\n",
|
||||
" with open(file_path, \"wb\") as file:\n",
|
||||
" file.write(response.content)\n",
|
||||
" print(\"Download complete.\")\n",
|
||||
"else:\n",
|
||||
" print(\"Error downloading the file.\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Parse the document using `LlamaParse`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id 09a49745-9f21-4190-9de8-27e4e1a4bdf5\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"documents = LlamaParse(result_type=\"text\").load_data(file_path)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"rmer - model architecture.\n",
|
||||
"The Transformer follows this overall architecture using stacked self-attention and point-wise, fully\n",
|
||||
"connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\n",
|
||||
"respectively.\n",
|
||||
"3.1 Encoder and Decoder Stacks\n",
|
||||
"Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two\n",
|
||||
"sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-\n",
|
||||
"wise fully connected feed-forward network. We employ a residual connection [11] around each of\n",
|
||||
"the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is\n",
|
||||
"LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\n",
|
||||
"itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\n",
|
||||
"layers, produce outputs of dimension dmodel = 512.\n",
|
||||
"Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Take a quick look at some of the parsed text from the document:\n",
|
||||
"print(documents[0].get_content()[10000:11000])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create `MongoDBAtlasVectorSearch`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"mongo_uri = os.environ[\"MONGO_URI\"]\n",
|
||||
"\n",
|
||||
"mongodb_client = pymongo.MongoClient(mongo_uri)\n",
|
||||
"mongodb_vector_store = MongoDBAtlasVectorSearch(mongodb_client)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create nodes."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"node_parser = SimpleNodeParser()\n",
|
||||
"\n",
|
||||
"nodes = node_parser.get_nodes_from_documents(documents)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create Index and Query Engine."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"storage_context = StorageContext.from_defaults(vector_store=mongodb_vector_store)\n",
|
||||
"\n",
|
||||
"index = VectorStoreIndex(\n",
|
||||
" nodes=nodes,\n",
|
||||
" storage_context=storage_context,\n",
|
||||
" embed_model=OpenAIEmbedding(),\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_engine = index.as_query_engine(similarity_top_k=2)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Test Query"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"\n",
|
||||
"***********New LlamaParse+ Basic Query Engine***********\n",
|
||||
"The BLEU score on the WMT 2014 English-to-German translation task is 28.4.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"query = \"What is BLEU score on the WMT 2014 English-to-German translation task?\"\n",
|
||||
"\n",
|
||||
"response = query_engine.query(query)\n",
|
||||
"print(\"\\n***********New LlamaParse+ Basic Query Engine***********\")\n",
|
||||
"print(response)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"We varied the learning\n",
|
||||
"rate over the course of training, according to the formula:\n",
|
||||
" lrate = d−0.5 (3)\n",
|
||||
" model · min(step_num−0.5, step_num · warmup_steps−1.5)\n",
|
||||
"This corresponds to increasing the learning rate linearly for the first warmup_steps training steps,\n",
|
||||
"and decreasing it thereafter proportionally to the inverse square root of the step number. We used\n",
|
||||
"warmup_steps = 4000.\n",
|
||||
"5.4 Regularization\n",
|
||||
"We employ three types of regularization during training:\n",
|
||||
" 7\n",
|
||||
"---\n",
|
||||
"Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the\n",
|
||||
"English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.\n",
|
||||
" Model BLEU Training Cost (FLOPs)\n",
|
||||
" EN-DE EN-FR EN-DE EN-FR\n",
|
||||
" ByteNet [18] 23.75\n",
|
||||
" Deep-Att + PosUnk [39] 39.2 1.0 · 1020\n",
|
||||
" GNMT + RL [38] 24.6 39.92 2.3 · 1019 1.4 · 1020\n",
|
||||
" ConvS2S [9] 25.16 40.46 9.6 · 1018 1.5 · 1020\n",
|
||||
" MoE [32] 26.03 40.56 2.0 · 1019 1.2 · 1020\n",
|
||||
" Deep-Att + PosUnk Ensemble [39] 40.4 8.0 · 1020\n",
|
||||
" GNMT + RL Ensemble [38] 26.30 41.16 1.8 · 1020 1.1 · 1021\n",
|
||||
" ConvS2S Ensemble [9] 26.36 41.29 7.7 · 1019 1.2 · 1021\n",
|
||||
" Transformer (base model) 27.3 38.1 3.3 · 1018\n",
|
||||
" Transformer (big) 28.4 41.8 2.3 · 1019\n",
|
||||
"Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the\n",
|
||||
"sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the\n",
|
||||
"positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of\n",
|
||||
"Pdrop = 0.1.\n",
|
||||
"Label Smoothing During training, we employed label smoothing of value ϵls = 0.1 [36]. This\n",
|
||||
"hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.\n",
|
||||
"6 Results\n",
|
||||
"6.1 Machine Translation\n",
|
||||
"On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big)\n",
|
||||
"in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0\n",
|
||||
"BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is\n",
|
||||
"listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model\n",
|
||||
"surpasses all previously published models and ensembles, at a fraction of the training cost of any of\n",
|
||||
"the competitive models.\n",
|
||||
"On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0,\n",
|
||||
"outperforming all of the previously published single models, at less than 1/4 the training cost of the\n",
|
||||
"previous state-of-the-art model. The Transformer (big) model trained for English-to-French used\n",
|
||||
"dropout rate Pdrop = 0.1, instead of 0.3.\n",
|
||||
"For the base models, we used a single model obtained by averaging the last 5 checkpoints, which\n",
|
||||
"were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We\n",
|
||||
"used beam search with a beam size of 4 and length penalty α = 0.6 [38]. These hyperparameters\n",
|
||||
"were chosen after experimentation on the development set. We set the maximum output length during\n",
|
||||
"inference to input length + 50, but terminate early when possible [38].\n",
|
||||
"Table 2 summarizes our results and compares our translation quality and training costs to other model\n",
|
||||
"architectures from the literature.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Take a look at one of the source nodes from the response\n",
|
||||
"print(response.source_nodes[0].get_content())"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "anthropic_env",
|
||||
"language": "python",
|
||||
"name": "anthropic_env"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
},
|
||||
"vscode": {
|
||||
"interpreter": {
|
||||
"hash": "b0fa6594d8f4cbf19f97940f81e996739fb7646882a419484c72d19e05852a7e"
|
||||
}
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -28,13 +28,13 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install llama-index\n",
|
||||
"!pip install llama-index-core\n",
|
||||
"!pip install llama-index-embeddings-openai\n",
|
||||
"!pip install llama-index-question-gen-openai\n",
|
||||
"!pip install llama-index-postprocessor-flag-embedding-reranker\n",
|
||||
"!pip install git+https://github.com/FlagOpen/FlagEmbedding.git\n",
|
||||
"!pip install llama-parse"
|
||||
"%pip install llama-index\n",
|
||||
"%pip install llama-index-core\n",
|
||||
"%pip install llama-index-embeddings-openai\n",
|
||||
"%pip install llama-index-question-gen-openai\n",
|
||||
"%pip install llama-index-postprocessor-flag-embedding-reranker\n",
|
||||
"%pip install git+https://github.com/FlagOpen/FlagEmbedding.git\n",
|
||||
"%pip install llama-parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -56,15 +56,17 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# llama-parse is async-first, running the async code in a notebook requires the use of nest_asyncio\n",
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# API access to llama-cloud\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-\"\n",
|
||||
"\n",
|
||||
@@ -74,7 +76,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -83,11 +85,11 @@
|
||||
"from llama_index.core import VectorStoreIndex\n",
|
||||
"from llama_index.core import Settings\n",
|
||||
"\n",
|
||||
"embed_model=OpenAIEmbedding(model=\"text-embedding-3-small\")\n",
|
||||
"embed_model = OpenAIEmbedding(model=\"text-embedding-3-small\")\n",
|
||||
"llm = OpenAI(model=\"gpt-3.5-turbo-0125\")\n",
|
||||
"\n",
|
||||
"Settings.llm = llm\n",
|
||||
"Settings.embed_model = embed_model\n"
|
||||
"Settings.embed_model = embed_model"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -109,8 +111,8 @@
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"docs_2021 = LlamaParse(result_type=\"markdown\").load_data('./apple_2021_10k.pdf')\n",
|
||||
"docs_2020 = LlamaParse(result_type=\"markdown\").load_data('./apple_2020_10k.pdf')"
|
||||
"docs_2021 = LlamaParse(result_type=\"markdown\").load_data(\"./apple_2021_10k.pdf\")\n",
|
||||
"docs_2020 = LlamaParse(result_type=\"markdown\").load_data(\"./apple_2020_10k.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -127,31 +129,34 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 36,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core.node_parser import MarkdownElementNodeParser\n",
|
||||
"\n",
|
||||
"node_parser = MarkdownElementNodeParser(llm=OpenAI(model=\"gpt-3.5-turbo-0125\"), num_workers=8)"
|
||||
"node_parser = MarkdownElementNodeParser(\n",
|
||||
" llm=OpenAI(model=\"gpt-3.5-turbo-0125\"), num_workers=8\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 46,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import pickle\n",
|
||||
"from llama_index.postprocessor.flag_embedding_reranker import FlagEmbeddingReranker\n",
|
||||
"from llama_index.postprocessor.flag_embedding_reranker import (\n",
|
||||
" FlagEmbeddingReranker,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"reranker = FlagEmbeddingReranker(\n",
|
||||
" top_n=5,\n",
|
||||
" model=\"BAAI/bge-reranker-large\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def create_query_engine_over_doc(docs, nodes_save_path=None):\n",
|
||||
" \"\"\"Big function to go from document path -> recursive retriever.\"\"\"\n",
|
||||
" if nodes_save_path is not None and os.path.exists(nodes_save_path):\n",
|
||||
@@ -161,16 +166,13 @@
|
||||
" if nodes_save_path is not None:\n",
|
||||
" pickle.dump(raw_nodes, open(nodes_save_path, \"wb\"))\n",
|
||||
"\n",
|
||||
" base_nodes, objects = node_parser.get_nodes_and_objects(\n",
|
||||
" raw_nodes\n",
|
||||
" )\n",
|
||||
" base_nodes, objects = node_parser.get_nodes_and_objects(raw_nodes)\n",
|
||||
"\n",
|
||||
" ### Construct Retrievers\n",
|
||||
" # construct top-level vector index + query engine\n",
|
||||
" vector_index = VectorStoreIndex(nodes=base_nodes+objects)\n",
|
||||
" vector_index = VectorStoreIndex(nodes=base_nodes + objects)\n",
|
||||
" query_engine = vector_index.as_query_engine(\n",
|
||||
" similarity_top_k=15,\n",
|
||||
" node_postprocessors=[reranker]\n",
|
||||
" similarity_top_k=15, node_postprocessors=[reranker]\n",
|
||||
" )\n",
|
||||
" return query_engine, base_nodes"
|
||||
]
|
||||
@@ -178,9 +180,7 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_engine_2021, nodes_2021 = create_query_engine_over_doc(\n",
|
||||
@@ -193,10 +193,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 38,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core.tools import QueryEngineTool, ToolMetadata\n",
|
||||
@@ -209,18 +207,14 @@
|
||||
" query_engine=query_engine_2021,\n",
|
||||
" metadata=ToolMetadata(\n",
|
||||
" name=\"apple_2021_10k\",\n",
|
||||
" description=(\n",
|
||||
" \"Provides information about Apple financials for year 2021\"\n",
|
||||
" ),\n",
|
||||
" description=(\"Provides information about Apple financials for year 2021\"),\n",
|
||||
" ),\n",
|
||||
" ),\n",
|
||||
" QueryEngineTool(\n",
|
||||
" query_engine=query_engine_2020,\n",
|
||||
" metadata=ToolMetadata(\n",
|
||||
" name=\"apple_2020_10k\",\n",
|
||||
" description=(\n",
|
||||
" \"Provides information about Apple financials for year 2020\"\n",
|
||||
" ),\n",
|
||||
" description=(\"Provides information about Apple financials for year 2020\"),\n",
|
||||
" ),\n",
|
||||
" ),\n",
|
||||
"]\n",
|
||||
@@ -241,10 +235,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 41,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -271,10 +263,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 40,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -290,10 +280,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 42,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -316,10 +304,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 44,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -342,10 +328,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 45,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -358,13 +342,6 @@
|
||||
"source": [
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
@@ -382,8 +359,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.8"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0db58db5-d4ee-4631-af5b-4fc53eb05170",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# RAG with Excel Spreadsheet using LlamaPrase\n",
|
||||
"\n",
|
||||
"<a href=\"https://colab.research.google.com/github/run-llama/llama_parse/blob/main/examples/demo_excel.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
|
||||
"\n",
|
||||
"This notebook constructs a RAG pipeline over a simple DCF template [here](https://eqvista.com/app/uploads/2020/09/Eqvista_DCF-Excel-Template.xlsx).\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5f7d99ad-6ebd-47d0-92a7-566630b0c22a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup\n",
|
||||
"\n",
|
||||
"We first setup and load the data. If you haven't already, [download the template](https://eqvista.com/app/uploads/2020/09/Eqvista_DCF-Excel-Template.xlsx) and name it `dcf_template.xlxs` locally."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d867d1a6-cfcf-4f53-952a-f4a6ff2fa205",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install llama-index\n",
|
||||
"%pip install llama-parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "103c7983-56d3-45be-b763-d1828d07c43e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7b694b56-e04b-4d87-aa37-f0725d6b3adb",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"# api_key = \"llx-\" # get from cloud.llamaindex.ai"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9c4693c7-c1c8-47b4-8a8c-25d7e9ef9d2c",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id cac11eca-d5da-4d46-90e6-321f40e11611\n",
|
||||
"Started parsing the file under job_id cac11eca-5450-4847-9da0-fa6879c4cf3a\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"parser = LlamaParse(\n",
|
||||
" # api_key=api_key, # can also be set in your env as LLAMA_CLOUD_API_KEY\n",
|
||||
" result_type=\"markdown\",\n",
|
||||
")\n",
|
||||
"docs = parser.load_data(\"./dcf_template.xlsx\")\n",
|
||||
"# docs_txt = LlamaParse(result_type=\"text\").load_data(\"./dcf_template.xlsx\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7302f1c8-e405-4cda-8ff7-1d55185816f7",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"# Cover Page\n",
|
||||
"\n",
|
||||
"|Thank you for downloading our DCF Model excel template. This DCF Model excel template helps you to value your business using Discounted Free Cash Flow or DCF Method. | |\n",
|
||||
"|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n",
|
||||
"| | |\n",
|
||||
"| |Eqvista is an equity management software that allows companies, investors and company shareholders to track, manage, and make intelligent decisions about their companies’ equity.|\n",
|
||||
"| | |\n",
|
||||
"| |GET STARTED- IT'S FREE |\n",
|
||||
"| | |\n",
|
||||
"| |Note: This template is not professional advice and not a substitute for professional advice. |\n",
|
||||
"|Accordingly, before taking any actions based upon such information, we encourage you to consult with the appropriate professionals. | |\n",
|
||||
"| | |\n",
|
||||
"| |@Eqvista Inc. All Rights Reserved |\n",
|
||||
"---\n",
|
||||
"# DCF Model\n",
|
||||
"\n",
|
||||
"|Discounted Cash Flow Excel Template | | | | | | | | | | | |\n",
|
||||
"|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------|-----------|-----------|-----------------------|-----------|-----------------------|--------------|-----------|-----------|-----------|--------------|\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Here is a simple discounted cash flow excel template for estimating your company value based on this income valuation approach | | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Instructions: | | | | | | | | | | | |\n",
|
||||
"|1) Fill out the two assumptions in yellow highlight | | | | | | | | | | | |\n",
|
||||
"|2) Fill in either the 5 year or 3 year weighted average figures in yellow highlight | | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Assumptions | | | | | | | | | | | |\n",
|
||||
"|Tax Rate |20% | | | | | | | | | | |\n",
|
||||
"|Discount Rate |15% | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|5 Year Weighted Moving Average | | | | | | | | | | | |\n",
|
||||
"|Indication of Company Value |$242,995.43 | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|3 Year Weighted Moving Average | | | | | | | | | | | |\n",
|
||||
"|Indication of Company Value |$158,651.07 | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"| |5 Year Weighted Moving Average| | | | | | | | | | |\n",
|
||||
"| |Past Years | | | | |Forecasted Future Years| | | | | |\n",
|
||||
"| |Year 1 |Year 2 |Year 3 |Year 4 |Year 5 |Year 6 |Year 7 |Year 8 |Year 9 |Year 10 |Terminal Value|\n",
|
||||
"|Pre-tax income |50,000.00 |55,000.00 |45,000.00 |52,000.00 |60,000.00 | | | | | | |\n",
|
||||
"|Income Taxes |10,000.00 |11,000.00 |9,000.00 |10,400.00 |12,000.00 | | | | | | |\n",
|
||||
"|Net Income |40,000.00 |44,000.00 |36,000.00 |41,600.00 |48,000.00 | | | | | | |\n",
|
||||
"|Depreciation Expense |5,000.00 |4,000.00 |3,000.00 |2,000.00 |1,000.00 | | | | | | |\n",
|
||||
"|Capital Expenditures |10,000.00 |8,000.00 |5,000.00 |5,000.00 |7,000.00 | | | | | | |\n",
|
||||
"|Debt Repayments |5,000.00 |5,000.00 |5,000.00 |5,000.00 |5,000.00 | | | | | | |\n",
|
||||
"|Net Cash Flow |20,000.00 |27,000.00 |23,000.00 |29,600.00 |35,000.00 |29,093.33 |29,817.78 |30,177.48 |30,469.23 |30,379.74 |287,188.00 |\n",
|
||||
"|Discounting Factor | | | | | |0.8696 |0.7561 |0.6575 |0.5718 |0.4972 |0.4972 |\n",
|
||||
"|Present Value of Future Cash Flow | | | | | |25,298.55 |22,546.52 |19,842.18 |17,420.88 |15,104.10 |142,783.19 |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"| |3 Year Weighted Moving Average| | | | | | | | | | |\n",
|
||||
"| |Past Years | | |Forecasted Future Years| | | | | | | |\n",
|
||||
"| |Year 1 |Year 2 |Year 3 |Year 4 |Year 5 |Year 6 |Terminal Value| | | | |\n",
|
||||
"|Pre-tax income |50,000.00 |55,000.00 |45,000.00 | | | | | | | | |\n",
|
||||
"|Income Taxes |10,000.00 |11,000.00 |9,000.00 | | | | | | | | |\n",
|
||||
"|Net Income |40,000.00 |44,000.00 |36,000.00 | | | | | | | | |\n",
|
||||
"|Depreciation Expense |5,000.00 |4,000.00 |3,000.00 | | | | | | | | |\n",
|
||||
"|Capital Expenditures |10,000.00 |8,000.00 |5,000.00 | | | | | | | | |\n",
|
||||
"|Debt Repayments |5,000.00 |5,000.00 |5,000.00 | | | | | | | | |\n",
|
||||
"|Net Cash Flow |20,000.00 |27,000.00 |23,000.00 |23,833.33 |24,083.33 |23,819.44 |158,253.59 | | | | |\n",
|
||||
"|Discounting Factor | | | |0.8696 |0.7561 |0.6575 |0.6575 | | | | |\n",
|
||||
"|Present Value of Future Cash Flow | | | |20,724.64 |18,210.46 |15,661.67 |104,054.30 | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Notes: | | | | | | | | | | | |\n",
|
||||
"|-We based this simple discounted cash flow excel model based on the weighted moving averages (5 year or 3 year) for simplicity, in case a constant growth rate cannot be easily determined.| | | | | | | | | | | |\n",
|
||||
"|-The factors such as Depreciation Expense, Capital Expense and Debt Repayments remain constant, so consider this when looking at the forecasted figures. | | | | | | | | | | | |\n",
|
||||
"|-For the terminal value constant growth rate, we make the assumption of the growth from the last forecasted year compared to the first forecasted year. Adjust in the formula as needed. | | | | | | | | | | | |\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(docs[0].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1aedd4bb-7939-4fbc-8f07-d362e24d9772",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Configure LLM, Setup Basic Summary Engine\n",
|
||||
"\n",
|
||||
"We setup a basic summary engine which retrieves the entire document as context to put into the prompt."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f7c056a8-d098-4ebe-9341-d9f07081067c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.llms.openai import OpenAI\n",
|
||||
"from llama_index.core import Settings\n",
|
||||
"\n",
|
||||
"llm = OpenAI(model=\"gpt-4-turbo-preview\")\n",
|
||||
"Settings.llm = llm"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c0fa2630-ee1b-4ce7-91e9-f9ffff8347f9",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SummaryIndex\n",
|
||||
"\n",
|
||||
"index = SummaryIndex.from_documents(docs)\n",
|
||||
"# index = SummaryIndex.from_documents(docs_txt)\n",
|
||||
"\n",
|
||||
"query_engine = index.as_query_engine()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1d39a075-46b8-4dcb-8aee-abd10343bedd",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Define Baseline\n",
|
||||
"\n",
|
||||
"Let's define a baseline query engine over this data, using a naive parser (our PandasExcelReader, available on LlamaHub)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "632f918e-7811-4931-8a5f-4aa4850718db",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Collecting openpyxl\n",
|
||||
" Downloading openpyxl-3.1.3-py2.py3-none-any.whl (251 kB)\n",
|
||||
"\u001b[2K \u001b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m251.3/251.3 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\n",
|
||||
"\u001b[?25hCollecting et-xmlfile\n",
|
||||
" Using cached et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)\n",
|
||||
"Installing collected packages: et-xmlfile, openpyxl\n",
|
||||
"Successfully installed et-xmlfile-1.1.0 openpyxl-3.1.3\n",
|
||||
"\n",
|
||||
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip available: \u001b[0m\u001b[31;49m22.2.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.0\u001b[0m\n",
|
||||
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"!pip install llama-index-readers-file\n",
|
||||
"!pip install openpyxl"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "85ff09fd-8a99-4aa4-8182-8d0cf30f7b85",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.readers.file import PandasExcelReader\n",
|
||||
"import importlib\n",
|
||||
"from pathlib import Path\n",
|
||||
"\n",
|
||||
"base_reader = PandasExcelReader()\n",
|
||||
"base_docs = base_reader.load_data(Path(\"dcf_template.xlsx\"))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ba45f806-58be-4f57-bf42-2721555136cb",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Discounted Cash Flow Excel Template \n",
|
||||
" \n",
|
||||
"Here is a simple discounted cash flow excel template for estimating your company value based on this income valuation approach \n",
|
||||
" \n",
|
||||
"Instructions: \n",
|
||||
"1) Fill out the two assumptions in yellow highlight \n",
|
||||
"2) Fill in either the 5 year or 3 year weighted average figures in yellow highlight \n",
|
||||
" \n",
|
||||
" \n",
|
||||
" \n",
|
||||
" \n",
|
||||
"Assumptions \n",
|
||||
"Tax Rate 0.2 \n",
|
||||
"Discount Rate 0.15 \n",
|
||||
" \n",
|
||||
"5 Year Weighted Moving Average \n",
|
||||
"Indication of Company Value 242995.4347636059 \n",
|
||||
" \n",
|
||||
"3 Year Weighted Moving Average \n",
|
||||
"Indication of Company Value 158651.0723286644 \n",
|
||||
" \n",
|
||||
" 5 Year Weighted Moving Average \n",
|
||||
" Past Years Forecasted Future Years \n",
|
||||
" Year 1 Year 2 Year 3 Year 4 Year 5 Year 6 Year 7 Year 8 Year 9 Year 10 Terminal Value\n",
|
||||
"Pre-tax income 50000 55000 45000 52000 60000 \n",
|
||||
"Income Taxes 10000 11000 9000 10400 12000 \n",
|
||||
"Net Income 40000 44000 36000 41600 48000 \n",
|
||||
"Depreciation Expense 5000 4000 3000 2000 1000 \n",
|
||||
"Capital Expenditures 10000 8000 5000 5000 7000 \n",
|
||||
"Debt Repayments 5000 5000 5000 5000 5000 \n",
|
||||
"Net Cash Flow 20000 27000 23000 29600 35000 29093.333333333332 29817.777777777774 30177.481481481478 30469.234567901232 30379.73991769547 287188.0007003137\n",
|
||||
"Discounting Factor 0.8695652173913044 0.7561436672967865 0.6575162324319883 0.5717532455930334 0.4971767352982899 0.4971767352982899\n",
|
||||
"Present Value of Future Cash Flow 25298.550724637684 22546.523839529513 19842.183927989798 17420.883754932976 15104.099911490972 142783.19260502496\n",
|
||||
" \n",
|
||||
" \n",
|
||||
" 3 Year Weighted Moving Average \n",
|
||||
" Past Years Forecasted Future Years \n",
|
||||
" Year 1 Year 2 Year 3 Year 4 Year 5 Year 6 Terminal Value \n",
|
||||
"Pre-tax income 50000 55000 45000 \n",
|
||||
"Income Taxes 10000 11000 9000 \n",
|
||||
"Net Income 40000 44000 36000 \n",
|
||||
"Depreciation Expense 5000 4000 3000 \n",
|
||||
"Capital Expenditures 10000 8000 5000 \n",
|
||||
"Debt Repayments 5000 5000 5000 \n",
|
||||
"Net Cash Flow 20000 27000 23000 23833.333333333332 24083.333333333332 23819.44444444444 158253.58851674633 \n",
|
||||
"Discounting Factor 0.8695652173913044 0.7561436672967865 0.6575162324319883 0.6575162324319883 \n",
|
||||
"Present Value of Future Cash Flow 20724.63768115942 18210.459987397608 15661.671369734164 104054.30329037321 \n",
|
||||
" \n",
|
||||
" \n",
|
||||
"Notes: \n",
|
||||
"-We based this simple discounted cash flow excel model based on the weighted moving averages (5 year or 3 year) for simplicity, in case a constant growth rate cannot be easily determined. \n",
|
||||
"-The factors such as Depreciation Expense, Capital Expense and Debt Repayments remain constant, so consider this when looking at the forecasted figures. \n",
|
||||
"-For the terminal value constant growth rate, we make the assumption of the growth from the last forecasted year compared to the first forecasted year. Adjust in the formula as needed. \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(base_docs[1].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ff6e812f-fa94-4b0f-8907-ee70983e53f1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SummaryIndex\n",
|
||||
"\n",
|
||||
"base_index = SummaryIndex.from_documents([base_docs[1]])\n",
|
||||
"\n",
|
||||
"base_query_engine = base_index.as_query_engine()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "fa75f1bc-6fed-4721-ba5e-dc5408395618",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Ask Questions over this Data\n",
|
||||
"\n",
|
||||
"Let's now ask questions over this data, using both the LlamaParse-powered pipeline and naive pipeline."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "a875a20e-a6b6-46b7-80d4-614546215ffc",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_str = \"Tell me about the income taxes in the past years (year 3-5) for the 5 year WMA table\"\n",
|
||||
"response = query_engine.query(query_str)\n",
|
||||
"base_response = base_query_engine.query(query_str)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "06b0b072-f159-47c4-9cad-9f0cc0d56b28",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"******* LlamaParse RAG *******\n",
|
||||
"The income taxes in the past years (year 3 to 5) for the 5-year Weighted Moving Average table were $9,000.00 in Year 3, $10,400.00 in Year 4, and $12,000.00 in Year 5.\n",
|
||||
"******* Naive RAG *******\n",
|
||||
"The income taxes in the past years (year 3-5) for the 5 year WMA table were $9,000, $10,400, and $12,000, respectively.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"******* LlamaParse RAG *******\")\n",
|
||||
"print(str(response))\n",
|
||||
"print(\"******* Naive RAG *******\")\n",
|
||||
"print(str(base_response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8bd0998f-4f7f-46f9-9b51-cfb510f384ee",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(response.source_nodes[0].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7a93af5f-fcea-4f14-80eb-5dfad230cd8a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_str = \"Tell me about the discounting factors in year 5 for the 3 year WMA\"\n",
|
||||
"response = query_engine.query(query_str)\n",
|
||||
"base_response = base_query_engine.query(query_str)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c6d3a5fb-c32c-4dea-8f2e-956af85456a4",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"******* LlamaParse RAG *******\n",
|
||||
"The discounting factor in year 5 for the 3-year Weighted Moving Average (WMA) is 0.7561.\n",
|
||||
"******* Naive RAG *******\n",
|
||||
"The discounting factor in year 5 for the 3-year Weighted Moving Average is 0.6575162324319883.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"******* LlamaParse RAG *******\")\n",
|
||||
"print(str(response))\n",
|
||||
"print(\"******* Naive RAG *******\")\n",
|
||||
"print(str(base_response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b96f3a9b-6e99-4192-b6d6-447319d3c4fa",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_str = \"Tell me about the projected net cash flow in years 7-9 for the 5 year WMA\"\n",
|
||||
"response = query_engine.query(query_str)\n",
|
||||
"base_response = base_query_engine.query(query_str)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "92b419b9-25ee-4d69-98d9-56c0a45b24af",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"******* LlamaParse RAG *******\n",
|
||||
"The projected net cash flow for years 7 to 9 in the 5-year Weighted Moving Average scenario is as follows: Year 7 is $29,817.78, Year 8 is $30,177.48, and Year 9 is $30,469.23.\n",
|
||||
"******* Naive RAG *******\n",
|
||||
"The projected net cash flow for years 7 to 9 in the 5-year weighted moving average scenario is as follows: Year 7 is $29,093.33, Year 8 is $29,817.78, and Year 9 is $30,177.48.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"******* LlamaParse RAG *******\")\n",
|
||||
"print(str(response))\n",
|
||||
"print(\"******* Naive RAG *******\")\n",
|
||||
"print(str(base_response))"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama_parse",
|
||||
"language": "python",
|
||||
"name": "llama_parse"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 334 KiB |
@@ -18,12 +18,11 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "14cdcfaf-88b4-4489-9910-e362e0ccec53",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"\n",
|
||||
"from llama_parse import LlamaParse"
|
||||
@@ -31,12 +30,13 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"id": "6f5b5841-dd3e-4169-9bd4-6a672b5b34ee",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-\""
|
||||
]
|
||||
},
|
||||
@@ -68,7 +68,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": null,
|
||||
"id": "0dd0f860-8e92-43a7-9443-ad1a4fb9365c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -78,7 +78,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": null,
|
||||
"id": "fd932bef-ba82-4449-b7a0-5c2a9b55089f",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
@@ -104,7 +104,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": null,
|
||||
"id": "2a73e553-2194-4ac9-9764-0edab0d6fdce",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
@@ -308,11 +308,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"execution_count": null,
|
||||
"id": "c779547f-e4f7-4c84-9786-2b6b749827ab",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import VectorStoreIndex"
|
||||
@@ -320,7 +318,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"execution_count": null,
|
||||
"id": "68b3a95e-ce19-4df1-9fdd-e6efb2fc423a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -330,11 +328,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"execution_count": null,
|
||||
"id": "a2ae28f6-4b3a-4130-8e65-0921b7678739",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_engine = index.as_query_engine()"
|
||||
@@ -342,23 +338,21 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"execution_count": null,
|
||||
"id": "232091ee-aa22-4f51-838c-410024acc344",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = query_engine.query(\"What are some response quality challenges with naive RAG?\") "
|
||||
"response = query_engine.query(\n",
|
||||
" \"What are some response quality challenges with naive RAG?\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"execution_count": null,
|
||||
"id": "75f32aa7-c308-4221-af60-779822cfdba1",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -371,14 +365,6 @@
|
||||
"source": [
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d309d8fb-750a-4393-a1b2-67b14b7c121f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
@@ -396,8 +382,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.8"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "eld1dKaN7P8B"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LlamaParse - Parsing Financial Powerpoints 📊\n",
|
||||
"\n",
|
||||
@@ -13,9 +11,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "goB1sV8zu_Xl"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Installation\n",
|
||||
"\n",
|
||||
@@ -27,25 +23,17 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "7Y3_BwQLu-qK",
|
||||
"outputId": "b1129c52-7a70-44cc-ad03-1f8d3a8c794a"
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install llama-index\n",
|
||||
"!pip install llama-parse\n",
|
||||
"!pip install torch transformers python-pptx Pillow"
|
||||
"%pip install llama-index\n",
|
||||
"%pip install llama-parse\n",
|
||||
"%pip install torch transformers python-pptx Pillow"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "i-Rg2D_Rvf2i"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## API Key\n",
|
||||
"\n",
|
||||
@@ -55,32 +43,26 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "af6i2P1vuU-U"
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-...\"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"sk-...\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "p8Eq-aX-wAEo"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"**NOTE**: Since LlamaParse is natively async, running the sync code in a notebook requires the use of nest_asyncio.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {
|
||||
"id": "4OB0BkTqv_0l",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
@@ -90,9 +72,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "dz927ecMyYo_"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Importing the package\n",
|
||||
"\n",
|
||||
@@ -102,10 +82,7 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "nSW-6sEwyXwx",
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse"
|
||||
@@ -113,9 +90,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "l_D4YsAHwUSk"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Using LlamaParse to Parse Presentations\n",
|
||||
"\n",
|
||||
@@ -127,14 +102,7 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "d3qeuiyawT0U",
|
||||
"outputId": "cec0ea0a-be8b-49b6-9376-797c91f63be7",
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"! mkdir data; wget \"https://meetings.wmo.int/Cg-19/PublishingImages/SitePages/FINAC-43/7%20-%20EC-77-Doc%205%20Financial%20Statements%20for%202022%20(FINAC).pptx\" -O data/presentation.pptx"
|
||||
@@ -142,9 +110,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Gbr8RiHEyF3-"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Parsing the presentation\n",
|
||||
"\n",
|
||||
@@ -155,24 +121,15 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "osocsofoJ42S"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"#### Llama Index default"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "PTVy5XCNJwW-",
|
||||
"outputId": "d0e2cc4b-1407-45a9-b5e6-d06f91a533b4",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SimpleDirectoryReader\n",
|
||||
@@ -182,24 +139,15 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "oucbsciZJwxt"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"#### Llama Parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "3jKnXCuAyQ9_",
|
||||
"outputId": "1f668f17-1e20-46e5-fbab-9a55e4b28891",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -210,7 +158,9 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"llama_parse_documents = LlamaParse(result_type=\"markdown\").load_data(\"./data/presentation.pptx\")"
|
||||
"llama_parse_documents = LlamaParse(result_type=\"markdown\").load_data(\n",
|
||||
" \"./data/presentation.pptx\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -224,10 +174,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 27,
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -259,9 +207,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Compared against the original slide image.\n",
|
||||
""
|
||||
@@ -269,9 +215,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "p4GVOdWzzvYg"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Comparing the two for RAG\n",
|
||||
"\n",
|
||||
@@ -280,20 +224,15 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "oVcdGus5NDxi"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Query Engine on SimpleDirectoryReader results"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"metadata": {
|
||||
"id": "DqXYsLCWNg9_",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import VectorStoreIndex, SimpleDirectoryReader\n",
|
||||
@@ -304,20 +243,15 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ZLkHt9l2Nbxx"
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Query Engine on LlamaParse Results\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"metadata": {
|
||||
"id": "ZllaDcfRNLv3",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"llama_parse_index = VectorStoreIndex.from_documents(llama_parse_documents)\n",
|
||||
@@ -326,10 +260,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "0dY_0_1bNg0X",
|
||||
"tags": []
|
||||
},
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Liability provision\n",
|
||||
"What was the liability provision as of Dec 31 2021?\n",
|
||||
@@ -339,15 +270,8 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 21,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "Tmn-qNTEN-cb",
|
||||
"outputId": "a9bffc00-9cfc-43d8-b159-596a6c1aca64",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -358,21 +282,16 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"vanilla_response = vanilla_query_engine.query(\"What was the liability provision as of Dec 31 2021?\")\n",
|
||||
"vanilla_response = vanilla_query_engine.query(\n",
|
||||
" \"What was the liability provision as of Dec 31 2021?\"\n",
|
||||
")\n",
|
||||
"print(vanilla_response)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 22,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "4EZ_uqlROP7R",
|
||||
"outputId": "0645a159-06c6-411e-d1f6-79ea95d32b42",
|
||||
"tags": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -383,16 +302,11 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"llama_parse_response = llama_parse_query_engine.query(\"What was the liability provision as of Dec 31 2021?\")\n",
|
||||
"llama_parse_response = llama_parse_query_engine.query(\n",
|
||||
" \"What was the liability provision as of Dec 31 2021?\"\n",
|
||||
")\n",
|
||||
"print(llama_parse_response)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
@@ -413,8 +327,7 @@
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.8"
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,359 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f20600ce-d57a-446e-b033-3aadeec39c1b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LlamaParse with GPT-4o\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"<a href=\"https://colab.research.google.com/github/run-llama/llama_parse/blob/main/examples/test_tesla_impact_report/test_gpt4o.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
|
||||
"\n",
|
||||
"GPT-4o is a [fully multimodal model by OpenAI](https://openai.com/index/hello-gpt-4o/) released in May 2024. It matches GPT-4 Turbo performance in text and code, and has significantly improved vision and audio capabilities.\n",
|
||||
"\n",
|
||||
"The expanded vision/audio capabilities mean that it can be used for document parsing, by treating each page as an image and performing document extraction. We support using GPT-4o natively in LlamaParse for document parsing. The notebook below walks you through an example of using GPT-4o over the Tesla impact report.\n",
|
||||
"\n",
|
||||
"**NOTE**: The pricing for LlamaParse + gpt4o is an order more expensive than using LlamaParse by default. Currently, every page parsed with gpt4o counts for 10 pages in the LlamaParse usage tracker.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "86b173ac-9fce-4813-bdf1-6dd7d93a491d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ecc5eba5-96ce-4db7-bba1-f9ece33e681c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b805592b-d1a5-4cd2-b916-348f66ca7941",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"<LLAMA_CLOUD_API_KEY>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6e73e3c4-9e09-4cba-805f-326c82be812d",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Use LlamaParse with `gpt4o_mode=True`\n",
|
||||
"\n",
|
||||
"By turning on gpt4o, we use GPT-4o multimodal capabilities to do document parsing per page instead of the LlamaParse default pipeline.\n",
|
||||
"\n",
|
||||
"We load a snippet of the [2019 Tesla impact report](https://www.tesla.com/ns_videos/2019-tesla-impact-report.pdf). **NOTE**: The report is 57 pages, but will count for 570 pages in LlamaParse due to GPT-4o usage (which is approximately $1.71 USD).\n",
|
||||
"\n",
|
||||
"You can optionally choose to provide a `gpt4o_api_key`. If you do this, then we will use your API key to make GPT-4o calls, and your LlamaParse usage will be counted as if `gpt4o_mode` was not turned on (each page will be counted as a page instead of 10 pages). "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "aaa2ec5d-f27c-4262-80bf-e57daacff182",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"--2024-05-21 00:10:32-- https://www.dropbox.com/scl/fi/vu6w1dsfo5eddydz13ssm/2019-tesla-impact-report-15.pdf?rlkey=ik8lfqbg2p1ervss4qqt3xose&st=70j04z8j&dl=1\n",
|
||||
"Resolving www.dropbox.com (www.dropbox.com)... 2620:100:6057:18::a27d:d12, 162.125.13.18\n",
|
||||
"Connecting to www.dropbox.com (www.dropbox.com)|2620:100:6057:18::a27d:d12|:443... connected.\n",
|
||||
"HTTP request sent, awaiting response... 302 Found\n",
|
||||
"Location: https://uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com/cd/0/inline/CTTnZs8U4V1GtUCNxoB7INwmLq2yU97Q6QbWS6uVnb_XdHe368GrqF0zLDEKTnpc-x7utwNUUpMvWjLyrujrqNVrbGKTKa6hwHu5BxYPA2zXYrzdAEZyeve274xpHZKFywQ/file?dl=1# [following]\n",
|
||||
"--2024-05-21 00:10:33-- https://uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com/cd/0/inline/CTTnZs8U4V1GtUCNxoB7INwmLq2yU97Q6QbWS6uVnb_XdHe368GrqF0zLDEKTnpc-x7utwNUUpMvWjLyrujrqNVrbGKTKa6hwHu5BxYPA2zXYrzdAEZyeve274xpHZKFywQ/file?dl=1\n",
|
||||
"Resolving uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com (uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com)... 2620:100:6057:15::a27d:d0f, 162.125.13.15\n",
|
||||
"Connecting to uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com (uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com)|2620:100:6057:15::a27d:d0f|:443... connected.\n",
|
||||
"HTTP request sent, awaiting response... 302 Found\n",
|
||||
"Location: /cd/0/inline2/CTSaARDHbxvyEEgefshmsHLbuXkgV1Rmr-ItVhk5lPuZXkLlNnZMZWCF9YF5j4t2lLs4VurFW2VI1Q4A6ZFi8D2RXJmUG3wdgJhR6qSaBpwRZxjB_vk8qkJb8h1jRDaL7ATK6XYTHncab_aoPWzB62vrZ9yXUM0Mr-EdCX1k-hMbzXLV2dorA71IuFPY8ICkTemRWaG6VhBd3bV0C5AkMsAqy90w6Kez1ySFO06UkrxLSmkCaKdFgVoLcUVO2PLv4rGv6AuZOF_kqwsHdh82J9DQU4PMMyg-f5ChSGGSCKgmUfTBE2qP1eISP-GXSB91yWwMf-7rxGtM8MpDp-AL5jxYZxhZcmZn1cU8Or_8OOZrxg/file?dl=1 [following]\n",
|
||||
"--2024-05-21 00:10:33-- https://uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com/cd/0/inline2/CTSaARDHbxvyEEgefshmsHLbuXkgV1Rmr-ItVhk5lPuZXkLlNnZMZWCF9YF5j4t2lLs4VurFW2VI1Q4A6ZFi8D2RXJmUG3wdgJhR6qSaBpwRZxjB_vk8qkJb8h1jRDaL7ATK6XYTHncab_aoPWzB62vrZ9yXUM0Mr-EdCX1k-hMbzXLV2dorA71IuFPY8ICkTemRWaG6VhBd3bV0C5AkMsAqy90w6Kez1ySFO06UkrxLSmkCaKdFgVoLcUVO2PLv4rGv6AuZOF_kqwsHdh82J9DQU4PMMyg-f5ChSGGSCKgmUfTBE2qP1eISP-GXSB91yWwMf-7rxGtM8MpDp-AL5jxYZxhZcmZn1cU8Or_8OOZrxg/file?dl=1\n",
|
||||
"Reusing existing connection to [uc872df1ff4ea2fecd3d024fa97a.dl.dropboxusercontent.com]:443.\n",
|
||||
"HTTP request sent, awaiting response... 200 OK\n",
|
||||
"Length: 26199694 (25M) [application/binary]\n",
|
||||
"Saving to: ‘2019-tesla-impact-report-15.pdf’\n",
|
||||
"\n",
|
||||
"2019-tesla-impact-r 100%[===================>] 24.99M 30.5MB/s in 0.8s \n",
|
||||
"\n",
|
||||
"2024-05-21 00:10:35 (30.5 MB/s) - ‘2019-tesla-impact-report-15.pdf’ saved [26199694/26199694]\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"!wget \"https://www.dropbox.com/scl/fi/vu6w1dsfo5eddydz13ssm/2019-tesla-impact-report-15.pdf?rlkey=ik8lfqbg2p1ervss4qqt3xose&st=70j04z8j&dl=1\" -O \"2019-tesla-impact-report-15.pdf\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f46991c1-031b-461f-b9a6-9237a821f4c8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"parser_gpt4o = LlamaParse(\n",
|
||||
" result_type=\"markdown\",\n",
|
||||
" # api_key=api_key,\n",
|
||||
" gpt4o_mode=True,\n",
|
||||
" split_by_page=True,\n",
|
||||
" # gpt4o_api_key=\"<gpt4o_api_key>\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "1136ba82-074b-489d-9b0a-d609ccbf02b6",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id bf7d4619-3e26-479d-80e9-25702186ef32\n",
|
||||
"."
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"documents_gpt4o = parser_gpt4o.load_data(\"./2019-tesla-impact-report-15.pdf\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9e65c54f-3e4c-4c78-b1e8-a55ebeba1f24",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"# Mission & Tesla Ecosystem\n",
|
||||
"\n",
|
||||
"Climate change is reaching alarming levels in large part due to emissions from burning fossil fuels for transportation and electricity generation. In 2016, carbon dioxide (CO2) concentration levels in the atmosphere exceeded the 400 parts per million threshold on a sustained basis - a level that climate scientists believe will have a catastrophic impact on the environment. Worse, annual global CO2 emissions continue to increase and have approximately doubled over the past 50 years to over 43 gigatons in 2019. The world’s current path is unwise and unsustainable.\n",
|
||||
"\n",
|
||||
"The world cannot reduce CO2 emissions without addressing both energy generation and consumption. And the world cannot address its energy habits without first directly reducing emissions in the transportation and energy sectors. We are focused on creating a complete energy and transportation ecosystem from solar generation and energy storage to all-electric vehicles that produce zero tailpipe emissions.\n",
|
||||
"\n",
|
||||
"Since the onset of shelter-in-place orders and travel restrictions due to COVID-19, we have seen dramatic increases in air quality across the planet, as well as projections for CO2 emissions to drop in excess of 4% in 2020 compared to pre-COVID-19 levels, according to researchers. Because these improvements in air quality and reductions in CO2 are a result of a global economic disruption and not due to systemic changes in how we produce and consume energy, they are not expected to be sustained absent intervention. However, these changes have shown us the positive impacts of reduced pollution in a very short period of time. At Tesla, we believe that we all have an unprecedented opportunity to learn from this disruption and accelerate the deployment of clean energy solutions as part of a recovery for all economies throughout the world, and we will actively continue to advocate for the realization of these long-term changes.\n",
|
||||
"\n",
|
||||
"| Global Greenhouse Gas (GHG) Emissions by Economic Sector |\n",
|
||||
"|----------------------------------------------------------|\n",
|
||||
"|  |\n",
|
||||
"\n",
|
||||
"| Sector | Percentage |\n",
|
||||
"|---------------------------------------------|------------|\n",
|
||||
"| Electricity & Heat Production* | 31% |\n",
|
||||
"| Agriculture, Forestry & Other Land Use | 20% |\n",
|
||||
"| Industry | 18% |\n",
|
||||
"| Transportation* | 16% |\n",
|
||||
"| Other Energy | 9% |\n",
|
||||
"| Buildings | 6% |\n",
|
||||
"\n",
|
||||
"*Tesla-related sectors. Source: World Resources Institute\n",
|
||||
"\n",
|
||||
"According to the Global Carbon project, when fully tallied, total carbon emissions from 2019 are expected to hit another record high of over 43 gigatons for the year. Energy use through electricity and heat production (31%) and transportation (16%) are significant drivers of these GHG emissions.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(documents_gpt4o[3].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "d62cbb62-37ea-4370-9411-d979aa3a627e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Build RAG pipeline over the Parsed Report\n",
|
||||
"\n",
|
||||
"We now try building a RAG pipeline over this parsed report. It's not a lot of text, but we split it into chunks and load it into a simple in-memory vector store.\n",
|
||||
"\n",
|
||||
"We ask a question over the parsed markdown table and get back the right answer! We also ask a question over the text."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d8b7c3ad-2147-448c-bcbe-3e6fcd8d5361",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import VectorStoreIndex\n",
|
||||
"\n",
|
||||
"vector_index = VectorStoreIndex(documents_gpt4o)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8013351a-180d-4947-9f81-513042175c19",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_engine = vector_index.as_query_engine(similarity_top_k=6)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "795dc5c4-e122-4ff3-94d2-747fa51d5add",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = query_engine.query(\n",
|
||||
" \"What are the greenhouse emissions for agriculture and transportation?\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "39d2e6bd-3316-49b5-9a5d-5b4b95343e5a",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Agriculture accounts for 20% of global greenhouse gas emissions, while transportation contributes 16% of these emissions.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9beb5cd4-4041-48c7-b22b-de5540f92a6d",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Let's also try asking a question over another piece of the text."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "543c8b63-5cd1-47a1-a8a1-81abbfd3e52b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = query_engine.query(\n",
|
||||
" \"How does the EPA range of Teslas compare with other vehicles? Give details\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e739eabf-732b-4f59-9628-972c4bf6c857",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The EPA range of Tesla vehicles varies across different models. The Model 3 Standard Range Plus (SR+) achieves an EPA range of 4.8 miles/kWh, making it the most efficient electric vehicle in production. The Model Y all-wheel drive (AWD) achieves 4.1 miles/kWh, which positions it as the most efficient electric SUV produced to date. The energy efficiency of Tesla vehicles is highlighted by these EPA range figures, showcasing their advancements in powertrain efficiency compared to other electric vehicles on the market.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(str(response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "04b05c53-1a81-41a7-97f2-98a960211957",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"# Reducing Carbon Footprint Even Further\n",
|
||||
"## Improving Powertrain Efficiency\n",
|
||||
"\n",
|
||||
"Tesla vehicles are known to have the highest energy efficiency of any EV built to date. In the early days of Model S production, we were able to achieve energy efficiency of 3.1 EPA miles / kWh. Today, our most efficient Model 3 Standard Range Plus (SR+) achieves an EPA range of 4.8 miles / kWh, more than any EV in production. Model Y all-wheel drive (AWD) achieves 4.1 EPA miles / kWh, which makes it the most efficient electric SUV produced to date.\n",
|
||||
"\n",
|
||||
"The energy efficiency of Tesla vehicles will continue to improve further over time as we continue to improve our technology and powertrain efficiency. It is also reasonable to assume that our high-mileage products, such as our future Tesla Robotaxis, will be designed for maximum energy efficiency as handling, acceleration, and top speed become less relevant. That way, we will minimize cost for our customers as well as reduce the carbon footprint per mile driven.\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| Vehicle Type | Manufacturing Phase | Use Phase | Total Emissions |\n",
|
||||
"|---------------------------------------|---------------------|-----------|-----------------|\n",
|
||||
"| Avg. Mid-Size Premium ICE | | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged)| | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged)| | | |\n",
|
||||
"\n",
|
||||
"*Note: The chart shows that the emissions depend on powertrain efficiency.*\n",
|
||||
"\n",
|
||||
"### Energy Efficiency EPA range in miles/kWh\n",
|
||||
"\n",
|
||||
"| Vehicle Model | EPA Range (miles/kWh) |\n",
|
||||
"|---------------------|-----------------------|\n",
|
||||
"| Model 3 SR+ | 4.8 |\n",
|
||||
"| Model 3 AWD | |\n",
|
||||
"| Model Y AWD | |\n",
|
||||
"| Hyundai Kona | |\n",
|
||||
"| Chevy Bolt | |\n",
|
||||
"| Model S LR+ | |\n",
|
||||
"| Nissan Leaf | |\n",
|
||||
"| Model X LR+ | |\n",
|
||||
"| Jaguar iPace | |\n",
|
||||
"| Mercedes EQC* | |\n",
|
||||
"| Ford Mach E AWD | |\n",
|
||||
"| Audi e-tron | |\n",
|
||||
"| Porsche Taycan | |\n",
|
||||
"\n",
|
||||
"*Tesla estimate. Source: OEM websites*\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(response.source_nodes[0].get_content())"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama_parse",
|
||||
"language": "python",
|
||||
"name": "llama_parse"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
from llama_parse.base import LlamaParse, ResultType
|
||||
|
||||
__all__ = ["LlamaParse", "ResultType"]
|
||||
__all__ = ["LlamaParse", "ResultType"]
|
||||
|
||||
+299
-194
@@ -3,122 +3,42 @@ import asyncio
|
||||
import httpx
|
||||
import mimetypes
|
||||
import time
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Union
|
||||
from io import BufferedIOBase
|
||||
|
||||
from llama_index.core.async_utils import run_jobs
|
||||
from llama_index.core.bridge.pydantic import Field, validator
|
||||
from llama_index.core.constants import DEFAULT_BASE_URL
|
||||
from llama_index.core.readers.base import BasePydanticReader
|
||||
from llama_index.core.schema import Document
|
||||
from llama_parse.utils import (
|
||||
nest_asyncio_err,
|
||||
nest_asyncio_msg,
|
||||
ResultType,
|
||||
Language,
|
||||
SUPPORTED_FILE_TYPES,
|
||||
)
|
||||
from copy import deepcopy
|
||||
|
||||
# can put in a path to the file or the file bytes itself
|
||||
# if passing as bytes or a buffer, must provide the file_name in extra_info
|
||||
FileInput = Union[str, bytes, BufferedIOBase]
|
||||
|
||||
|
||||
nest_asyncio_err = "cannot be called from a running event loop"
|
||||
nest_asyncio_msg = "The event loop is already running. Add `import nest_asyncio; nest_asyncio.apply()` to your code to fix this issue."
|
||||
def _get_sub_docs(docs: List[Document]) -> List[Document]:
|
||||
"""Split docs into pages, by separator."""
|
||||
sub_docs = []
|
||||
for doc in docs:
|
||||
doc_chunks = doc.text.split("\n---\n")
|
||||
for doc_chunk in doc_chunks:
|
||||
sub_doc = Document(
|
||||
text=doc_chunk,
|
||||
metadata=deepcopy(doc.metadata),
|
||||
)
|
||||
sub_docs.append(sub_doc)
|
||||
|
||||
class ResultType(str, Enum):
|
||||
"""The result type for the parser."""
|
||||
TXT = "text"
|
||||
MD = "markdown"
|
||||
|
||||
class Language(str, Enum):
|
||||
BAZA = "abq"
|
||||
ADYGHE = "ady"
|
||||
AFRIKAANS = "af"
|
||||
ANGIKA = "ang"
|
||||
ARABIC = "ar"
|
||||
ASSAMESE = "as"
|
||||
AVAR = "ava"
|
||||
AZERBAIJANI = "az"
|
||||
BELARUSIAN = "be"
|
||||
BULGARIAN = "bg"
|
||||
BIHARI = "bh"
|
||||
BHOJPURI = "bho"
|
||||
BENGALI = "bn"
|
||||
BOSNIAN = "bs"
|
||||
SIMPLIFIED_CHINESE = "ch_sim"
|
||||
TRADITIONAL_CHINESE = "ch_tra"
|
||||
CHECHEN = "che"
|
||||
CZECH = "cs"
|
||||
WELSH = "cy"
|
||||
DANISH = "da"
|
||||
DARGWA = "dar"
|
||||
GERMAN = "de"
|
||||
ENGLISH = "en"
|
||||
SPANISH = "es"
|
||||
ESTONIAN = "et"
|
||||
PERSIAN_FARSI = "fa"
|
||||
FRENCH = "fr"
|
||||
IRISH = "ga"
|
||||
GOAN_KONKANI = "gom"
|
||||
HINDI = "hi"
|
||||
CROATIAN = "hr"
|
||||
HUNGARIAN = "hu"
|
||||
INDONESIAN = "id"
|
||||
INGUSH = "inh"
|
||||
ICELANDIC = "is"
|
||||
ITALIAN = "it"
|
||||
JAPANESE = "ja"
|
||||
KABARDIAN = "kbd"
|
||||
KANNADA = "kn"
|
||||
KOREAN = "ko"
|
||||
KURDISH = "ku"
|
||||
LATIN = "la"
|
||||
LAK = "lbe"
|
||||
LEZGHIAN = "lez"
|
||||
LITHUANIAN = "lt"
|
||||
LATVIAN = "lv"
|
||||
MAGAHI = "mah"
|
||||
MAITHILI = "mai"
|
||||
MAORI = "mi"
|
||||
MONGOLIAN = "mn"
|
||||
MARATHI = "mr"
|
||||
MALAY = "ms"
|
||||
MALTESE = "mt"
|
||||
NEPALI = "ne"
|
||||
NEWARI = "new"
|
||||
DUTCH = "nl"
|
||||
NORWEGIAN = "no"
|
||||
OCCITAN = "oc"
|
||||
PALI = "pi"
|
||||
POLISH = "pl"
|
||||
PORTUGUESE = "pt"
|
||||
ROMANIAN = "ro"
|
||||
RUSSIAN = "ru"
|
||||
SERBIAN_CYRILLIC = "rs_cyrillic"
|
||||
SERBIAN_LATIN = "rs_latin"
|
||||
NAGPURI = "sck"
|
||||
SLOVAK = "sk"
|
||||
SLOVENIAN = "sl"
|
||||
ALBANIAN = "sq"
|
||||
SWEDISH = "sv"
|
||||
SWAHILI = "sw"
|
||||
TAMIL = "ta"
|
||||
TABASSARAN = "tab"
|
||||
TELUGU = "te"
|
||||
THAI = "th"
|
||||
TAJIK = "tjk"
|
||||
TAGALOG = "tl"
|
||||
TURKISH = "tr"
|
||||
UYGHUR = "ug"
|
||||
UKRANIAN = "uk"
|
||||
URDU = "ur"
|
||||
UZBEK = "uz"
|
||||
VIETNAMESE = "vi"
|
||||
|
||||
|
||||
SUPPORTED_FILE_TYPES = [
|
||||
".pdf",
|
||||
".xml"
|
||||
".doc",
|
||||
".docx",
|
||||
".pptx",
|
||||
".rtf",
|
||||
".pages",
|
||||
".key",
|
||||
".epub"
|
||||
]
|
||||
return sub_docs
|
||||
|
||||
|
||||
class LlamaParse(BasePydanticReader):
|
||||
@@ -135,8 +55,8 @@ class LlamaParse(BasePydanticReader):
|
||||
num_workers: int = Field(
|
||||
default=4,
|
||||
gt=0,
|
||||
lt=10,
|
||||
description="The number of workers to use sending API requests for parsing."
|
||||
lt=10,
|
||||
description="The number of workers to use sending API requests for parsing.",
|
||||
)
|
||||
check_interval: int = Field(
|
||||
default=1,
|
||||
@@ -149,12 +69,74 @@ class LlamaParse(BasePydanticReader):
|
||||
verbose: bool = Field(
|
||||
default=True, description="Whether to print the progress of the parsing."
|
||||
)
|
||||
language: Language = Field(
|
||||
default=Language.ENGLISH, description="The language of the text to parse."
|
||||
show_progress: bool = Field(
|
||||
default=True, description="Show progress when parsing multiple files."
|
||||
)
|
||||
language: Language = Field(
|
||||
default=Language.ENGLISH, description="The language of the text to parse."
|
||||
)
|
||||
parsing_instruction: Optional[str] = Field(
|
||||
default="",
|
||||
description="The parsing instruction for the parser."
|
||||
default="", description="The parsing instruction for the parser."
|
||||
)
|
||||
skip_diagonal_text: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the parser will ignore diagonal text (when the text rotation in degrees modulo 90 is not 0).",
|
||||
)
|
||||
invalidate_cache: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the cache will be ignored and the document re-processes. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice.",
|
||||
)
|
||||
do_not_cache: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the document will not be cached. This mean that you will be re-charged it you reprocess them as they will not be cached.",
|
||||
)
|
||||
fast_mode: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="Note: Non compatible with gpt-4o. If set to true, the parser will use a faster mode to extract text from documents. This mode will skip OCR of images, and table/heading reconstruction.",
|
||||
)
|
||||
do_not_unroll_columns: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the parser will keep column in the text according to document layout. Reduce reconstruction accuracy, and LLM's/embedings performances in most case.",
|
||||
)
|
||||
page_separator: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The page separator to use to split the text. Default is None, which means the parser will use the default separator '\\n---\\n'.",
|
||||
)
|
||||
gpt4o_mode: bool = Field(
|
||||
default=False,
|
||||
description="Whether to use gpt-4o extract text from documents.",
|
||||
)
|
||||
gpt4o_api_key: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The API key for the GPT-4o API. Lowers the cost of parsing.",
|
||||
)
|
||||
bounding_box: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The bounding box to use to extract text from documents describe as a string containing the bounding box margins",
|
||||
)
|
||||
target_pages: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The target pages to extract text from documents. Describe as a comma separated list of page numbers. The first page of the document is page 0",
|
||||
)
|
||||
ignore_errors: bool = Field(
|
||||
default=True,
|
||||
description="Whether or not to ignore and skip errors raised during parsing.",
|
||||
)
|
||||
split_by_page: bool = Field(
|
||||
default=True,
|
||||
description="Whether to split by page (NOTE: using a predefined separator `\n---\n`)",
|
||||
)
|
||||
vendor_multimodal_api_key: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The API key for the multimodal API.",
|
||||
)
|
||||
use_vendor_multimodal: bool = Field(
|
||||
default=False,
|
||||
description="Whether to use the vendor multimodal API.",
|
||||
)
|
||||
vendor_multimodal_model_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The model name for the vendor multimodal API.",
|
||||
)
|
||||
|
||||
@validator("api_key", pre=True, always=True)
|
||||
@@ -162,13 +144,14 @@ class LlamaParse(BasePydanticReader):
|
||||
"""Validate the API key."""
|
||||
if not v:
|
||||
import os
|
||||
|
||||
api_key = os.getenv("LLAMA_CLOUD_API_KEY", None)
|
||||
if api_key is None:
|
||||
raise ValueError("The API key is required.")
|
||||
return api_key
|
||||
|
||||
|
||||
return v
|
||||
|
||||
|
||||
@validator("base_url", pre=True, always=True)
|
||||
def validate_base_url(cls, v: str) -> str:
|
||||
"""Validate the base URL."""
|
||||
@@ -176,96 +159,177 @@ class LlamaParse(BasePydanticReader):
|
||||
return url or v or DEFAULT_BASE_URL
|
||||
|
||||
# upload a document and get back a job_id
|
||||
async def _create_job(self, file_path: str, extra_info: Optional[dict] = None) -> str:
|
||||
file_path = str(file_path)
|
||||
file_ext = os.path.splitext(file_path)[1]
|
||||
if file_ext not in SUPPORTED_FILE_TYPES:
|
||||
raise Exception(
|
||||
f"Currently, only the following file types are supported: {SUPPORTED_FILE_TYPES}\n"
|
||||
f"Current file type: {file_ext}"
|
||||
async def _create_job(
|
||||
self, file_input: FileInput, extra_info: Optional[dict] = None
|
||||
) -> str:
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
url = f"{self.base_url}/api/parsing/upload"
|
||||
files = None
|
||||
file_handle = None
|
||||
|
||||
if isinstance(file_input, (bytes, BufferedIOBase)):
|
||||
if not extra_info or "file_name" not in extra_info:
|
||||
raise ValueError(
|
||||
"file_name must be provided in extra_info when passing bytes"
|
||||
)
|
||||
file_name = extra_info["file_name"]
|
||||
mime_type = mimetypes.guess_type(file_name)[0]
|
||||
files = {"file": (file_name, file_input, mime_type)}
|
||||
elif isinstance(file_input, (str, Path)):
|
||||
file_path = str(file_input)
|
||||
file_ext = os.path.splitext(file_path)[1]
|
||||
if file_ext not in SUPPORTED_FILE_TYPES:
|
||||
raise Exception(
|
||||
f"Currently, only the following file types are supported: {SUPPORTED_FILE_TYPES}\n"
|
||||
f"Current file type: {file_ext}"
|
||||
)
|
||||
mime_type = mimetypes.guess_type(file_path)[0]
|
||||
# Open the file here for the duration of the async context
|
||||
file_handle = open(file_path, "rb")
|
||||
files = {"file": (os.path.basename(file_path), file_handle, mime_type)}
|
||||
else:
|
||||
raise ValueError(
|
||||
"file_input must be either a file path string, file bytes, or buffer object"
|
||||
)
|
||||
|
||||
extra_info = extra_info or {}
|
||||
extra_info["file_path"] = file_path
|
||||
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
|
||||
# load data, set the mime type
|
||||
with open(file_path, "rb") as f:
|
||||
mime_type = mimetypes.guess_type(file_path)[0]
|
||||
files = {"file": (f.name, f, mime_type)}
|
||||
|
||||
# send the request, start job
|
||||
url = f"{self.base_url}/api/parsing/upload"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.max_timeout) as client:
|
||||
response = await client.post(url, files=files, headers=headers, data={"language": self.language.value, "parsing_instruction": self.parsing_instruction})
|
||||
response = await client.post(
|
||||
url,
|
||||
files=files,
|
||||
headers=headers,
|
||||
data={
|
||||
"language": self.language.value,
|
||||
"parsing_instruction": self.parsing_instruction,
|
||||
"invalidate_cache": self.invalidate_cache,
|
||||
"skip_diagonal_text": self.skip_diagonal_text,
|
||||
"do_not_cache": self.do_not_cache,
|
||||
"fast_mode": self.fast_mode,
|
||||
"do_not_unroll_columns": self.do_not_unroll_columns,
|
||||
"page_separator": self.page_separator,
|
||||
"gpt4o_mode": self.gpt4o_mode,
|
||||
"gpt4o_api_key": self.gpt4o_api_key,
|
||||
"bounding_box": self.bounding_box,
|
||||
"target_pages": self.target_pages,
|
||||
},
|
||||
)
|
||||
if not response.is_success:
|
||||
raise Exception(f"Failed to parse the file: {response.text}")
|
||||
job_id = response.json()["id"]
|
||||
return job_id
|
||||
finally:
|
||||
if file_handle is not None:
|
||||
file_handle.close()
|
||||
|
||||
# check the status of the job, return when done
|
||||
job_id = response.json()["id"]
|
||||
return job_id
|
||||
|
||||
async def _get_job_result(self, job_id: str, result_type: str) -> dict:
|
||||
async def _get_job_result(
|
||||
self, job_id: str, result_type: str, verbose: bool = False
|
||||
) -> dict:
|
||||
result_url = f"{self.base_url}/api/parsing/job/{job_id}/result/{result_type}"
|
||||
status_url = f"{self.base_url}/api/parsing/job/{job_id}"
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
|
||||
start = time.time()
|
||||
tries = 0
|
||||
while True:
|
||||
await asyncio.sleep(self.check_interval)
|
||||
async with httpx.AsyncClient(timeout=self.max_timeout) as client:
|
||||
tries += 1
|
||||
|
||||
result = await client.get(result_url, headers=headers)
|
||||
async with httpx.AsyncClient(timeout=self.max_timeout) as client:
|
||||
tries += 1
|
||||
|
||||
if result.status_code == 404:
|
||||
result = await client.get(status_url, headers=headers)
|
||||
|
||||
if result.status_code != 200:
|
||||
end = time.time()
|
||||
if end - start > self.max_timeout:
|
||||
raise Exception(
|
||||
f"Timeout while parsing the file: {job_id}"
|
||||
)
|
||||
if self.verbose and tries % 10 == 0:
|
||||
raise Exception(f"Timeout while parsing the file: {job_id}")
|
||||
if verbose and tries % 10 == 0:
|
||||
print(".", end="", flush=True)
|
||||
|
||||
await asyncio.sleep(self.check_interval)
|
||||
|
||||
continue
|
||||
|
||||
if result.status_code == 400:
|
||||
detail = result.json().get("detail", "Unknown error")
|
||||
raise Exception(f"Failed to parse the file: {detail}")
|
||||
# Allowed values "PENDING", "SUCCESS", "ERROR", "CANCELED"
|
||||
status = result.json()["status"]
|
||||
if status == "SUCCESS":
|
||||
parsed_result = await client.get(result_url, headers=headers)
|
||||
return parsed_result.json()
|
||||
elif status == "PENDING":
|
||||
end = time.time()
|
||||
if end - start > self.max_timeout:
|
||||
raise Exception(f"Timeout while parsing the file: {job_id}")
|
||||
if verbose and tries % 10 == 0:
|
||||
print(".", end="", flush=True)
|
||||
|
||||
return result.json()
|
||||
await asyncio.sleep(self.check_interval)
|
||||
|
||||
async def _aload_data(self, file_path: str, extra_info: Optional[dict] = None) -> List[Document]:
|
||||
continue
|
||||
else:
|
||||
raise Exception(
|
||||
f"Failed to parse the file: {job_id}, status: {status}"
|
||||
)
|
||||
|
||||
async def _aload_data(
|
||||
self,
|
||||
file_path: FileInput,
|
||||
extra_info: Optional[dict] = None,
|
||||
verbose: bool = False,
|
||||
) -> List[Document]:
|
||||
"""Load data from the input path."""
|
||||
try:
|
||||
job_id = await self._create_job(file_path, extra_info=extra_info)
|
||||
if self.verbose:
|
||||
if verbose:
|
||||
print("Started parsing the file under job_id %s" % job_id)
|
||||
|
||||
result = await self._get_job_result(job_id, self.result_type.value)
|
||||
|
||||
return [
|
||||
result = await self._get_job_result(
|
||||
job_id, self.result_type.value, verbose=verbose
|
||||
)
|
||||
|
||||
docs = [
|
||||
Document(
|
||||
text=result[self.result_type.value],
|
||||
metadata=extra_info or {},
|
||||
)
|
||||
]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error while parsing the file '{file_path}':", e)
|
||||
raise e
|
||||
return []
|
||||
|
||||
if self.split_by_page:
|
||||
return _get_sub_docs(docs)
|
||||
else:
|
||||
return docs
|
||||
|
||||
async def aload_data(self, file_path: Union[List[str], str], extra_info: Optional[dict] = None) -> List[Document]:
|
||||
except Exception as e:
|
||||
file_repr = file_path if isinstance(file_path, str) else "<bytes/buffer>"
|
||||
print(f"Error while parsing the file '{file_repr}':", e)
|
||||
if self.ignore_errors:
|
||||
return []
|
||||
else:
|
||||
raise e
|
||||
|
||||
async def aload_data(
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[Document]:
|
||||
"""Load data from the input path."""
|
||||
if isinstance(file_path, (str, Path)):
|
||||
return await self._aload_data(file_path, extra_info=extra_info)
|
||||
if isinstance(file_path, (str, Path, bytes, BufferedIOBase)):
|
||||
return await self._aload_data(
|
||||
file_path, extra_info=extra_info, verbose=self.verbose
|
||||
)
|
||||
elif isinstance(file_path, list):
|
||||
jobs = [self._aload_data(f, extra_info=extra_info) for f in file_path]
|
||||
jobs = [
|
||||
self._aload_data(
|
||||
f,
|
||||
extra_info=extra_info,
|
||||
verbose=self.verbose and not self.show_progress,
|
||||
)
|
||||
for f in file_path
|
||||
]
|
||||
try:
|
||||
results = await run_jobs(jobs, workers=self.num_workers)
|
||||
|
||||
results = await run_jobs(
|
||||
jobs,
|
||||
workers=self.num_workers,
|
||||
desc="Parsing files",
|
||||
show_progress=self.show_progress,
|
||||
)
|
||||
|
||||
# return flattened results
|
||||
return [item for sublist in results for item in sublist]
|
||||
except RuntimeError as e:
|
||||
@@ -274,9 +338,15 @@ class LlamaParse(BasePydanticReader):
|
||||
else:
|
||||
raise e
|
||||
else:
|
||||
raise ValueError("The input file_path must be a string or a list of strings.")
|
||||
raise ValueError(
|
||||
"The input file_path must be a string or a list of strings."
|
||||
)
|
||||
|
||||
def load_data(self, file_path: Union[List[str], str], extra_info: Optional[dict] = None) -> List[Document]:
|
||||
def load_data(
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[Document]:
|
||||
"""Load data from the input path."""
|
||||
try:
|
||||
return asyncio.run(self.aload_data(file_path, extra_info))
|
||||
@@ -285,35 +355,47 @@ class LlamaParse(BasePydanticReader):
|
||||
raise RuntimeError(nest_asyncio_msg)
|
||||
else:
|
||||
raise e
|
||||
|
||||
|
||||
async def _aget_json(self, file_path: str, extra_info: Optional[dict] = None) -> List[dict]:
|
||||
async def _aget_json(
|
||||
self, file_path: FileInput, extra_info: Optional[dict] = None
|
||||
) -> List[dict]:
|
||||
"""Load data from the input path."""
|
||||
try:
|
||||
job_id = await self._create_job(file_path, extra_info=extra_info)
|
||||
if self.verbose:
|
||||
print("Started parsing the file under job_id %s" % job_id)
|
||||
|
||||
|
||||
result = await self._get_job_result(job_id, "json")
|
||||
result["job_id"] = job_id
|
||||
result["file_path"] = file_path
|
||||
return [result]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error while parsing the file '{file_path}':", e)
|
||||
raise e
|
||||
|
||||
|
||||
|
||||
async def aget_json(self, file_path: Union[List[str], str], extra_info: Optional[dict] = None) -> List[dict]:
|
||||
except Exception as e:
|
||||
file_repr = file_path if isinstance(file_path, str) else "<bytes/buffer>"
|
||||
print(f"Error while parsing the file '{file_repr}':", e)
|
||||
if self.ignore_errors:
|
||||
return []
|
||||
else:
|
||||
raise e
|
||||
|
||||
async def aget_json(
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[dict]:
|
||||
"""Load data from the input path."""
|
||||
if isinstance(file_path, (str, Path)):
|
||||
return await self._aget_json(file_path, extra_info=extra_info)
|
||||
elif isinstance(file_path, list):
|
||||
jobs = [self._aget_json(f, extra_info=extra_info) for f in file_path]
|
||||
try:
|
||||
results = await run_jobs(jobs, workers=self.num_workers)
|
||||
|
||||
results = await run_jobs(
|
||||
jobs,
|
||||
workers=self.num_workers,
|
||||
desc="Parsing files",
|
||||
show_progress=self.show_progress,
|
||||
)
|
||||
|
||||
# return flattened results
|
||||
return [item for sublist in results for item in sublist]
|
||||
except RuntimeError as e:
|
||||
@@ -322,10 +404,15 @@ class LlamaParse(BasePydanticReader):
|
||||
else:
|
||||
raise e
|
||||
else:
|
||||
raise ValueError("The input file_path must be a string or a list of strings.")
|
||||
raise ValueError(
|
||||
"The input file_path must be a string or a list of strings."
|
||||
)
|
||||
|
||||
|
||||
def get_json_result(self, file_path: Union[List[str], str], extra_info: Optional[dict] = None) -> List[dict]:
|
||||
def get_json_result(
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[dict]:
|
||||
"""Parse the input path."""
|
||||
try:
|
||||
return asyncio.run(self.aget_json(file_path, extra_info))
|
||||
@@ -334,10 +421,15 @@ class LlamaParse(BasePydanticReader):
|
||||
raise RuntimeError(nest_asyncio_msg)
|
||||
else:
|
||||
raise e
|
||||
|
||||
def get_images(self, json_result: list[dict], download_path: str) -> List[dict]:
|
||||
|
||||
def get_images(self, json_result: List[dict], download_path: str) -> List[dict]:
|
||||
"""Download images from the parsed result."""
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
|
||||
# make the download path
|
||||
if not os.path.exists(download_path):
|
||||
os.makedirs(download_path)
|
||||
|
||||
try:
|
||||
images = []
|
||||
for result in json_result:
|
||||
@@ -347,16 +439,29 @@ class LlamaParse(BasePydanticReader):
|
||||
print(f"> Image for page {page['page']}: {page['images']}")
|
||||
for image in page["images"]:
|
||||
image_name = image["name"]
|
||||
image_path = os.path.join(download_path, f"{job_id}-{image_name}")
|
||||
image["path"]=image_path
|
||||
image["job_id"]=job_id
|
||||
image["original_pdf_path"]=result["file_path"]
|
||||
image["page_number"]=page["page"]
|
||||
|
||||
# get the full path
|
||||
image_path = os.path.join(
|
||||
download_path, f"{job_id}-{image_name}"
|
||||
)
|
||||
|
||||
# get a valid image path
|
||||
if not image_path.endswith(".png"):
|
||||
if not image_path.endswith(".jpg"):
|
||||
image_path += ".png"
|
||||
|
||||
image["path"] = image_path
|
||||
image["job_id"] = job_id
|
||||
image["original_pdf_path"] = result["file_path"]
|
||||
image["page_number"] = page["page"]
|
||||
with open(image_path, "wb") as f:
|
||||
image_url = f"{self.base_url}/api/parsing/job/{job_id}/result/image/{image_name}"
|
||||
f.write(httpx.get(image_url, headers=headers).content)
|
||||
images.append(image)
|
||||
return images
|
||||
except Exception as e:
|
||||
print(f"Error while downloading images from the parsed result:", e)
|
||||
return []
|
||||
print("Error while downloading images from the parsed result:", e)
|
||||
if self.ignore_errors:
|
||||
return []
|
||||
else:
|
||||
raise e
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
from enum import Enum
|
||||
|
||||
# Asyncio error messages
|
||||
nest_asyncio_err = "cannot be called from a running event loop"
|
||||
nest_asyncio_msg = "The event loop is already running. Add `import nest_asyncio; nest_asyncio.apply()` to your code to fix this issue."
|
||||
|
||||
|
||||
class ResultType(str, Enum):
|
||||
"""The result type for the parser."""
|
||||
|
||||
TXT = "text"
|
||||
MD = "markdown"
|
||||
JSON = "json"
|
||||
|
||||
|
||||
class Language(str, Enum):
|
||||
BAZA = "abq"
|
||||
ADYGHE = "ady"
|
||||
AFRIKAANS = "af"
|
||||
ANGIKA = "ang"
|
||||
ARABIC = "ar"
|
||||
ASSAMESE = "as"
|
||||
AVAR = "ava"
|
||||
AZERBAIJANI = "az"
|
||||
BELARUSIAN = "be"
|
||||
BULGARIAN = "bg"
|
||||
BIHARI = "bh"
|
||||
BHOJPURI = "bho"
|
||||
BENGALI = "bn"
|
||||
BOSNIAN = "bs"
|
||||
SIMPLIFIED_CHINESE = "ch_sim"
|
||||
TRADITIONAL_CHINESE = "ch_tra"
|
||||
CHECHEN = "che"
|
||||
CZECH = "cs"
|
||||
WELSH = "cy"
|
||||
DANISH = "da"
|
||||
DARGWA = "dar"
|
||||
GERMAN = "de"
|
||||
ENGLISH = "en"
|
||||
SPANISH = "es"
|
||||
ESTONIAN = "et"
|
||||
PERSIAN_FARSI = "fa"
|
||||
FRENCH = "fr"
|
||||
IRISH = "ga"
|
||||
GOAN_KONKANI = "gom"
|
||||
HINDI = "hi"
|
||||
CROATIAN = "hr"
|
||||
HUNGARIAN = "hu"
|
||||
INDONESIAN = "id"
|
||||
INGUSH = "inh"
|
||||
ICELANDIC = "is"
|
||||
ITALIAN = "it"
|
||||
JAPANESE = "ja"
|
||||
KABARDIAN = "kbd"
|
||||
KANNADA = "kn"
|
||||
KOREAN = "ko"
|
||||
KURDISH = "ku"
|
||||
LATIN = "la"
|
||||
LAK = "lbe"
|
||||
LEZGHIAN = "lez"
|
||||
LITHUANIAN = "lt"
|
||||
LATVIAN = "lv"
|
||||
MAGAHI = "mah"
|
||||
MAITHILI = "mai"
|
||||
MAORI = "mi"
|
||||
MONGOLIAN = "mn"
|
||||
MARATHI = "mr"
|
||||
MALAY = "ms"
|
||||
MALTESE = "mt"
|
||||
NEPALI = "ne"
|
||||
NEWARI = "new"
|
||||
DUTCH = "nl"
|
||||
NORWEGIAN = "no"
|
||||
OCCITAN = "oc"
|
||||
PALI = "pi"
|
||||
POLISH = "pl"
|
||||
PORTUGUESE = "pt"
|
||||
ROMANIAN = "ro"
|
||||
RUSSIAN = "ru"
|
||||
SERBIAN_CYRILLIC = "rs_cyrillic"
|
||||
SERBIAN_LATIN = "rs_latin"
|
||||
NAGPURI = "sck"
|
||||
SLOVAK = "sk"
|
||||
SLOVENIAN = "sl"
|
||||
ALBANIAN = "sq"
|
||||
SWEDISH = "sv"
|
||||
SWAHILI = "sw"
|
||||
TAMIL = "ta"
|
||||
TABASSARAN = "tab"
|
||||
TELUGU = "te"
|
||||
THAI = "th"
|
||||
TAJIK = "tjk"
|
||||
TAGALOG = "tl"
|
||||
TURKISH = "tr"
|
||||
UYGHUR = "ug"
|
||||
UKRAINIAN = "uk"
|
||||
URDU = "ur"
|
||||
UZBEK = "uz"
|
||||
VIETNAMESE = "vi"
|
||||
|
||||
|
||||
SUPPORTED_FILE_TYPES = [
|
||||
".pdf",
|
||||
# document and presentations
|
||||
".602",
|
||||
".abw",
|
||||
".cgm",
|
||||
".cwk",
|
||||
".doc",
|
||||
".docx",
|
||||
".docm",
|
||||
".dot",
|
||||
".dotm",
|
||||
".hwp",
|
||||
".key",
|
||||
".lwp",
|
||||
".mw",
|
||||
".mcw",
|
||||
".pages",
|
||||
".pbd",
|
||||
".ppt",
|
||||
".pptm",
|
||||
".pptx",
|
||||
".pot",
|
||||
".potm",
|
||||
".potx",
|
||||
".rtf",
|
||||
".sda",
|
||||
".sdd",
|
||||
".sdp",
|
||||
".sdw",
|
||||
".sgl",
|
||||
".sti",
|
||||
".sxi",
|
||||
".sxw",
|
||||
".stw",
|
||||
".sxg",
|
||||
".txt",
|
||||
".uof",
|
||||
".uop",
|
||||
".uot",
|
||||
".vor",
|
||||
".wpd",
|
||||
".wps",
|
||||
".xml",
|
||||
".zabw",
|
||||
".epub",
|
||||
# images
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".bmp",
|
||||
".svg",
|
||||
".tiff",
|
||||
".webp",
|
||||
# web
|
||||
".htm",
|
||||
".html",
|
||||
# spreadsheets
|
||||
".xlsx",
|
||||
".xls",
|
||||
".xlsm",
|
||||
".xlsb",
|
||||
".xlw",
|
||||
".csv",
|
||||
".dif",
|
||||
".sylk",
|
||||
".slk",
|
||||
".prn",
|
||||
".numbers",
|
||||
".et",
|
||||
".ods",
|
||||
".fods",
|
||||
".uos1",
|
||||
".uos2",
|
||||
".dbf",
|
||||
".wk1",
|
||||
".wk2",
|
||||
".wk3",
|
||||
".wk4",
|
||||
".wks",
|
||||
".123",
|
||||
".wq1",
|
||||
".wq2",
|
||||
".wb1",
|
||||
".wb2",
|
||||
".wb3",
|
||||
".qpw",
|
||||
".xlr",
|
||||
".eth",
|
||||
".tsv",
|
||||
]
|
||||
Generated
+735
-720
File diff suppressed because it is too large
Load Diff
+6
-6
@@ -1,6 +1,10 @@
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.poetry]
|
||||
name = "llama-parse"
|
||||
version = "0.3.9"
|
||||
version = "0.4.6"
|
||||
description = "Parse files into RAG-Optimized formats."
|
||||
authors = ["Logan Markewich <logan@llamaindex.ai>"]
|
||||
license = "MIT"
|
||||
@@ -9,12 +13,8 @@ packages = [{include = "llama_parse"}]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.8.1,<4.0"
|
||||
llama-index-core = ">=0.10.7"
|
||||
llama-index-core = ">=0.10.29"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
pytest = "^8.0.0"
|
||||
ipykernel = "^6.29.0"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
+83
-6
@@ -1,18 +1,95 @@
|
||||
import os
|
||||
import pytest
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
def test_simple_page_text():
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("LLAMA_CLOUD_API_KEY", "") == "",
|
||||
reason="LLAMA_CLOUD_API_KEY not set",
|
||||
)
|
||||
def test_simple_page_text() -> None:
|
||||
parser = LlamaParse(result_type="text")
|
||||
|
||||
filepath = os.path.join(os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf")
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
result = parser.load_data(filepath)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
def test_simple_page_markdown():
|
||||
parser = LlamaParse(result_type="markdown")
|
||||
|
||||
filepath = os.path.join(os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf")
|
||||
result = parser.load_data(filepath)
|
||||
@pytest.fixture
|
||||
def markdown_parser() -> LlamaParse:
|
||||
if os.environ.get("LLAMA_CLOUD_API_KEY", "") == "":
|
||||
pytest.skip("LLAMA_CLOUD_API_KEY not set")
|
||||
return LlamaParse(result_type="markdown", ignore_errors=False)
|
||||
|
||||
|
||||
def test_simple_page_markdown(markdown_parser: LlamaParse) -> None:
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
result = markdown_parser.load_data(filepath)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
def test_simple_page_markdown_bytes(markdown_parser: LlamaParse) -> None:
|
||||
markdown_parser = LlamaParse(result_type="markdown", ignore_errors=False)
|
||||
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
with open(filepath, "rb") as f:
|
||||
file_bytes = f.read()
|
||||
# client must provide extra_info with file_name
|
||||
with pytest.raises(ValueError):
|
||||
result = markdown_parser.load_data(file_bytes)
|
||||
result = markdown_parser.load_data(
|
||||
file_bytes, extra_info={"file_name": "attention_is_all_you_need.pdf"}
|
||||
)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
def test_simple_page_markdown_buffer(markdown_parser: LlamaParse) -> None:
|
||||
markdown_parser = LlamaParse(result_type="markdown", ignore_errors=False)
|
||||
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
with open(filepath, "rb") as f:
|
||||
# client must provide extra_info with file_name
|
||||
with pytest.raises(ValueError):
|
||||
result = markdown_parser.load_data(f)
|
||||
result = markdown_parser.load_data(
|
||||
f, extra_info={"file_name": "attention_is_all_you_need.pdf"}
|
||||
)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("LLAMA_CLOUD_API_KEY", "") == "",
|
||||
reason="LLAMA_CLOUD_API_KEY not set",
|
||||
)
|
||||
def test_simple_page_progress_workers() -> None:
|
||||
parser = LlamaParse(result_type="markdown", show_progress=True, verbose=True)
|
||||
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
result = parser.load_data([filepath, filepath])
|
||||
assert len(result) == 2
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
parser = LlamaParse(
|
||||
result_type="markdown", show_progress=True, num_workers=2, verbose=True
|
||||
)
|
||||
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
result = parser.load_data([filepath, filepath])
|
||||
assert len(result) == 2
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
Reference in New Issue
Block a user