code stringlengths 141 97.3k | apis listlengths 1 24 | extract_api stringlengths 113 214k |
|---|---|---|
#!/usr/bin/env python3
from flask import Flask, request
from werkzeug.utils import secure_filename
from llama_index import GPTSimpleVectorIndex, download_loader
import json
import secrets
app = Flask(__name__)
@app.route('/index', methods = ['GET', 'POST'])
def upload_and_index():
if request.method == "POST"... | [
"llama_index.GPTSimpleVectorIndex.load_from_disk",
"llama_index.download_loader",
"llama_index.GPTSimpleVectorIndex"
] | [((199, 214), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (204, 214), False, 'from flask import Flask, request\n'), ((893, 947), 'llama_index.GPTSimpleVectorIndex.load_from_disk', 'GPTSimpleVectorIndex.load_from_disk', (['f"""{data_id}.json"""'], {}), "(f'{data_id}.json')\n", (928, 947), False, 'from ll... |
from contextlib import contextmanager
import uuid
import os
import tiktoken
from . import S2_tools as scholar
import csv
import sys
import requests
# pdf loader
from langchain.document_loaders import OnlinePDFLoader
## paper questioning tools
from llama_index import Document
from llama_index.vector_stores import Pi... | [
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.vector_stores.PineconeVectorStore",
"llama_index.ServiceContext.from_defaults",
"llama_index.StorageContext.from_defaults",
"llama_index.embeddings.openai.OpenAIEmbedding"
] | [((768, 796), 'os.mkdir', 'os.mkdir', (['workspace_dir_name'], {}), '(workspace_dir_name)\n', (776, 796), False, 'import os\n'), ((5950, 5986), 'tiktoken.encoding_for_model', 'tiktoken.encoding_for_model', (['"""gpt-4"""'], {}), "('gpt-4')\n", (5977, 5986), False, 'import tiktoken\n'), ((7532, 7548), 'os.listdir', 'os.... |
import os
import logging
import sys
from llama_index import GPTSimpleVectorIndex
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
# 加载索引
new_index = GPTSimpleVectorIndex.load_from_disk('index.json')
# 查询索引
response = new_index.query("W... | [
"llama_index.GPTSimpleVectorIndex.load_from_disk"
] | [((82, 140), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (101, 140), False, 'import logging\n'), ((234, 283), 'llama_index.GPTSimpleVectorIndex.load_from_disk', 'GPTSimpleVectorIndex.load_from_disk', (['"""index.json... |
import os
import openai
from fastapi import FastAPI, HTTPException
from llama_index import StorageContext, load_index_from_storage, ServiceContext, set_global_service_context
from llama_index.indices.postprocessor import SentenceEmbeddingOptimizer
from llama_index.embeddings import OpenAIEmbedding
from pydantic import... | [
"llama_index.ServiceContext.from_defaults",
"llama_index.StorageContext.from_defaults",
"llama_index.load_index_from_storage",
"llama_index.indices.postprocessor.SentenceEmbeddingOptimizer",
"llama_index.set_global_service_context",
"llama_index.embeddings.OpenAIEmbedding"
] | [((385, 394), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (392, 394), False, 'from fastapi import FastAPI, HTTPException\n'), ((510, 546), 'llama_index.embeddings.OpenAIEmbedding', 'OpenAIEmbedding', ([], {'embed_batch_size': '(10)'}), '(embed_batch_size=10)\n', (525, 546), False, 'from llama_index.embeddings impor... |
"""Example of how to use llamaindex for semantic search.
This example assumes that initially there is a projects.DATASETS_DIR_PATH/embeddings.pkl file
that has a list of dictionaries with each dictionary containing "text",
"rule_name" and "section_label" fields.
The first time you run this script, a vector store will... | [
"llama_index.get_response_synthesizer",
"llama_index.schema.TextNode",
"llama_index.ServiceContext.from_defaults",
"llama_index.StorageContext.from_defaults",
"llama_index.VectorStoreIndex",
"llama_index.retrievers.VectorIndexRetriever",
"llama_index.load_index_from_storage",
"llama_index.indices.post... | [((1802, 1832), 'pathlib.Path', 'Path', (['"""cache/msrb_index_store"""'], {}), "('cache/msrb_index_store')\n", (1806, 1832), False, 'from pathlib import Path\n'), ((1726, 1783), 'os.path.join', 'os.path.join', (['project.DATASETS_DIR_PATH', '"""embeddings.pkl"""'], {}), "(project.DATASETS_DIR_PATH, 'embeddings.pkl')\n... |
from dotenv import load_dotenv
load_dotenv()
from llama_index import GPTVectorStoreIndex, TrafilaturaWebReader
import chromadb
def create_embedding_store(name):
chroma_client = chromadb.Client()
return chroma_client.create_collection(name)
def query_pages(collection, urls, questions):
docs = Trafilatur... | [
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.TrafilaturaWebReader"
] | [((32, 45), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (43, 45), False, 'from dotenv import load_dotenv\n'), ((185, 202), 'chromadb.Client', 'chromadb.Client', ([], {}), '()\n', (200, 202), False, 'import chromadb\n'), ((361, 431), 'llama_index.GPTVectorStoreIndex.from_documents', 'GPTVectorStoreIndex.from_... |
import logging
from llama_index.readers.base import BaseReader
from llama_index.readers.schema.base import Document
import requests
from typing import List
import re
import os
import logging
from llama_index.readers.base import BaseReader
from llama_index.readers.schema.base import Document
import requests
from typing ... | [
"llama_index.readers.schema.base.Document"
] | [((1299, 1406), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': '"""gpt-3.5-turbo"""', 'messages': 'messages', 'temperature': '(0.5)', 'max_tokens': '(256)'}), "(model='gpt-3.5-turbo', messages=messages,\n temperature=0.5, max_tokens=256)\n", (1327, 1406), False, 'import openai\n'), ((... |
"""Simple horoscope predictions generator."""
from typing import List, Optional, Dict, Callable
import re
import json
from llama_index.core.bridge.pydantic import PrivateAttr
from llama_index.core.readers.base import BasePydanticReader
from llama_index.core.schema import Document
from vedastro import *
class SimpleB... | [
"llama_index.core.bridge.pydantic.PrivateAttr",
"llama_index.core.Document",
"llama_index.core.schema.NodeWithScore"
] | [((767, 780), 'llama_index.core.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (778, 780), False, 'from llama_index.core.bridge.pydantic import PrivateAttr\n'), ((8054, 8115), 're.sub', 're.sub', (['"""((?<=[a-z])[A-Z]|(?<!\\\\A)[A-Z](?=[a-z]))"""', '""" \\\\1"""', 's'], {}), "('((?<=[a-z])[A-Z]|(?<!\\\... |
from llama_index.callbacks import CallbackManager, LlamaDebugHandler, CBEventType
from llama_index import ListIndex, ServiceContext, SimpleDirectoryReader, VectorStoreIndex
'''
Title of the page: A simple Python implementation of the ReAct pattern for LLMs
Name of the website: LlamaIndex (GPT Index) is a data framewor... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.callbacks.LlamaDebugHandler",
"llama_index.ServiceContext.from_defaults",
"llama_index.SimpleDirectoryReader",
"llama_index.callbacks.CallbackManager"
] | [((676, 718), 'llama_index.callbacks.LlamaDebugHandler', 'LlamaDebugHandler', ([], {'print_trace_on_end': '(True)'}), '(print_trace_on_end=True)\n', (693, 718), False, 'from llama_index.callbacks import CallbackManager, LlamaDebugHandler, CBEventType\n'), ((738, 768), 'llama_index.callbacks.CallbackManager', 'CallbackM... |
import logging
import os
from llama_index import (
StorageContext,
load_index_from_storage,
)
from app.engine.constants import STORAGE_DIR
from app.engine.context import create_service_context
def get_chat_engine():
service_context = create_service_context()
# check if storage already exists
if n... | [
"llama_index.StorageContext.from_defaults",
"llama_index.load_index_from_storage"
] | [((249, 273), 'app.engine.context.create_service_context', 'create_service_context', ([], {}), '()\n', (271, 273), False, 'from app.engine.context import create_service_context\n'), ((507, 535), 'logging.getLogger', 'logging.getLogger', (['"""uvicorn"""'], {}), "('uvicorn')\n", (524, 535), False, 'import logging\n'), (... |
"""Module for loading index."""
import logging
from typing import TYPE_CHECKING, Any, Optional
from llama_index import ServiceContext, StorageContext, load_index_from_storage
from llama_index.indices.base import BaseIndex
from ols.app.models.config import ReferenceContent
# This is to avoid importing HuggingFaceBge... | [
"llama_index.ServiceContext.from_defaults",
"llama_index.StorageContext.from_defaults",
"llama_index.load_index_from_storage"
] | [((661, 688), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (678, 688), False, 'import logging\n'), ((2376, 2445), 'llama_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'embed_model': 'self._embed_model', 'llm': 'None'}), '(embed_model=self._embed_model, llm=N... |
from llama_index import PromptTemplate
instruction_str = """\
1. Convert the query to executable Python code using Pandas.
2. The final line of code should be a Python expression that can be called with the `eval()` function.
3. The code should represent a solution to the query.
4. PRINT ONLY THE EXPR... | [
"llama_index.PromptTemplate"
] | [((381, 660), 'llama_index.PromptTemplate', 'PromptTemplate', (['""" You are working with a pandas dataframe in Python.\n The name of the dataframe is `df`.\n This is the result of `print(df.head())`:\n {df_str}\n\n Follow these instructions:\n {instruction_str}\n Query: {query_str}\n\n Expressi... |
import os, shutil, datetime, time, json
import gradio as gr
import sys
import os
from llama_index import GPTSimpleVectorIndex
bank_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../memory_bank')
sys.path.append(bank_path)
from build_memory_index import build_memory_index
memory_bank_path = os.path.joi... | [
"llama_index.GPTSimpleVectorIndex.load_from_disk"
] | [((213, 239), 'sys.path.append', 'sys.path.append', (['bank_path'], {}), '(bank_path)\n', (228, 239), False, 'import sys\n'), ((384, 417), 'sys.path.append', 'sys.path.append', (['memory_bank_path'], {}), '(memory_bank_path)\n', (399, 417), False, 'import sys\n'), ((882, 945), 'os.path.join', 'os.path.join', (['data_ar... |
from llama_index import SimpleDirectoryReader, VectorStoreIndex, load_index_from_storage
from llama_index.storage.storage_context import StorageContext
from llama_index.indices.service_context import ServiceContext
from llama_index.llms import OpenAI
from llama_index.node_parser import SimpleNodeParser
from llama_index... | [
"llama_index.node_parser.extractors.KeywordExtractor",
"llama_index.text_splitter.TokenTextSplitter",
"llama_index.node_parser.SimpleNodeParser",
"llama_index.SimpleDirectoryReader",
"llama_index.storage.storage_context.StorageContext.from_defaults",
"llama_index.node_parser.extractors.QuestionsAnsweredEx... | [((692, 705), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (703, 705), False, 'from dotenv import load_dotenv\n'), ((724, 751), 'os.getenv', 'os.getenv', (['"""OPENAI_API_KEY"""'], {}), "('OPENAI_API_KEY')\n", (733, 751), False, 'import sys, os\n'), ((781, 839), 'logging.basicConfig', 'logging.basicConfig', (... |
import os
from typing import Any, Callable, Dict, Optional, Sequence
from llama_index.bridge.pydantic import Field, PrivateAttr
from llama_index.core.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseGen,
CompletionResponse,
CompletionResponseGen,
LLMMetadata,
)
from llama_index.llms.... | [
"llama_index.core.llms.types.CompletionResponse",
"llama_index.bridge.pydantic.Field",
"llama_index.llms.base.llm_completion_callback",
"llama_index.bridge.pydantic.PrivateAttr",
"llama_index.core.llms.types.LLMMetadata",
"llama_index.llms.base.llm_chat_callback",
"llama_index.llms.generic_utils.complet... | [((858, 926), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to print verbose output."""'}), "(default=False, description='Whether to print verbose output.')\n", (863, 926), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((974, 987), 'llama_... |
from typing import Any, List, Optional, Sequence
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.base.base_retriever import BaseRetriever
from llama_index.core.base.response.schema import RESPONSE_TYPE
from llama_index.core.callbacks.base import CallbackManager
from llama_inde... | [
"llama_index.core.prompts.PromptTemplate",
"llama_index.core.settings.llm_from_settings_or_context",
"llama_index.core.node_parser.SentenceSplitter",
"llama_index.core.settings.callback_manager_from_settings_or_context",
"llama_index.core.response_synthesizers.get_response_synthesizer",
"llama_index.core.... | [((1182, 1924), 'llama_index.core.prompts.PromptTemplate', 'PromptTemplate', (['"""Please provide an answer based solely on the provided sources. When referencing information from a source, cite the appropriate source(s) using their corresponding numbers. Every answer should include at least one source citation. Only c... |
"""
# My first app
Here's our first attempt at using data to create a table:
"""
import logging
import sys
import streamlit as st
from clickhouse_connect import common
from llama_index.core.settings import Settings
from llama_index.embeddings.fastembed import FastEmbedEmbedding
from llama_index.llms.openai import Open... | [
"llama_index.core.PromptTemplate",
"llama_index.core.vector_stores.types.MetadataInfo",
"llama_index.core.VectorStoreIndex.from_vector_store",
"llama_index.llms.openai.OpenAI",
"llama_index.core.tools.QueryEngineTool.from_defaults",
"llama_index.core.SQLDatabase",
"llama_index.embeddings.fastembed.FastE... | [((1100, 1158), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (1119, 1158), False, 'import logging\n'), ((1713, 1957), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""Get summaries of Hacker ... |
import chromadb
import openai
from dotenv import load_dotenv
from langchain.chat_models import ChatOpenAI
load_dotenv()
from llama_index.llms import OpenAI
from llama_index import VectorStoreIndex, ServiceContext
from llama_index.vector_stores import ChromaVectorStore
import os
OPENAI_API_KEY = os.getenv('OPENAI_API_... | [
"llama_index.VectorStoreIndex.from_vector_store",
"llama_index.ServiceContext.from_defaults",
"llama_index.vector_stores.ChromaVectorStore"
] | [((107, 120), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (118, 120), False, 'from dotenv import load_dotenv\n'), ((298, 325), 'os.getenv', 'os.getenv', (['"""OPENAI_API_KEY"""'], {}), "('OPENAI_API_KEY')\n", (307, 325), False, 'import os\n'), ((390, 434), 'chromadb.PersistentClient', 'chromadb.PersistentCli... |
import os
from dotenv import load_dotenv
from llama_index import SimpleDirectoryReader, GPTSimpleVectorIndex, LLMPredictor
from langchain.chat_models import ChatOpenAI
load_dotenv()
os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_KEY')
def tune_llm(input_directory="sourcedata", output_file="indexdata/index.json"):
... | [
"llama_index.GPTSimpleVectorIndex",
"llama_index.SimpleDirectoryReader"
] | [((169, 182), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (180, 182), False, 'from dotenv import load_dotenv\n'), ((215, 238), 'os.getenv', 'os.getenv', (['"""OPENAI_KEY"""'], {}), "('OPENAI_KEY')\n", (224, 238), False, 'import os\n'), ((506, 571), 'llama_index.GPTSimpleVectorIndex', 'GPTSimpleVectorIndex', ... |
from ..conversable_agent import ConversableAgent
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from ....utils.client import ByzerLLM
from byzerllm.utils.retrieval import ByzerRetrieval
from ..agent import Agent
import ray
from ray.util.client.common import ClientActorHandle, ClientObjectRef... | [
"llama_index.VectorStoreIndex.from_vector_store",
"llama_index.tools.ToolMetadata",
"llama_index.query_engine.SubQuestionQueryEngine.from_defaults"
] | [((2438, 2462), 'byzerllm.apps.llama_index.get_service_context', 'get_service_context', (['llm'], {}), '(llm)\n', (2457, 2462), False, 'from byzerllm.apps.llama_index import get_service_context, get_storage_context\n'), ((2494, 2529), 'byzerllm.apps.llama_index.get_storage_context', 'get_storage_context', (['llm', 'ret... |
from typing import Union, Optional, List
from llama_index.chat_engine.types import BaseChatEngine, ChatMode
from llama_index.embeddings.utils import EmbedType
from llama_index.chat_engine import ContextChatEngine
from llama_index.memory import ChatMemoryBuffer
from lyzr.base.llm import LyzrLLMFactory
from lyzr.base.s... | [
"llama_index.memory.ChatMemoryBuffer.from_defaults"
] | [((1242, 1430), 'lyzr.utils.document_reading.read_pdf_as_documents', 'read_pdf_as_documents', ([], {'input_dir': 'input_dir', 'input_files': 'input_files', 'exclude_hidden': 'exclude_hidden', 'filename_as_id': 'filename_as_id', 'recursive': 'recursive', 'required_exts': 'required_exts'}), '(input_dir=input_dir, input_f... |
import json
from util import rm_file
from tqdm import tqdm
import argparse
from copy import deepcopy
import os
from util import JSONReader
import openai
from typing import List, Dict
from llama_index import (
ServiceContext,
OpenAIEmbedding,
PromptHelper,
VectorStoreIndex,
set_global_service_cont... | [
"llama_index.OpenAIEmbedding",
"llama_index.ServiceContext.from_defaults",
"llama_index.embeddings.cohereai.CohereEmbedding",
"llama_index.VectorStoreIndex",
"llama_index.postprocessor.FlagEmbeddingReranker",
"llama_index.llms.OpenAI",
"llama_index.embeddings.VoyageEmbedding",
"llama_index.embeddings.... | [((1340, 1395), 'os.environ.get', 'os.environ.get', (['"""OPENAI_API_KEY"""', '"""your_openai_api_key"""'], {}), "('OPENAI_API_KEY', 'your_openai_api_key')\n", (1354, 1395), False, 'import os\n'), ((1455, 1510), 'os.environ.get', 'os.environ.get', (['"""VOYAGE_API_KEY"""', '"""your_voyage_api_key"""'], {}), "('VOYAGE_A... |
import pinecone
import torch
import numpy as np
import torchvision.transforms as T
from PIL import Image
import os
import tqdm
import openai
import hashlib
import io
from gradio_client import Client
from monitor import Monitor, monitoring
from llama_index.vector_stores import PineconeVectorStore
from llama_index import... | [
"llama_index.schema.TextNode",
"llama_index.VectorStoreIndex.from_vector_store",
"llama_index.vector_stores.PineconeVectorStore"
] | [((945, 950), 'trulens_eval.Tru', 'Tru', ([], {}), '()\n', (948, 950), False, 'from trulens_eval import Feedback, Tru, TruLlama\n'), ((1012, 1020), 'trulens_eval.feedback.provider.openai.OpenAI', 'OpenAI', ([], {}), '()\n', (1018, 1020), False, 'from trulens_eval.feedback.provider.openai import OpenAI\n'), ((1697, 1746... |
# Copyright 2023 Qarik Group, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | [
"llama_index.query_engine.transform_query_engine.TransformQueryEngine",
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.StorageContext.from_defaults",
"llama_index.SimpleDirectoryReader",
"llama_index.indices.query.query_transform.base.DecomposeQu... | [((1710, 1726), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1724, 1726), False, 'import threading\n'), ((1794, 1810), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1808, 1810), False, 'import threading\n'), ((1950, 1991), 'common.solution.getenv', 'solution.getenv', (['"""EMBEDDINGS_BUCKET_NAME"""']... |
# The MIT License
# Copyright (c) Jerry Liu
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publi... | [
"llama_index.schema.Document"
] | [((14702, 14755), 'logging.debug', 'log.debug', (['"""downloading file using OpenDAL: %s"""', 'path'], {}), "('downloading file using OpenDAL: %s', path)\n", (14711, 14755), True, 'import logging as log\n'), ((14765, 14796), 'typing.cast', 'cast', (['opendal.AsyncOperator', 'op'], {}), '(opendal.AsyncOperator, op)\n', ... |
from langchain.agents import (
initialize_agent,
Tool,
AgentType
)
from llama_index.callbacks import (
CallbackManager,
LlamaDebugHandler
)
from llama_index.node_parser.simple import SimpleNodeParser
from llama_index import (
VectorStoreIndex,
SummaryIndex,
SimpleDirectoryReader,
ServiceConte... | [
"llama_index.callbacks.LlamaDebugHandler",
"llama_index.StorageContext.from_defaults",
"llama_index.VectorStoreIndex",
"llama_index.SimpleDirectoryReader",
"llama_index.node_parser.simple.SimpleNodeParser.from_defaults",
"llama_index.callbacks.CallbackManager",
"llama_index.SummaryIndex",
"llama_index... | [((398, 456), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (417, 456), False, 'import logging\n'), ((529, 545), 'os.getenv', 'os.getenv', (['"""LLM"""'], {}), "('LLM')\n", (538, 545), False, 'import os\n'), ((1217, 12... |
from llama_index import DiscordReader
from llama_index import download_loader
import os
import nest_asyncio
nest_asyncio.apply()
from llama_index import ServiceContext
import openai
import re
import csv
import time
import random
from dotenv import load_dotenv
import os
from llama_index import Document
load_dotenv()
... | [
"llama_index.DiscordReader",
"llama_index.ServiceContext.from_defaults",
"llama_index.download_loader",
"llama_index.Document"
] | [((108, 128), 'nest_asyncio.apply', 'nest_asyncio.apply', ([], {}), '()\n', (126, 128), False, 'import nest_asyncio\n'), ((304, 317), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (315, 317), False, 'from dotenv import load_dotenv\n'), ((337, 365), 'os.environ.get', 'os.environ.get', (['"""OPENAI_API"""'], {})... |
from typing import Union
from llama_index.core import Prompt
from llama_index.core.response_synthesizers import get_response_synthesizer, ResponseMode
from llama_index.core.postprocessor import SimilarityPostprocessor
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.agent.openai import OpenAI... | [
"llama_index.agent.openai.OpenAIAgent.from_tools",
"llama_index.core.Prompt",
"llama_index.core.response_synthesizers.get_response_synthesizer",
"llama_index.llms.openai.OpenAI",
"llama_index.core.llms.ChatMessage",
"llama_index.core.postprocessor.SimilarityPostprocessor"
] | [((2418, 2434), 'app.llama_index_server.chat_message_dao.ChatMessageDao', 'ChatMessageDao', ([], {}), '()\n', (2432, 2434), False, 'from app.llama_index_server.chat_message_dao import ChatMessageDao\n'), ((3036, 3057), 'app.llama_index_server.index_storage.index_storage.index', 'index_storage.index', ([], {}), '()\n', ... |
import streamlit as st
from llama_index import VectorStoreIndex, ServiceContext, Document
from llama_index.llms import OpenAI
import openai
from llama_index import SimpleDirectoryReader
st.set_page_config(page_title="Converse com Resoluções do Bacen, powered by LlamaIndex", page_icon="🦙", layout="centered", initial_s... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.llms.OpenAI",
"llama_index.SimpleDirectoryReader"
] | [((187, 366), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""Converse com Resoluções do Bacen, powered by LlamaIndex"""', 'page_icon': '"""🦙"""', 'layout': '"""centered"""', 'initial_sidebar_state': '"""auto"""', 'menu_items': 'None'}), "(page_title=\n 'Converse com Resoluções do Bacen, ... |
from llama_index.core.tools import FunctionTool
def calculate_average(*values):
"""
Calculates the average of the provided values.
"""
return sum(values) / len(values)
average_tool = FunctionTool.from_defaults(
fn=calculate_average
)
| [
"llama_index.core.tools.FunctionTool.from_defaults"
] | [((200, 248), 'llama_index.core.tools.FunctionTool.from_defaults', 'FunctionTool.from_defaults', ([], {'fn': 'calculate_average'}), '(fn=calculate_average)\n', (226, 248), False, 'from llama_index.core.tools import FunctionTool\n')] |
#ingest uploaded documents
from global_settings import STORAGE_PATH, INDEX_STORAGE, CACHE_FILE
from logging_functions import log_action
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.ingestion import IngestionPipeline, IngestionCache
from llama_index.core.node_parser import T... | [
"llama_index.core.extractors.SummaryExtractor",
"llama_index.core.ingestion.IngestionCache.from_persist_path",
"llama_index.core.SimpleDirectoryReader",
"llama_index.core.node_parser.TokenTextSplitter",
"llama_index.embeddings.openai.OpenAIEmbedding"
] | [((644, 711), 'logging_functions.log_action', 'log_action', (['f"""File \'{doc.id_}\' uploaded user"""'], {'action_type': '"""UPLOAD"""'}), '(f"File \'{doc.id_}\' uploaded user", action_type=\'UPLOAD\')\n', (654, 711), False, 'from logging_functions import log_action\n'), ((786, 830), 'llama_index.core.ingestion.Ingest... |
import tiktoken
from llama_index.core import TreeIndex, SimpleDirectoryReader, Settings
from llama_index.core.llms.mock import MockLLM
from llama_index.core.callbacks import CallbackManager, TokenCountingHandler
llm = MockLLM(max_tokens=256)
token_counter = TokenCountingHandler(
tokenizer=tiktoken.encoding_for_mod... | [
"llama_index.core.TreeIndex.from_documents",
"llama_index.core.callbacks.CallbackManager",
"llama_index.core.SimpleDirectoryReader",
"llama_index.core.llms.mock.MockLLM"
] | [((219, 242), 'llama_index.core.llms.mock.MockLLM', 'MockLLM', ([], {'max_tokens': '(256)'}), '(max_tokens=256)\n', (226, 242), False, 'from llama_index.core.llms.mock import MockLLM\n'), ((368, 400), 'llama_index.core.callbacks.CallbackManager', 'CallbackManager', (['[token_counter]'], {}), '([token_counter])\n', (383... |
import torch
from langchain.llms.base import LLM
from llama_index import SimpleDirectoryReader, LangchainEmbedding, GPTListIndex, PromptHelper
from llama_index import LLMPredictor, ServiceContext
from transformers import pipeline
from typing import Optional, List, Mapping, Any
"""
使用自定义 LLM 模型,您只需要实现Langchain 中的LLM类。您... | [
"llama_index.PromptHelper",
"llama_index.ServiceContext.from_defaults",
"llama_index.GPTListIndex.from_documents",
"llama_index.SimpleDirectoryReader"
] | [((616, 675), 'llama_index.PromptHelper', 'PromptHelper', (['max_input_size', 'num_output', 'max_chunk_overlap'], {}), '(max_input_size, num_output, max_chunk_overlap)\n', (628, 675), False, 'from llama_index import SimpleDirectoryReader, LangchainEmbedding, GPTListIndex, PromptHelper\n'), ((1429, 1520), 'llama_index.S... |
import time, ast, requests, warnings
import numpy as np
from llama_index import Document, ServiceContext, VectorStoreIndex
from llama_index.storage.storage_context import StorageContext
from llama_index.vector_stores import MilvusVectorStore
from llama_index.node_parser import SentenceWindowNodeParser, HierarchicalNo... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.node_parser.get_leaf_nodes",
"llama_index.ServiceContext.from_defaults",
"llama_index.storage.storage_context.StorageContext.from_defaults",
"llama_index.node_parser.HierarchicalNodeParser.from_defaults",
"llama_index.VectorStoreIndex",
"llama_... | [((484, 517), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (507, 517), False, 'import time, ast, requests, warnings\n'), ((611, 743), 'llama_index.node_parser.SentenceWindowNodeParser.from_defaults', 'SentenceWindowNodeParser.from_defaults', ([], {'window_size': '(5)', '... |
"""Llama Dataset Class."""
import asyncio
import time
from typing import List, Optional
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.bridge.pydantic import Field
from llama_index.core.llama_dataset.base import (
BaseLlamaDataExample,
BaseLlamaDataset,
BaseLlama... | [
"llama_index.core.bridge.pydantic.Field"
] | [((764, 909), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'str', 'description': '"""The generated (predicted) response that can be compared to a reference (ground-truth) answer."""'}), "(default_factory=str, description=\n 'The generated (predicted) response that can be compared to a ... |
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseGen,
MessageRole,
)
from llama_index.core.types import TokenGen
def response_gen_from_query_engine(response_gen: TokenGen) -> ChatResponseGen:
response_str = ""
for token in response_gen:
response_str... | [
"llama_index.core.base.llms.types.ChatMessage"
] | [((378, 439), 'llama_index.core.base.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response_str'}), '(role=MessageRole.ASSISTANT, content=response_str)\n', (389, 439), False, 'from llama_index.core.base.llms.types import ChatMessage, ChatResponse, ChatResponseGen, MessageRol... |
from typing import Dict, Any
import asyncio
# Create a new event loop
loop = asyncio.new_event_loop()
# Set the event loop as the current event loop
asyncio.set_event_loop(loop)
from llama_index import (
VectorStoreIndex,
ServiceContext,
download_loader,
)
from llama_index.llama_pack.base import BaseLlam... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.llms.OpenAI",
"llama_index.download_loader"
] | [((78, 102), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ([], {}), '()\n', (100, 102), False, 'import asyncio\n'), ((151, 179), 'asyncio.set_event_loop', 'asyncio.set_event_loop', (['loop'], {}), '(loop)\n', (173, 179), False, 'import asyncio\n'), ((420, 607), 'streamlit.set_page_config', 'st.set_page_config', ... |
"""DashScope llm api."""
from http import HTTPStatus
from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.legacy.bridge.pydantic import Field
from llama_index.legacy.callbacks import CallbackManager
from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS, DEFAULT_TEMPERATURE
from llama_... | [
"llama_index.legacy.core.llms.types.CompletionResponse",
"llama_index.legacy.llms.dashscope_utils.chat_message_to_dashscope_messages",
"llama_index.legacy.llms.dashscope_utils.dashscope_response_to_chat_response",
"llama_index.legacy.core.llms.types.LLMMetadata",
"llama_index.legacy.llms.base.llm_chat_callb... | [((2272, 2350), 'dashscope.Generation.call', 'Generation.call', ([], {'model': 'model', 'messages': 'messages', 'api_key': 'api_key'}), '(model=model, messages=messages, api_key=api_key, **parameters)\n', (2287, 2350), False, 'from dashscope import Generation\n'), ((2443, 2540), 'llama_index.legacy.bridge.pydantic.Fiel... |
import os
from llama_index import download_loader
from llama_index.node_parser import SimpleNodeParser
from llama_index import GPTVectorStoreIndex
download_loader("GithubRepositoryReader")
from llama_index.readers.llamahub_modules.github_repo import (
GithubRepositoryReader,
GithubClient,
)
# Initialize the... | [
"llama_index.readers.llamahub_modules.github_repo.GithubRepositoryReader",
"llama_index.node_parser.SimpleNodeParser",
"llama_index.GPTVectorStoreIndex",
"llama_index.download_loader"
] | [((149, 190), 'llama_index.download_loader', 'download_loader', (['"""GithubRepositoryReader"""'], {}), "('GithubRepositoryReader')\n", (164, 190), False, 'from llama_index import download_loader\n'), ((409, 706), 'llama_index.readers.llamahub_modules.github_repo.GithubRepositoryReader', 'GithubRepositoryReader', (['gi... |
"""Relevancy evaluation."""
from __future__ import annotations
import asyncio
from typing import Any, Optional, Sequence, Union
from llama_index.core import ServiceContext
from llama_index.core.evaluation.base import BaseEvaluator, EvaluationResult
from llama_index.core.indices import SummaryIndex
from llama_index.co... | [
"llama_index.core.prompts.PromptTemplate",
"llama_index.core.settings.llm_from_settings_or_context",
"llama_index.core.evaluation.base.EvaluationResult",
"llama_index.core.schema.Document",
"llama_index.core.indices.SummaryIndex.from_documents"
] | [((620, 974), 'llama_index.core.prompts.PromptTemplate', 'PromptTemplate', (['"""Your task is to evaluate if the response for the query is in line with the context information provided.\nYou have two options to answer. Either YES/ NO.\nAnswer - YES, if the response for the query is in line with context informat... |
"""Base tool spec class."""
import asyncio
from inspect import signature
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.tools.function_tool import FunctionTool
from llama_index.core.tools.types import ... | [
"llama_index.core.tools.function_tool.FunctionTool.from_defaults",
"llama_index.core.tools.types.ToolMetadata"
] | [((2092, 2161), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', ([], {'name': 'name', 'description': 'description', 'fn_schema': 'fn_schema'}), '(name=name, description=description, fn_schema=fn_schema)\n', (2104, 2161), False, 'from llama_index.core.tools.types import ToolMetadata\n'), ((4457, 4481), 'asy... |
"""Tree Index inserter."""
from typing import Optional, Sequence
from llama_index.core.data_structs.data_structs import IndexGraph
from llama_index.core.indices.prompt_helper import PromptHelper
from llama_index.core.indices.tree.utils import get_numbered_text_from_nodes
from llama_index.core.indices.utils import (
... | [
"llama_index.core.indices.tree.utils.get_numbered_text_from_nodes",
"llama_index.core.settings.llm_from_settings_or_context",
"llama_index.core.storage.docstore.registry.get_default_docstore",
"llama_index.core.indices.utils.extract_numbers_given_response",
"llama_index.core.schema.TextNode",
"llama_index... | [((5228, 5265), 'llama_index.core.indices.utils.get_sorted_node_list', 'get_sorted_node_list', (['cur_graph_nodes'], {}), '(cur_graph_nodes)\n', (5248, 5265), False, 'from llama_index.core.indices.utils import extract_numbers_given_response, get_sorted_node_list\n'), ((1733, 1788), 'llama_index.core.settings.llm_from_s... |
"""JSON node parser."""
import json
from typing import Any, Dict, Generator, List, Optional, Sequence
from llama_index.core.callbacks.base import CallbackManager
from llama_index.core.node_parser.interface import NodeParser
from llama_index.core.node_parser.node_utils import build_nodes_from_splits
from llama_index.co... | [
"llama_index.core.callbacks.base.CallbackManager",
"llama_index.core.utils.get_tqdm_iterable"
] | [((1510, 1566), 'llama_index.core.utils.get_tqdm_iterable', 'get_tqdm_iterable', (['nodes', 'show_progress', '"""Parsing nodes"""'], {}), "(nodes, show_progress, 'Parsing nodes')\n", (1527, 1566), False, 'from llama_index.core.utils import get_tqdm_iterable\n'), ((995, 1014), 'llama_index.core.callbacks.base.CallbackMa... |
import asyncio
import os
import tempfile
import traceback
from datetime import date, datetime
from functools import partial
from pathlib import Path
import aiohttp
import discord
import openai
import tiktoken
from langchain import OpenAI
from langchain.chat_models import ChatOpenAI
from llama_index import (
Beauti... | [
"llama_index.indices.query.query_transform.StepDecomposeQueryTransform",
"llama_index.OpenAIEmbedding",
"llama_index.composability.QASummaryQueryEngineBuilder",
"llama_index.MockEmbedding",
"llama_index.QuestionAnswerPrompt",
"llama_index.ServiceContext.from_defaults",
"llama_index.query_engine.Retrieve... | [((1193, 1226), 'services.environment_service.EnvService.get_max_search_price', 'EnvService.get_max_search_price', ([], {}), '()\n', (1224, 1226), False, 'from services.environment_service import EnvService\n'), ((1404, 1442), 'services.environment_service.EnvService.get_google_search_api_key', 'EnvService.get_google_s... |
import asyncio
import json
import os
import tempfile
import time
from functools import lru_cache
from logging import getLogger
from pathlib import Path
from fastapi import APIRouter, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.responses import HTMLResponse
from typing import List, Dict, ... | [
"llama_index.response_synthesizers.TreeSummarize",
"llama_index.vector_stores.types.MetadataInfo",
"llama_index.query_pipeline.QueryPipeline",
"llama_index.PromptTemplate",
"llama_index.indices.vector_store.retrievers.VectorIndexRetriever",
"llama_index.schema.NodeWithScore"
] | [((2834, 2845), 'logging.getLogger', 'getLogger', ([], {}), '()\n', (2843, 2845), False, 'from logging import getLogger\n'), ((2859, 2881), 'snowflake.SnowflakeGenerator', 'SnowflakeGenerator', (['(42)'], {}), '(42)\n', (2877, 2881), False, 'from snowflake import SnowflakeGenerator\n'), ((2892, 2903), 'fastapi.APIRoute... |
from dotenv import load_dotenv
import cv2
import numpy as np
import os
import streamlit as st
from llama_index import SimpleDirectoryReader
from pydantic_llm import (
pydantic_llm,
DamagedParts,
damages_initial_prompt_str,
ConditionsReport,
conditions_report_initial_prompt_str,
)
import pandas as pd... | [
"llama_index.multi_modal_llms.openai.OpenAIMultiModal",
"llama_index.SimpleDirectoryReader"
] | [((557, 607), 'streamlit_modal.Modal', 'Modal', (['"""Damage Report"""'], {'key': '"""demo"""', 'max_width': '(1280)'}), "('Damage Report', key='demo', max_width=1280)\n", (562, 607), False, 'from streamlit_modal import Modal\n'), ((912, 925), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (923, 925), False, 'f... |
from typing import TYPE_CHECKING, Any, Optional
from llama_index.legacy.core.base_query_engine import BaseQueryEngine
if TYPE_CHECKING:
from llama_index.legacy.langchain_helpers.agents.tools import (
LlamaIndexTool,
)
from llama_index.legacy.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput
... | [
"llama_index.legacy.langchain_helpers.agents.tools.LlamaIndexTool.from_tool_config",
"llama_index.legacy.tools.types.ToolMetadata",
"llama_index.legacy.langchain_helpers.agents.tools.IndexToolConfig"
] | [((1408, 1456), 'llama_index.legacy.tools.types.ToolMetadata', 'ToolMetadata', ([], {'name': 'name', 'description': 'description'}), '(name=name, description=description)\n', (1420, 1456), False, 'from llama_index.legacy.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput\n'), ((3568, 3683), 'llama_index.legacy.... |
from llama_index.core.llama_dataset import download_llama_dataset
from llama_index.core.llama_pack import download_llama_pack
from llama_index.core import VectorStoreIndex
async def main():
# DOWNLOAD LLAMADATASET
rag_dataset, documents = download_llama_dataset(
"EvaluatingLlmSurveyPaperDataset", "./d... | [
"llama_index.core.llama_dataset.download_llama_dataset",
"llama_index.core.llama_pack.download_llama_pack",
"llama_index.core.VectorStoreIndex.from_documents"
] | [((249, 316), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""EvaluatingLlmSurveyPaperDataset"""', '"""./data"""'], {}), "('EvaluatingLlmSurveyPaperDataset', './data')\n", (271, 316), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((375, 427), 'll... |
# !pip install llama-index faiss-cpu llama-index-vector-stores-faiss
import faiss
from llama_index.core import (
SimpleDirectoryReader,
VectorStoreIndex,
StorageContext,
)
from llama_index.vector_stores.faiss import FaissVectorStore
from llama_index.core import get_response_synthesizer
from llama_index.c... | [
"llama_index.core.StorageContext.from_defaults",
"llama_index.core.retrievers.VectorIndexRetriever",
"llama_index.core.prompts.base.PromptTemplate",
"llama_index.core.query_engine.RetrieverQueryEngine",
"llama_index.vector_stores.faiss.FaissVectorStore",
"llama_index.core.VectorStoreIndex.from_documents",... | [((1083, 1103), 'faiss.IndexFlatL2', 'faiss.IndexFlatL2', (['d'], {}), '(d)\n', (1100, 1103), False, 'import faiss\n'), ((1150, 1191), 'llama_index.vector_stores.faiss.FaissVectorStore', 'FaissVectorStore', ([], {'faiss_index': 'faiss_index'}), '(faiss_index=faiss_index)\n', (1166, 1191), False, 'from llama_index.vecto... |
from dotenv import load_dotenv
from llama_index.llms import OpenAI
from llama_index.prompts import PromptTemplate
from retriever import run_retrieval
import nest_asyncio
import asyncio
nest_asyncio.apply()
async def acombine_results(
texts,
query_str,
qa_prompt,
llm,
cur_prompt_list,
num_c... | [
"llama_index.llms.OpenAI",
"llama_index.prompts.PromptTemplate"
] | [((189, 209), 'nest_asyncio.apply', 'nest_asyncio.apply', ([], {}), '()\n', (207, 209), False, 'import nest_asyncio\n'), ((2126, 2160), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""'}), "(model_name='gpt-3.5-turbo')\n", (2132, 2160), False, 'from llama_index.llms import OpenAI\n'), ((217... |
from pathlib import Path
from llama_index import download_loader
from llama_index import SimpleDirectoryReader
PDFReader = download_loader("PDFReader")
def getdocument(filename : str,filetype:str):
if filetype == "pdf":
loader = PDFReader()
elif filetype == "txt":
loader = SimpleDirectoryReade... | [
"llama_index.download_loader",
"llama_index.SimpleDirectoryReader"
] | [((124, 152), 'llama_index.download_loader', 'download_loader', (['"""PDFReader"""'], {}), "('PDFReader')\n", (139, 152), False, 'from llama_index import download_loader\n'), ((300, 334), 'llama_index.SimpleDirectoryReader', 'SimpleDirectoryReader', (['"""./example"""'], {}), "('./example')\n", (321, 334), False, 'from... |
import faiss
import openai
from llama_index.readers.file.epub_parser import EpubParser
# create an index with the text and save it to disk in data/indexes
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor
from langchain.chat_models import ChatOpenAI
from llama_index import GPTTreeIndex
i... | [
"llama_index.GPTSimpleVectorIndex",
"llama_index.SimpleDirectoryReader"
] | [((1175, 1217), 'llama_index.GPTSimpleVectorIndex', 'GPTSimpleVectorIndex', ([], {'documents': 'self._docs'}), '(documents=self._docs)\n', (1195, 1217), False, 'from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor\n'), ((1057, 1136), 'llama_index.SimpleDirectoryReader', 'SimpleDirectoryRead... |
# -*- coding: utf-8 -*-
# @place: Pudong, Shanghai
# @file: query_rewrite_ensemble_retriever.py
# @time: 2023/12/28 13:49
# -*- coding: utf-8 -*-
# @place: Pudong, Shanghai
# @file: ensemble_retriever.py
# @time: 2023/12/26 18:50
import json
from typing import List
from operator import itemgetter
from llama_index.sche... | [
"llama_index.schema.TextNode"
] | [((3476, 3493), 'faiss.IndexFlatIP', 'IndexFlatIP', (['(1536)'], {}), '(1536)\n', (3487, 3493), False, 'from faiss import IndexFlatIP\n'), ((3693, 3709), 'pprint.pprint', 'pprint', (['t_result'], {}), '(t_result)\n', (3699, 3709), False, 'from pprint import pprint\n'), ((942, 1030), 'custom_retriever.vector_store_retri... |
"""Utils for jupyter notebook."""
import os
from io import BytesIO
from typing import Any, Dict, List, Tuple
import matplotlib.pyplot as plt
import requests
from IPython.display import Markdown, display
from llama_index.core.base.response.schema import Response
from llama_index.core.img_utils import b64_2_img
from lla... | [
"llama_index.core.img_utils.b64_2_img"
] | [((723, 741), 'llama_index.core.img_utils.b64_2_img', 'b64_2_img', (['img_str'], {}), '(img_str)\n', (732, 741), False, 'from llama_index.core.img_utils import b64_2_img\n'), ((770, 782), 'IPython.display.display', 'display', (['img'], {}), '(img)\n', (777, 782), False, 'from IPython.display import Markdown, display\n'... |
from typing import Optional, Type
from llama_index.legacy.download.module import (
LLAMA_HUB_URL,
MODULE_TYPE,
download_llama_module,
track_download,
)
from llama_index.legacy.llama_pack.base import BaseLlamaPack
def download_llama_pack(
llama_pack_class: str,
download_dir: str,
llama_hub... | [
"llama_index.legacy.download.module.download_llama_module",
"llama_index.legacy.download.module.track_download"
] | [((887, 1134), 'llama_index.legacy.download.module.download_llama_module', 'download_llama_module', (['llama_pack_class'], {'llama_hub_url': 'llama_hub_url', 'refresh_cache': 'refresh_cache', 'custom_path': 'download_dir', 'library_path': '"""llama_packs/library.json"""', 'disable_library_cache': '(True)', 'override_pa... |
# Debug stuff
#import os
#import readline
#print("Current Working Directory:", os.getcwd())
#env_var = os.getenv('OPENAI_API_KEY')
#print(env_var)
# Sets llama-index
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.st... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.StorageContext.from_defaults",
"llama_index.load_index_from_storage",
"llama_index.SimpleDirectoryReader"
] | [((194, 253), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.DEBUG'}), '(stream=sys.stdout, level=logging.DEBUG)\n', (213, 253), False, 'import logging\n'), ((285, 325), 'logging.StreamHandler', 'logging.StreamHandler', ([], {'stream': 'sys.stdout'}), '(stream=sys.stdout)\... |
import os, streamlit as st
# Uncomment to specify your OpenAI API key here (local testing only, not in production!), or add corresponding environment variable (recommended)
# os.environ['OPENAI_API_KEY']= ""
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, PromptHelper, ServiceContex... | [
"llama_index.PromptHelper",
"llama_index.GPTSimpleVectorIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.SimpleDirectoryReader"
] | [((396, 417), 'streamlit.title', 'st.title', (['"""Ask Llama"""'], {}), "('Ask Llama')\n", (404, 417), True, 'import os, streamlit as st\n'), ((426, 500), 'streamlit.text_input', 'st.text_input', (['"""What would you like to ask? (source: data/Create.txt)"""', '""""""'], {}), "('What would you like to ask? (source: dat... |
import os, streamlit as st
# Uncomment to specify your OpenAI API key here (local testing only, not in production!), or add corresponding environment variable (recommended)
# os.environ['OPENAI_API_KEY']= ""
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, PromptHelper
from langchain... | [
"llama_index.PromptHelper",
"llama_index.GPTSimpleVectorIndex",
"llama_index.SimpleDirectoryReader"
] | [((635, 694), 'llama_index.PromptHelper', 'PromptHelper', (['max_input_size', 'num_output', 'max_chunk_overlap'], {}), '(max_input_size, num_output, max_chunk_overlap)\n', (647, 694), False, 'from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, PromptHelper\n'), ((801, 895), 'llama_index.G... |
from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.response.schema import RESPONSE_TYPE, Response
from llama_index.core.callbacks.base import CallbackManager
from llama_index.core.callbacks.schema import CBEventType, EventPayload
from llama_index.core.indices.multi_modal import Mu... | [
"llama_index.core.callbacks.base.CallbackManager",
"llama_index.multi_modal_llms.openai.OpenAIMultiModal"
] | [((3353, 3372), 'llama_index.core.callbacks.base.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (3368, 3372), False, 'from llama_index.core.callbacks.base import CallbackManager\n'), ((2707, 2774), 'llama_index.multi_modal_llms.openai.OpenAIMultiModal', 'OpenAIMultiModal', ([], {'model': '"""gpt-4-vision-... |
import json
from typing import Sequence
from llama_index.legacy.prompts.base import PromptTemplate
from llama_index.legacy.question_gen.types import SubQuestion
from llama_index.legacy.tools.types import ToolMetadata
# deprecated, kept for backward compatibility
SubQuestionPrompt = PromptTemplate
def build_tools_te... | [
"llama_index.legacy.question_gen.types.SubQuestion",
"llama_index.legacy.tools.types.ToolMetadata"
] | [((465, 497), 'json.dumps', 'json.dumps', (['tools_dict'], {'indent': '(4)'}), '(tools_dict, indent=4)\n', (475, 497), False, 'import json\n'), ((817, 923), 'llama_index.legacy.tools.types.ToolMetadata', 'ToolMetadata', ([], {'name': '"""uber_10k"""', 'description': '"""Provides information about Uber financials for ye... |
import os
import openai
from typing import Union
import collections
from IPython.display import Markdown, display
# access/create the .env file in the project dir for getting API keys. Create a .env file in the project/repository root,
# and add your own API key like "OPENAI_API_KEY = <your key>" without any quotes, ... | [
"llama_index.SQLDatabase",
"llama_index.ServiceContext.from_defaults",
"llama_index.objects.SQLTableSchema",
"llama_index.objects.ObjectIndex.from_objects",
"llama_index.set_global_service_context",
"llama_index.logger.LlamaLogger",
"llama_index.objects.SQLTableNodeMapping"
] | [((517, 530), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (528, 530), False, 'from dotenv import load_dotenv\n'), ((2230, 2243), 'llama_index.logger.LlamaLogger', 'LlamaLogger', ([], {}), '()\n', (2241, 2243), False, 'from llama_index.logger import LlamaLogger\n'), ((2277, 2304), 'os.getenv', 'os.getenv', ([... |
#
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | [
"llama_index.VectorStoreIndex.from_vector_store",
"llama_index.vector_stores.CassandraVectorStore"
] | [((1311, 1342), 'base64.b64decode', 'base64.b64decode', (['secure_bundle'], {}), '(secure_bundle)\n', (1327, 1342), False, 'import base64\n'), ((1765, 1955), 'llama_index.vector_stores.CassandraVectorStore', 'CassandraVectorStore', ([], {'session': 'self.session', 'keyspace': "self.config['cassandra']['keyspace']", 'ta... |
import os
from django.conf import settings
from postdata.models import UploadedFile
from .create_node import *
import llama_index
from llama_index.llms import OpenAI
from llama_index import (VectorStoreIndex,
ServiceContext,
set_global_service_context,
... | [
"llama_index.set_global_service_context",
"llama_index.ServiceContext.from_defaults",
"llama_index.VectorStoreIndex",
"llama_index.set_global_handler"
] | [((334, 374), 'llama_index.set_global_handler', 'llama_index.set_global_handler', (['"""simple"""'], {}), "('simple')\n", (364, 374), False, 'import llama_index\n'), ((544, 581), 'llama_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'llm': 'llm'}), '(llm=llm)\n', (572, 581), False, 'from lla... |
"""Base retrieval abstractions."""
import asyncio
from abc import abstractmethod
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple
from llama_index.core.bridge.pydantic import BaseModel, Field
from llama_index.core.evaluation.retrieval.metrics import resolve_metrics
from llama_index.core.evalu... | [
"llama_index.core.evaluation.retrieval.metrics.resolve_metrics",
"llama_index.core.bridge.pydantic.Field"
] | [((1364, 1402), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Query string"""'}), "(..., description='Query string')\n", (1369, 1402), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1433, 1471), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'],... |
"""Code splitter."""
from typing import Any, Callable, List, Optional
from llama_index.legacy.bridge.pydantic import Field, PrivateAttr
from llama_index.legacy.callbacks.base import CallbackManager
from llama_index.legacy.callbacks.schema import CBEventType, EventPayload
from llama_index.legacy.node_parser.interface ... | [
"llama_index.legacy.bridge.pydantic.PrivateAttr",
"llama_index.legacy.bridge.pydantic.Field",
"llama_index.legacy.callbacks.base.CallbackManager"
] | [((779, 849), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The programming language of the code being split."""'}), "(description='The programming language of the code being split.')\n", (784, 849), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((887, 99... |
import asyncio
from llama_index.core.llama_dataset import download_llama_dataset
from llama_index.core.llama_pack import download_llama_pack
from llama_index.core import VectorStoreIndex
from llama_index.llms import OpenAI
async def main():
# DOWNLOAD LLAMADATASET
rag_dataset, documents = download_llama_data... | [
"llama_index.core.llama_dataset.download_llama_dataset",
"llama_index.core.llama_pack.download_llama_pack",
"llama_index.core.VectorStoreIndex.from_documents",
"llama_index.llms.OpenAI"
] | [((301, 376), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""DocugamiKgRagSec10Q"""', '"""./docugami_kg_rag_sec_10_q"""'], {}), "('DocugamiKgRagSec10Q', './docugami_kg_rag_sec_10_q')\n", (323, 376), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ... |
import os
import torch
import json
import argparse
from datasets import load_dataset
from llama_index import GPTVectorStoreIndex, Document, ServiceContext
from llama_index.indices.prompt_helper import PromptHelper
from transformers import AutoTokenizer
import openai
import tiktoken
#import GPUtil
stopped_num = 10000000... | [
"llama_index.indices.prompt_helper.PromptHelper",
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.Document"
] | [((783, 808), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (806, 808), False, 'import argparse\n'), ((1533, 1569), 'tiktoken.get_encoding', 'tiktoken.get_encoding', (['encoding_name'], {}), '(encoding_name)\n', (1554, 1569), False, 'import tiktoken\n'), ((1870, 1988), 'llama_index.indices.pro... |
# inspired by: https://github.com/rushic24/langchain-remember-me-llm/
# MIT license
import torch
from json_database import JsonStorageXDG
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from langchain.llms.base import LLM
from llama_index import Document
from llama_index import LLMPredictor, ServiceC... | [
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.Document",
"llama_index.LangchainEmbedding"
] | [((541, 570), 'json_database.JsonStorageXDG', 'JsonStorageXDG', (['"""personalLLM"""'], {}), "('personalLLM')\n", (555, 570), False, 'from json_database import JsonStorageXDG\n'), ((1152, 1263), 'transformers.pipeline', 'pipeline', (['"""text2text-generation"""'], {'model': 'model_name', 'device': '(0)', 'model_kwargs'... |
from dotenv import load_dotenv
import os.path
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
StorageContext,
load_index_from_storage,
)
import logging
import sys
load_dotenv()
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.Str... | [
"llama_index.core.StorageContext.from_defaults",
"llama_index.core.load_index_from_storage",
"llama_index.core.VectorStoreIndex.from_documents",
"llama_index.core.SimpleDirectoryReader"
] | [((204, 217), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (215, 217), False, 'from dotenv import load_dotenv\n'), ((219, 277), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (238, 277), False, 'import logging... |
"""Table node mapping."""
from typing import Any, Dict, Optional, Sequence
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.objects.base_node_mapping import (
DEFAULT_PERSIST_DIR,
DEFAULT_PERSIST_FNAME,
BaseObjectNodeMapping,
)
from llama_index.core.schema import BaseNode, Text... | [
"llama_index.core.schema.TextNode"
] | [((1821, 1968), 'llama_index.core.schema.TextNode', 'TextNode', ([], {'text': 'table_text', 'metadata': 'metadata', 'excluded_embed_metadata_keys': "['name', 'context']", 'excluded_llm_metadata_keys': "['name', 'context']"}), "(text=table_text, metadata=metadata, excluded_embed_metadata_keys=[\n 'name', 'context'], ... |
import logging
from typing import Any, Dict, Generator, List, Optional, Tuple, Type, Union, cast
from llama_index.legacy.agent.openai.utils import resolve_tool_choice
from llama_index.legacy.llms.llm import LLM
from llama_index.legacy.llms.openai import OpenAI
from llama_index.legacy.llms.openai_utils import OpenAIToo... | [
"llama_index.legacy.agent.openai.utils.resolve_tool_choice",
"llama_index.legacy.llms.openai_utils.to_openai_tool",
"llama_index.legacy.llms.openai.OpenAI",
"llama_index.legacy.prompts.base.PromptTemplate",
"llama_index.legacy.program.utils.create_list_model"
] | [((619, 646), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (636, 646), False, 'import logging\n'), ((914, 950), 'llama_index.legacy.agent.openai.utils.resolve_tool_choice', 'resolve_tool_choice', (["schema['title']"], {}), "(schema['title'])\n", (933, 950), False, 'from llama_index.lega... |
# use SQLAlchemy to setup a simple sqlite db
from sqlalchemy import (Column, Integer, MetaData, String, Table, column,
create_engine, select)
engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()
# create a toy city_stats table
table_name = "city_stats"
city_stats_table = Tabl... | [
"llama_index.SQLDatabase"
] | [((176, 211), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///:memory:"""'], {}), "('sqlite:///:memory:')\n", (189, 211), False, 'from sqlalchemy import Column, Integer, MetaData, String, Table, column, create_engine, select\n'), ((227, 237), 'sqlalchemy.MetaData', 'MetaData', ([], {}), '()\n', (235, 237),... |
from llama_index import SimpleDirectoryReader, GPTSimpleVectorIndex, LLMPredictor, PromptHelper
from langchain import OpenAI
class GPTModel:
def __init__(self, directory_path):
# set maximum input size
self.max_input_size = 4096
# set number of output tokens
self.num_outputs = 2000
... | [
"llama_index.PromptHelper",
"llama_index.GPTSimpleVectorIndex",
"llama_index.SimpleDirectoryReader"
] | [((673, 792), 'llama_index.PromptHelper', 'PromptHelper', (['self.max_input_size', 'self.num_outputs', 'self.max_chunk_overlap'], {'chunk_size_limit': 'self.chunk_size_limit'}), '(self.max_input_size, self.num_outputs, self.max_chunk_overlap,\n chunk_size_limit=self.chunk_size_limit)\n', (685, 792), False, 'from lla... |
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, cast
import httpx
from openai import AsyncOpenAI
from openai import OpenAI as SyncOpenAI
from openai.types.chat import ChatCompletionMessageParam
from openai.types.chat.chat_completion_chunk import (
ChatCompletionChunk,
ChoiceDelta,
... | [
"llama_index.legacy.llms.openai_utils.from_openai_message",
"llama_index.legacy.multi_modal_llms.MultiModalLLMMetadata",
"llama_index.legacy.multi_modal_llms.openai_utils.generate_openai_multi_modal_chat_message",
"llama_index.legacy.bridge.pydantic.Field",
"llama_index.legacy.core.llms.types.ChatMessage",
... | [((1407, 1469), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Multi-Modal model to use from OpenAI."""'}), "(description='The Multi-Modal model to use from OpenAI.')\n", (1412, 1469), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1495, 1552), 'llama... |
import os
from typing import Any
from llama_index import ServiceContext, VectorStoreIndex
from llama_index.embeddings.openai import OpenAIEmbedding, OpenAIEmbeddingMode
from llama_index.prompts import PromptTemplate
from llama_index.indices.query.schema import QueryBundle
from llama_index.llms import OpenAI
from llama... | [
"llama_index.prompts.PromptTemplate",
"llama_index.VectorStoreIndex",
"llama_index.VectorStoreIndex.from_vector_store",
"llama_index.llms.OpenAI",
"llama_index.embeddings.openai.OpenAIEmbedding"
] | [((2518, 2654), 'llama_index.VectorStoreIndex.from_vector_store', 'VectorStoreIndex.from_vector_store', (['docstore.vector_store'], {'service_context': 'self.service_context', 'show_progress': '(True)', 'use_async': '(True)'}), '(docstore.vector_store, service_context=\n self.service_context, show_progress=True, use... |
"""SQL Structured Store."""
from collections import defaultdict
from enum import Enum
from typing import Any, Optional, Sequence, Union
from sqlalchemy import Table
from llama_index.legacy.core.base_query_engine import BaseQueryEngine
from llama_index.legacy.core.base_retriever import BaseRetriever
from llama_index.... | [
"llama_index.legacy.indices.struct_store.container_builder.SQLContextContainerBuilder",
"llama_index.legacy.indices.common.struct_store.sql.SQLStructDatapointExtractor",
"llama_index.legacy.indices.struct_store.sql_query.NLStructStoreQueryEngine",
"llama_index.legacy.indices.struct_store.sql_query.SQLStructSt... | [((5106, 5332), 'llama_index.legacy.indices.common.struct_store.sql.SQLStructDatapointExtractor', 'SQLStructDatapointExtractor', (['self._service_context.llm', 'self.schema_extract_prompt', 'self.output_parser', 'self.sql_database'], {'table_name': 'self._table_name', 'table': 'self._table', 'ref_doc_id_column': 'self.... |
"""Base vector store index query."""
from pathlib import Path
from typing import List, Optional
from llama_index import QueryBundle, StorageContext, load_index_from_storage
from llama_index.data_structs import NodeWithScore, IndexDict
from llama_index.indices.utils import log_vector_store_query_result
from llama_index... | [
"llama_index.vector_stores.FaissVectorStore.from_persist_dir",
"llama_index.token_counter.token_counter.llm_token_counter",
"llama_index.StorageContext.from_defaults",
"llama_index.indices.utils.log_vector_store_query_result",
"llama_index.vector_stores.types.VectorStoreQuery",
"llama_index.data_structs.N... | [((1342, 1371), 'llama_index.token_counter.token_counter.llm_token_counter', 'llm_token_counter', (['"""retrieve"""'], {}), "('retrieve')\n", (1359, 1371), False, 'from llama_index.token_counter.token_counter import llm_token_counter\n'), ((1813, 2059), 'llama_index.vector_stores.types.VectorStoreQuery', 'VectorStoreQu... |
import logging
import sys
import os.path
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
StorageContext,
load_index_from_storage,
)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
# check if s... | [
"llama_index.core.StorageContext.from_defaults",
"llama_index.core.load_index_from_storage",
"llama_index.core.VectorStoreIndex.from_documents",
"llama_index.core.SimpleDirectoryReader"
] | [((173, 232), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.DEBUG'}), '(stream=sys.stdout, level=logging.DEBUG)\n', (192, 232), False, 'import logging\n'), ((264, 304), 'logging.StreamHandler', 'logging.StreamHandler', ([], {'stream': 'sys.stdout'}), '(stream=sys.stdout)\... |
import os
from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader
from IPython.display import Markdown, display
from llama_index import StorageContext, load_index_from_storage
# Set the OPENAI_API_KEY environment variable using the value from st.secrets['OPENAI_API_KEY']
os.environ['OPENAI_API_KEY'] = st.se... | [
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.SimpleDirectoryReader"
] | [((495, 540), 'llama_index.GPTVectorStoreIndex.from_documents', 'GPTVectorStoreIndex.from_documents', (['documents'], {}), '(documents)\n', (529, 540), False, 'from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader\n'), ((400, 429), 'llama_index.SimpleDirectoryReader', 'SimpleDirectoryReader', (['"""data"""... |
from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
from llama_index.embeddings import resolve_embed_model
# Don't Import "from openai import OpenAI". It will panic
from llama_index.llms import OpenAI
# load data
documents = SimpleDirectoryReader("data").load_data()
# bge-m3 embedding mod... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.embeddings.resolve_embed_model",
"llama_index.SimpleDirectoryReader",
"llama_index.llms.OpenAI"
] | [((337, 388), 'llama_index.embeddings.resolve_embed_model', 'resolve_embed_model', (['"""local:BAAI/bge-small-en-v1.5"""'], {}), "('local:BAAI/bge-small-en-v1.5')\n", (356, 388), False, 'from llama_index.embeddings import resolve_embed_model\n'), ((412, 477), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'api_base': '"""h... |
import os
import openai
from dotenv import load_dotenv
from llama_index.embeddings import AzureOpenAIEmbedding, OpenAIEmbedding
from llama_index.llms import AzureOpenAI, OpenAI, OpenAILike
from llama_index.llms.llama_utils import messages_to_prompt
def load_models(args, logger):
llm_service = args.llm_service
... | [
"llama_index.llms.AzureOpenAI",
"llama_index.embeddings.AzureOpenAIEmbedding",
"llama_index.llms.OpenAILike",
"llama_index.llms.OpenAI",
"llama_index.embeddings.OpenAIEmbedding"
] | [((353, 366), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (364, 366), False, 'from dotenv import load_dotenv\n'), ((550, 584), 'os.getenv', 'os.getenv', (['"""AZURE_OPENAI_GPT4_KEY"""'], {}), "('AZURE_OPENAI_GPT4_KEY')\n", (559, 584), False, 'import os\n'), ((1760, 1777), 'llama_index.embeddings.OpenAIEmbedd... |
from llama_index.core.tools import FunctionTool
import os
note_file = os.path.join("data", "notes.txt")
def save_note(note):
if not os.path.exists(note_file):
open(note_file, "w")
with open(note_file, "a") as f:
f.writelines([note + "\n"])
return "note saved"
note_engine = FunctionToo... | [
"llama_index.core.tools.FunctionTool.from_defaults"
] | [((71, 104), 'os.path.join', 'os.path.join', (['"""data"""', '"""notes.txt"""'], {}), "('data', 'notes.txt')\n", (83, 104), False, 'import os\n'), ((309, 448), 'llama_index.core.tools.FunctionTool.from_defaults', 'FunctionTool.from_defaults', ([], {'fn': 'save_note', 'name': '"""note_saver"""', 'description': '"""this ... |
from llama_index import VectorStoreIndex, download_loader, StorageContext
from llama_index.vector_stores import PineconeVectorStore
"""Simple reader that reads wikipedia."""
from typing import Any, List
from llama_index.readers.base import BaseReader
from llama_index.schema import Document
from dotenv import load_do... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.schema.Document",
"llama_index.download_loader"
] | [((366, 379), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (377, 379), False, 'from dotenv import load_dotenv\n'), ((1291, 1325), 'llama_index.download_loader', 'download_loader', (['"""WikipediaReader"""'], {}), "('WikipediaReader')\n", (1306, 1325), False, 'from llama_index import VectorStoreIndex, download... |
# Load indices from disk
from llama_index.core import load_index_from_storage
from llama_index.core import StorageContext
from llama_index.core.tools import QueryEngineTool, ToolMetadata
from llama_index.llms.openai import OpenAI
from llama_index.core.query_engine import SubQuestionQueryEngine
from llama_index.agent.op... | [
"llama_index.agent.openai.OpenAIAgent.from_tools",
"llama_index.core.tools.ToolMetadata",
"llama_index.core.load_index_from_storage",
"llama_index.llms.openai.OpenAI"
] | [((452, 491), 'os.path.join', 'os.path.join', (['script_dir', '"""config.json"""'], {}), "(script_dir, 'config.json')\n", (464, 491), False, 'import os\n'), ((562, 609), 'os.path.join', 'os.path.join', (['script_dir', "config['storage-dir']"], {}), "(script_dir, config['storage-dir'])\n", (574, 609), False, 'import os\... |
import logging
logging.basicConfig(level=logging.CRITICAL)
import os
from pathlib import Path
import openai
from dotenv import load_dotenv
from langchain.chat_models import ChatOpenAI
from llama_index import (
GPTVectorStoreIndex,
LLMPredictor,
ServiceContext,
StorageContext,
download_loader,
... | [
"llama_index.GPTVectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.download_loader",
"llama_index.load_index_from_storage"
] | [((16, 59), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.CRITICAL'}), '(level=logging.CRITICAL)\n', (35, 59), False, 'import logging\n'), ((444, 457), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (455, 457), False, 'from dotenv import load_dotenv\n'), ((644, 729), 'llama_index.Service... |
# uses brave (requires api key) for web search then uses ollama for local embedding and inference, for a cost-free web RAG
# requires ollama to be installed and running
import os
import json
import logging
import sys
import requests
from dotenv import load_dotenv
from requests.adapters import HTTPAdapter
from urllib3.... | [
"llama_index.llms.ollama.Ollama",
"llama_index.tools.brave_search.BraveSearchToolSpec",
"llama_index.embeddings.ollama.OllamaEmbedding",
"llama_index.core.VectorStoreIndex.from_documents",
"llama_index.core.Document"
] | [((660, 706), 'llama_index.embeddings.ollama.OllamaEmbedding', 'OllamaEmbedding', ([], {'model_name': '"""nomic-embed-text"""'}), "(model_name='nomic-embed-text')\n", (675, 706), False, 'from llama_index.embeddings.ollama import OllamaEmbedding\n'), ((814, 860), 'llama_index.llms.ollama.Ollama', 'Ollama', ([], {'model'... |
import tkinter as tk
from tkinter import filedialog
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader
import os
os.environ['OPENAI_API_KEY'] = 'sk-'# Your API key
class MyApp(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
... | [
"llama_index.GPTSimpleVectorIndex",
"llama_index.GPTSimpleVectorIndex.load_from_disk",
"llama_index.SimpleDirectoryReader"
] | [((3123, 3130), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (3128, 3130), True, 'import tkinter as tk\n'), ((505, 591), 'tkinter.Label', 'tk.Label', (['self'], {'text': '"""Document Chatbot"""', 'font': "('Arial', 16, 'bold')", 'bg': '"""#f0f0f0"""'}), "(self, text='Document Chatbot', font=('Arial', 16, 'bold'), bg=\n ... |
"""Composability graphs."""
from typing import Any, Dict, List, Optional, Sequence, Type, cast
from llama_index.legacy.core.base_query_engine import BaseQueryEngine
from llama_index.legacy.data_structs.data_structs import IndexStruct
from llama_index.legacy.indices.base import BaseIndex
from llama_index.legacy.schema... | [
"llama_index.legacy.service_context.ServiceContext.from_defaults",
"llama_index.legacy.query_engine.graph_query_engine.ComposableGraphQueryEngine",
"llama_index.legacy.schema.RelatedNodeInfo"
] | [((4914, 4956), 'llama_index.legacy.query_engine.graph_query_engine.ComposableGraphQueryEngine', 'ComposableGraphQueryEngine', (['self'], {}), '(self, **kwargs)\n', (4940, 4956), False, 'from llama_index.legacy.query_engine.graph_query_engine import ComposableGraphQueryEngine\n'), ((1930, 1960), 'llama_index.legacy.ser... |
from langchain.callbacks import CallbackManager
from llama_index import ServiceContext, PromptHelper, LLMPredictor
from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
from core.embedding.openai_embedding import OpenAIEmbedding
from core.llm.llm_builder import LLMBuilder
class IndexBui... | [
"llama_index.PromptHelper",
"llama_index.LLMPredictor"
] | [((599, 745), 'core.llm.llm_builder.LLMBuilder.to_llm', 'LLMBuilder.to_llm', ([], {'tenant_id': 'tenant_id', 'model_name': '"""text-davinci-003"""', 'temperature': '(0)', 'max_tokens': 'num_output', 'callback_manager': 'callback_manager'}), "(tenant_id=tenant_id, model_name='text-davinci-003',\n temperature=0, max_t... |
#main.py
from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
from llama_index.embeddings import resolve_embed_model
from llama_index.llms import OpenAI
documents = SimpleDirectoryReader("data-qas").load_data()
embed_model = resolve_embed_model("local:BAAI/bge-small-en-v1.5")
llm = OpenAI(... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.embeddings.resolve_embed_model",
"llama_index.SimpleDirectoryReader",
"llama_index.llms.OpenAI"
] | [((254, 305), 'llama_index.embeddings.resolve_embed_model', 'resolve_embed_model', (['"""local:BAAI/bge-small-en-v1.5"""'], {}), "('local:BAAI/bge-small-en-v1.5')\n", (273, 305), False, 'from llama_index.embeddings import resolve_embed_model\n'), ((313, 400), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(... |
"""Langchain memory wrapper (for LlamaIndex)."""
from typing import Any, Dict, List, Optional
from llama_index.core.bridge.langchain import (
AIMessage,
BaseChatMemory,
BaseMessage,
HumanMessage,
)
from llama_index.core.bridge.langchain import BaseMemory as Memory
from llama_index.core.bridge.pydantic... | [
"llama_index.core.bridge.langchain.AIMessage",
"llama_index.core.bridge.langchain.HumanMessage",
"llama_index.core.bridge.pydantic.Field",
"llama_index.core.schema.Document"
] | [((1663, 1690), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (1668, 1690), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((4306, 4333), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict'}), '(default_f... |
import matplotlib.pyplot as plt
import polars as pl
import seaborn as sns
import torch
from llama_index.evaluation import RelevancyEvaluator
from llama_index.llms import HuggingFaceLLM
from llama_index.prompts import PromptTemplate
from tqdm import tqdm
from transformers import BitsAndBytesConfig
from src.common.utils... | [
"llama_index.evaluation.RelevancyEvaluator",
"llama_index.prompts.PromptTemplate"
] | [((376, 415), 'polars.Config.set_tbl_formatting', 'pl.Config.set_tbl_formatting', (['"""NOTHING"""'], {}), "('NOTHING')\n", (404, 415), True, 'import polars as pl\n'), ((416, 441), 'polars.Config.set_tbl_rows', 'pl.Config.set_tbl_rows', (['(4)'], {}), '(4)\n', (438, 441), True, 'import polars as pl\n'), ((535, 579), 's... |
import uuid
from llama_index import (StorageContext, VectorStoreIndex, download_loader,
load_index_from_storage)
from llama_index.memory import ChatMemoryBuffer
def create_index_and_query(transcript_id: str, full_transcription: any):
persist_dir = f'./storage/cache/transcription/{transcr... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.StorageContext.from_defaults",
"llama_index.download_loader",
"llama_index.load_index_from_storage",
"llama_index.memory.ChatMemoryBuffer.from_defaults"
] | [((963, 1011), 'llama_index.memory.ChatMemoryBuffer.from_defaults', 'ChatMemoryBuffer.from_defaults', ([], {'token_limit': '(2000)'}), '(token_limit=2000)\n', (993, 1011), False, 'from llama_index.memory import ChatMemoryBuffer\n'), ((365, 418), 'llama_index.StorageContext.from_defaults', 'StorageContext.from_defaults'... |
import glob
import os
import re
from PIL import Image
from io import BytesIO
from openai import OpenAI
from llama_index.node_parser import MarkdownNodeParser
from llama_index import ServiceContext, VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings import OpenAIEmbedding
from llama_index import downloa... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.node_parser.MarkdownNodeParser",
"llama_index.ServiceContext.from_defaults",
"llama_index.SimpleDirectoryReader",
"llama_index.download_loader",
"llama_index.indices.multi_modal.base.MultiModalVectorStoreIndex.from_documents",
"llama_index.embe... | [((455, 524), 'llama_index.node_parser.MarkdownNodeParser', 'MarkdownNodeParser', ([], {'include_metadata': '(True)', 'include_prev_next_rel': '(True)'}), '(include_metadata=True, include_prev_next_rel=True)\n', (473, 524), False, 'from llama_index.node_parser import MarkdownNodeParser\n'), ((535, 579), 'openai.OpenAI'... |
import streamlit as st
import redirect as rd
import os
import tempfile
import time
from llama_index import StorageContext, LLMPredictor
from llama_index import TreeIndex, load_index_from_storage
from llama_index import ServiceContext
from langchain.prompts import StringPromptTemplate
from typing import List, Union
fr... | [
"llama_index.tools.ToolMetadata",
"llama_index.ServiceContext.from_defaults",
"llama_index.StorageContext.from_defaults",
"llama_index.query_engine.MultiStepQueryEngine.from_defaults",
"llama_index.load_index_from_storage"
] | [((11873, 11906), 'streamlit.set_page_config', 'st.set_page_config', ([], {'layout': '"""wide"""'}), "(layout='wide')\n", (11891, 11906), True, 'import streamlit as st\n'), ((11910, 11941), 'streamlit.title', 'st.title', (['"""Agriculture Web App"""'], {}), "('Agriculture Web App')\n", (11918, 11941), True, 'import str... |
# Required Environment Variables: OPENAI_API_KEY
# Required TavilyAI API KEY for web searches - https://tavily.com/
from llama_index.core import SimpleDirectoryReader
from llama_index.packs.corrective_rag import CorrectiveRAGPack
# load documents
documents = SimpleDirectoryReader("./data").load_data()
# uses the LLM ... | [
"llama_index.packs.corrective_rag.CorrectiveRAGPack",
"llama_index.core.SimpleDirectoryReader"
] | [((387, 454), 'llama_index.packs.corrective_rag.CorrectiveRAGPack', 'CorrectiveRAGPack', (['documents'], {'tavily_ai_apikey': '"""<tavily_ai_apikey>"""'}), "(documents, tavily_ai_apikey='<tavily_ai_apikey>')\n", (404, 454), False, 'from llama_index.packs.corrective_rag import CorrectiveRAGPack\n'), ((260, 291), 'llama_... |
# LLama Index starter example from: https://gpt-index.readthedocs.io/en/latest/getting_started/starter_example.html
# In order to run this, download into data/ Paul Graham's Essay 'What I Worked On' from
# https://github.com/jerryjliu/llama_index/blob/main/examples/paul_graham_essay/data/paul_graham_essay.txt
# curl h... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.node_parser.SimpleNodeParser",
"llama_index.schema.TextNode",
"llama_index.StorageContext.from_defaults",
"llama_index.schema.RelatedNodeInfo",
"llama_index.VectorStoreIndex",
"llama_index.SimpleDirectoryReader",
"llama_index.load_index_from_... | [((789, 802), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (800, 802), False, 'from dotenv import load_dotenv\n'), ((809, 839), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (829, 839), False, 'import pprint\n'), ((970, 1012), 'llama_index.VectorStoreIndex.from_docum... |
import sounddevice as sd
import wavio
import whisper
import openai
from llama_index.llms import LlamaCPP
from llama_index.llms.base import ChatMessage
def record_audio(output_filename, duration, sample_rate):
print("Recording...")
audio_data = sd.rec(int(duration * sample_rate),
... | [
"llama_index.llms.base.ChatMessage",
"llama_index.llms.LlamaCPP"
] | [((366, 375), 'sounddevice.wait', 'sd.wait', ([], {}), '()\n', (373, 375), True, 'import sounddevice as sd\n'), ((498, 564), 'wavio.write', 'wavio.write', (['output_filename', 'audio_data', 'sample_rate'], {'sampwidth': '(2)'}), '(output_filename, audio_data, sample_rate, sampwidth=2)\n', (509, 564), False, 'import wav... |
import argparse
import os
from llama_index import StorageContext, load_index_from_storage
from dotenv import load_dotenv
from llama_index import VectorStoreIndex, SimpleDirectoryReader
def query_data(query: str):
"""Query to a vector database
## argument
Return: return_description
"""
sto... | [
"llama_index.StorageContext.from_defaults",
"llama_index.load_index_from_storage"
] | [((335, 388), 'llama_index.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': '"""./storage"""'}), "(persist_dir='./storage')\n", (363, 388), False, 'from llama_index import StorageContext, load_index_from_storage\n'), ((418, 458), 'llama_index.load_index_from_storage', 'load_index_from... |
from llama_index import SimpleDirectoryReader
from llama_index import ServiceContext
from langchain.chat_models import ChatOpenAI
from llama_index import VectorStoreIndex
from utils import build_sentence_window_index
from utils import build_automerging_index
import sys
import os
import logging
import configparser
c... | [
"llama_index.VectorStoreIndex.from_documents",
"llama_index.ServiceContext.from_defaults",
"llama_index.SimpleDirectoryReader"
] | [((328, 355), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (353, 355), False, 'import configparser\n'), ((2287, 2346), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.DEBUG'}), '(stream=sys.stdout, level=logging.DEBUG)\n', (2306, 2346), False,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.