id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
36,622
from typing import Any, Dict, List, Optional, Sequence, Tuple from llama_index.legacy.core.llms.types import ChatMessage, MessageRole from llama_index.legacy.llms.generic_utils import get_from_param_or_env DEFAULT_ANYSCALE_API_BASE = "https://api.endpoints.anyscale.com/v1" DEFAULT_ANYSCALE_API_VERSION = "" def get_fro...
"Resolve OpenAI credentials. The order of precedence is: 1. param 2. env 3. openai module 4. default
36,623
import asyncio from abc import abstractmethod from contextlib import contextmanager from typing import ( Any, AsyncGenerator, Callable, Generator, Sequence, cast, ) from llama_index.legacy.bridge.pydantic import Field, validator from llama_index.legacy.callbacks import CallbackManager, CBEventTy...
null
36,624
import asyncio from abc import abstractmethod from contextlib import contextmanager from typing import ( Any, AsyncGenerator, Callable, Generator, Sequence, cast, ) from llama_index.legacy.bridge.pydantic import Field, validator from llama_index.legacy.callbacks import CallbackManager, CBEventTy...
null
36,625
from typing import List, Sequence from llama_index.legacy.constants import AI21_J2_CONTEXT_WINDOW, COHERE_CONTEXT_WINDOW from llama_index.legacy.core.llms.types import ChatMessage, LLMMetadata, MessageRole from llama_index.legacy.llms.anyscale_utils import anyscale_modelname_to_contextsize from llama_index.legacy.llms....
null
36,626
from typing import List, Sequence from llama_index.legacy.constants import AI21_J2_CONTEXT_WINDOW, COHERE_CONTEXT_WINDOW from llama_index.legacy.core.llms.types import ChatMessage, LLMMetadata, MessageRole from llama_index.legacy.llms.anyscale_utils import anyscale_modelname_to_contextsize from llama_index.legacy.llms....
null
36,627
from typing import List, Sequence from llama_index.legacy.constants import AI21_J2_CONTEXT_WINDOW, COHERE_CONTEXT_WINDOW from llama_index.legacy.core.llms.types import ChatMessage, LLMMetadata, MessageRole from llama_index.legacy.llms.anyscale_utils import anyscale_modelname_to_contextsize from llama_index.legacy.llms....
Get LLM metadata from llm.
36,629
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_index.legacy.core.llms.type...
null
36,630
import logging from threading import Thread from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Union from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import ( DEFAULT_CONTEXT_WIN...
Convert ChatMessages to keyword arguments for Inference API conversational.
36,631
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 class ToolMetadata: description: str name: Optional[str] = None fn_schema: Optional[Type[B...
null
36,640
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
null
36,641
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Args: model_name(str): the model name of the tokenizer. For instance, fxmarty/tiny-llama-fast-tokenizer.
36,644
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Infer the input to torch.device.
36,647
import json import os import sys from collections import defaultdict from typing import Dict, List import numpy as np import tiktoken def validate_json(data_path: str) -> None: # Load dataset with open(data_path) as f: dataset = [json.loads(line) for line in f] # We can inspect the data quickly by...
null
36,648
import re from dataclasses import dataclass from typing import List, Optional from tqdm.auto import tqdm from llama_index.legacy import VectorStoreIndex, get_tokenizer from llama_index.legacy.llms import ChatMessage, OpenAI from llama_index.legacy.llms.llm import LLM from llama_index.legacy.node_parser import TokenText...
null
36,649
import re from dataclasses import dataclass from typing import List, Optional from tqdm.auto import tqdm from llama_index.legacy import VectorStoreIndex, get_tokenizer from llama_index.legacy.llms import ChatMessage, OpenAI from llama_index.legacy.llms.llm import LLM from llama_index.legacy.node_parser import TokenText...
null
36,650
import random from typing import Any, List, Optional, Tuple from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.finetuning import EmbeddingQAFinetuneDataset from llama_index.legacy.indices.query.embedding_utils import get_top_k_embeddings class CohereRerankerFinetuneDataset(BaseModel): ...
null
36,651
from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Type import torch import transformers from sentence_transformers.util import cos_sim from torch import Tensor, nn from torch.optim import Optimizer from tqdm.autonotebook import trange from llama_index.legacy.embeddings.adapter_utils impor...
Train model.
36,652
import json import re import uuid from typing import Dict, List, Tuple from tqdm import tqdm from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.llms.utils import LLM from llama_index.legacy.schema import MetadataMode, TextNode class EmbeddingQAFinetuneDataset(BaseModel): """Embedding Q...
Generate examples given a set of nodes.
36,653
import argparse from typing import Any, Optional from llama_index.legacy.command_line.rag import RagCLI, default_ragcli_persist_dir from llama_index.legacy.embeddings import OpenAIEmbedding from llama_index.legacy.ingestion import IngestionCache, IngestionPipeline from llama_index.legacy.llama_dataset.download import (...
null
36,654
import argparse from typing import Any, Optional from llama_index.legacy.command_line.rag import RagCLI, default_ragcli_persist_dir from llama_index.legacy.embeddings import OpenAIEmbedding from llama_index.legacy.ingestion import IngestionCache, IngestionPipeline from llama_index.legacy.llama_dataset.download import (...
null
36,655
import argparse from typing import Any, Optional from llama_index.legacy.command_line.rag import RagCLI, default_ragcli_persist_dir from llama_index.legacy.embeddings import OpenAIEmbedding from llama_index.legacy.ingestion import IngestionCache, IngestionPipeline from llama_index.legacy.llama_dataset.download import (...
null
36,656
import asyncio import os import shutil from argparse import ArgumentParser from glob import iglob from pathlib import Path from typing import Any, Callable, Dict, Optional, Union, cast from llama_index.legacy import ( Response, ServiceContext, SimpleDirectoryReader, VectorStoreIndex, ) from llama_index....
null
36,657
import logging from typing import Any, Callable, List, Optional, Tuple, Union from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_SIMILARITY_TOP_K from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.embeddings import BaseEmb...
null
36,658
import logging from typing import Any, Callable, List, Optional, Tuple, Union from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_SIMILARITY_TOP_K from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.embeddings import BaseEmb...
null
36,659
import logging from typing import Callable, List, Optional, cast from nltk.stem import PorterStemmer from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_SIMILARITY_TOP_K from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.in...
null
36,660
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast import llama_index.legacy from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.embeddings.base import BaseEmbedding from llama_inde...
Get default node parser.
36,661
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast import llama_index.legacy from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.embeddings.base import BaseEmbedding from llama_inde...
Get default prompt helper.
36,662
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast import llama_index.legacy from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.embeddings.base import BaseEmbedding from llama_inde...
Helper function to set the global service context.
36,663
from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, cast from llama_index.legacy.callbacks.base_handler import BaseCallbackHandler from llama_index.legacy.callbacks.schema import CBEventType, EventPayload from llama_index.legacy.utilities.token_counting import TokenCounter from lla...
null
36,664
import asyncio import functools import logging from typing import Any, Callable, cast from llama_index.legacy.callbacks.base import CallbackManager logger = logging.getLogger(__name__) class CallbackManager(BaseCallbackHandler, ABC): """ Callback manager that handles callbacks for events within LlamaIndex. ...
Decorator to trace a method. Example: @trace_method("my_trace_id") def my_method(self): pass Assumes that the self instance has a CallbackManager instance in an attribute named `callback_manager`. This can be overridden by passing in a `callback_manager_attr` keyword argument.
36,665
import importlib import uuid from dataclasses import dataclass, field, fields from datetime import datetime from types import ModuleType from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, TypeVar from llama_index.legacy.callbacks.base_handler import BaseCallbackHandler from llama_index.leg...
Generates a random ID. Returns: str: A random ID.
36,666
import importlib import uuid from dataclasses import dataclass, field, fields from datetime import datetime from types import ModuleType from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, TypeVar from llama_index.legacy.callbacks.base_handler import BaseCallbackHandler from llama_index.leg...
Converts a list of BaseDataType to a pandas dataframe. Args: data (Iterable[BaseDataType]): A list of BaseDataType. Returns: DataFrame: The converted pandas dataframe.
36,667
from typing import Any from llama_index.legacy.callbacks.argilla_callback import argilla_callback_handler from llama_index.legacy.callbacks.arize_phoenix_callback import ( arize_phoenix_callback_handler, ) from llama_index.legacy.callbacks.base_handler import BaseCallbackHandler from llama_index.legacy.callbacks.de...
Set global eval handlers.
36,669
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.core.query_pipeline.query_component import ( ChainableMixin, QueryComponent, ) from llama_index.legacy.prompts.mixin import PromptMixin, PromptMixinType f...
null
36,670
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.core.query_pipeline.query_component import ( ChainableMixin, QueryComponent, ) from llama_index.legacy.prompts.mixin import PromptMixin, PromptMixinType f...
null
36,671
import asyncio from abc import abstractmethod from enum import Enum from typing import Any, Callable, Coroutine, List, Optional, Tuple import numpy as np from llama_index.legacy.bridge.pydantic import Field, validator from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema...
Mean aggregation for embeddings.
36,672
from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.query_pipeline.query_component import ( InputKeys, OutputKeys, ...
Get parameters from function. Returns: Tuple[Set[str], Set[str]]: required and optional parameters
36,673
from abc import ABC, abstractmethod from typing import ( Any, Callable, Dict, Generator, List, Optional, Set, Union, cast, get_args, ) from llama_index.legacy.bridge.pydantic import BaseModel, Field from llama_index.legacy.callbacks.base import CallbackManager from llama_index.le...
null
36,674
from typing import Any, List, Type from llama_index.legacy.bridge.pydantic import BaseModel, Field, create_model from llama_index.legacy.llms.llm import LLM from llama_index.legacy.output_parsers.pydantic import PydanticOutputParser from llama_index.legacy.prompts.base import PromptTemplate from llama_index.legacy.type...
Create a list version of an existing Pydantic object.
36,675
from typing import Any, List, Type from llama_index.legacy.bridge.pydantic import BaseModel, Field, create_model from llama_index.legacy.llms.llm import LLM from llama_index.legacy.output_parsers.pydantic import PydanticOutputParser from llama_index.legacy.prompts.base import PromptTemplate from llama_index.legacy.type...
Get a program based on the compatible LLM.
36,676
import random import re import signal from collections import defaultdict from contextlib import contextmanager from typing import Any, Dict, List, Optional, Set, Tuple from llama_index.legacy.program.predefined.evaporate.prompts import ( DEFAULT_EXPECTED_OUTPUT_PREFIX_TMPL, DEFAULT_FIELD_EXTRACT_QUERY_TMPL, ...
Time limit context manager. NOTE: copied from https://github.com/HazyResearch/evaporate.
36,677
import random import re import signal from collections import defaultdict from contextlib import contextmanager from typing import Any, Dict, List, Optional, Set, Tuple from llama_index.legacy.program.predefined.evaporate.prompts import ( DEFAULT_EXPECTED_OUTPUT_PREFIX_TMPL, DEFAULT_FIELD_EXTRACT_QUERY_TMPL, ...
Get function field from attribute. NOTE: copied from https://github.com/HazyResearch/evaporate.
36,678
import random import re import signal from collections import defaultdict from contextlib import contextmanager from typing import Any, Dict, List, Optional, Set, Tuple from llama_index.legacy.program.predefined.evaporate.prompts import ( DEFAULT_EXPECTED_OUTPUT_PREFIX_TMPL, DEFAULT_FIELD_EXTRACT_QUERY_TMPL, ...
Extract field dictionaries.
36,679
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 OpenAITool...
Default OpenAI tool to choose.
36,680
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 OpenAITool...
Extract JSON str from raw string and start index.
36,681
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 OpenAITool...
null
36,682
from llama_index.legacy.llm_predictor.base import BaseLLMPredictor, LLMPredictor from llama_index.legacy.llm_predictor.mock import MockLLMPredictor from llama_index.legacy.llm_predictor.structured import StructuredLLMPredictor from llama_index.legacy.llm_predictor.vellum.predictor import VellumPredictor class BaseLLMP...
Load predictor by class name.
36,683
import re def convert_to_kebab_case(input_string: str) -> str: matches = re.findall( r"/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g", input_string.lower(), ) return "-".join(matches)
null
36,684
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock summary predict.
36,685
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock insert predict.
36,686
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock query select.
36,687
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock query select.
36,688
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock answer.
36,689
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock refine.
36,690
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock keyword extract.
36,691
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock query keyword extract.
36,692
from typing import Any, Dict from deprecated import deprecated from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import LLMMetadata from llam...
Mock knowledge graph triplet extract.
36,693
from llama_index.legacy.extractors.metadata_extractors import ( BaseExtractor, EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor, ) class TitleExtractor(BaseExtractor): """Title extractor. Useful for long documents. Extracts `document_title` ...
null
36,695
import os from typing import TYPE_CHECKING, List, Optional, Union from llama_index.legacy.embeddings.base import BaseEmbedding from llama_index.legacy.embeddings.clip import ClipEmbedding from llama_index.legacy.embeddings.huggingface import HuggingFaceEmbedding from llama_index.legacy.embeddings.huggingface_utils impo...
Save embedding to file.
36,696
import os from typing import TYPE_CHECKING, List, Optional, Union from llama_index.legacy.embeddings.base import BaseEmbedding from llama_index.legacy.embeddings.clip import ClipEmbedding from llama_index.legacy.embeddings.huggingface import HuggingFaceEmbedding from llama_index.legacy.embeddings.huggingface_utils impo...
Load embedding from file. Will only return first embedding in file.
36,697
from typing import Dict, Type from llama_index.legacy.embeddings.base import BaseEmbedding from llama_index.legacy.embeddings.google import GoogleUnivSentEncoderEmbedding from llama_index.legacy.embeddings.huggingface import HuggingFaceEmbedding from llama_index.legacy.embeddings.langchain import LangchainEmbedding fro...
Load Embedding by name.
36,701
from typing import Any, Dict, List, Optional import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.bas...
Get embedding. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,702
from typing import Any, Dict, List, Optional import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.bas...
Asynchronously get embedding. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,703
from typing import Any, Dict, List, Optional import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.bas...
Get embeddings. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,704
from typing import Any, Dict, List, Optional import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.bas...
Asynchronously get embeddings. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,705
from enum import Enum from typing import Any, Dict, List, Optional, Tuple import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.base import BaseEmbedding from ...
Get embedding. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,706
from enum import Enum from typing import Any, Dict, List, Optional, Tuple import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.base import BaseEmbedding from ...
Asynchronously get embedding. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,707
from enum import Enum from typing import Any, Dict, List, Optional, Tuple import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.base import BaseEmbedding from ...
Get embeddings. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,708
from enum import Enum from typing import Any, Dict, List, Optional, Tuple import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.base import BaseEmbedding from ...
Asynchronously get embeddings. NOTE: Copied from OpenAI's embedding utils: https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py Copied here to avoid importing unnecessary dependencies like matplotlib, plotly, scipy, sklearn.
36,709
from enum import Enum from typing import Any, Dict, List, Optional, Tuple import httpx from openai import AsyncOpenAI, OpenAI from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.embeddings.base import BaseEmbedding from ...
Get engine.
36,710
import logging from enum import Enum from http import HTTPStatus from typing import Any, Dict, List, Optional, Union from pydantic import PrivateAttr from llama_index.legacy.embeddings.multi_modal_base import MultiModalEmbedding from llama_index.legacy.schema import ImageType logger = logging.getLogger(__name__) The p...
Call DashScope text embedding. ref: https://help.aliyun.com/zh/dashscope/developer-reference/text-embedding-api-details. Args: model (str): The `DashScopeTextEmbeddingModels` text (Union[str, List[str]]): text or list text to embedding. Raises: ImportError: need import dashscope Returns: List[List[float]]: The list of ...
36,711
import logging from enum import Enum from http import HTTPStatus from typing import Any, Dict, List, Optional, Union from pydantic import PrivateAttr from llama_index.legacy.embeddings.multi_modal_base import MultiModalEmbedding from llama_index.legacy.schema import ImageType logger = logging.getLogger(__name__) The p...
Call DashScope batch text embedding. Args: model (str): The `DashScopeMultiModalEmbeddingModels` url (str): The url of the file to embedding which with lines of text to embedding. Raises: ImportError: Need install dashscope package. Returns: str: The url of the embedding result, format ref: https://help.aliyun.com/zh/d...
36,712
import logging from enum import Enum from http import HTTPStatus from typing import Any, Dict, List, Optional, Union from pydantic import PrivateAttr from llama_index.legacy.embeddings.multi_modal_base import MultiModalEmbedding from llama_index.legacy.schema import ImageType logger = logging.getLogger(__name__) class...
Call DashScope multimodal embedding. ref: https://help.aliyun.com/zh/dashscope/developer-reference/one-peace-multimodal-embedding-api-details. Args: model (str): The `DashScopeBatchTextEmbeddingModels` input (str): The input of the embedding, eg: [{'factor': 1, 'text': '你好'}, {'factor': 2, 'audio': 'https://dashscope.o...
36,713
from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, MessageRole, ) from llama_index.legacy.types import TokenGen class MessageRole(str, Enum): """Message role.""" SYSTEM = "system" USER = "user" ASSISTANT = "assistant" FUNCTION = "function" ...
null
36,714
import asyncio import logging import queue from abc import ABC, abstractmethod from dataclasses import dataclass, field from enum import Enum from threading import Event from typing import AsyncGenerator, Generator, List, Optional, Union from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse...
Utility for ChatMessage responses from OpenAI models.
36,719
import logging from typing import Dict, List, Optional, cast from llama_index.legacy.bridge.pydantic import Field, validator from llama_index.legacy.postprocessor.types import BaseNodePostprocessor from llama_index.legacy.prompts.base import PromptTemplate from llama_index.legacy.response_synthesizers import ( Resp...
Get forward nodes.
36,720
import logging from typing import Dict, List, Optional, cast from llama_index.legacy.bridge.pydantic import Field, validator from llama_index.legacy.postprocessor.types import BaseNodePostprocessor from llama_index.legacy.prompts.base import PromptTemplate from llama_index.legacy.response_synthesizers import ( Resp...
Get backward nodes.
36,721
from __future__ import annotations import asyncio import re from typing import Any, Callable, Optional, Sequence, Tuple from llama_index.legacy import ServiceContext from llama_index.legacy.evaluation.base import BaseEvaluator, EvaluationResult from llama_index.legacy.prompts import BasePromptTemplate, PromptTemplate f...
null
36,722
from __future__ import annotations import asyncio import re from typing import Any, Callable, Optional, Sequence, Tuple from llama_index.legacy import ServiceContext from llama_index.legacy.evaluation.base import BaseEvaluator, EvaluationResult from llama_index.legacy.indices import SummaryIndex from llama_index.legacy...
null
36,723
import asyncio from typing import Any, Dict, List, Optional, Sequence, Tuple, cast from llama_index.legacy.async_utils import asyncio_module from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.evaluatio...
Get aevaluate_response tasks with semaphore.
36,724
import asyncio from typing import Any, Dict, List, Optional, Sequence, Tuple, cast from llama_index.legacy.async_utils import asyncio_module from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.evaluatio...
Get aevaluate tasks with semaphore.
36,725
import asyncio from typing import Any, Dict, List, Optional, Sequence, Tuple, cast from llama_index.legacy.async_utils import asyncio_module from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.evaluatio...
Get aquery tasks with semaphore.
36,726
import json import os import re import string from collections import Counter from shutil import rmtree from typing import Any, Dict, List, Optional, Tuple import requests import tqdm from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.base_retriever import BaseRetriever f...
null
36,727
import json import os import re import string from collections import Counter from shutil import rmtree from typing import Any, Dict, List, Optional, Tuple import requests import tqdm from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.base_retriever import BaseRetriever f...
null
36,728
import asyncio from enum import Enum from typing import Any, Callable, Optional, Sequence, Tuple, Union from llama_index.legacy import ServiceContext from llama_index.legacy.evaluation.base import ( BaseEvaluator, EvaluationResult, ) from llama_index.legacy.prompts import ( BasePromptTemplate, ChatMessa...
null
36,729
import asyncio from collections import defaultdict from typing import Any, List, Optional, Tuple import numpy as np import pandas as pd from llama_index.legacy.async_utils import asyncio_module from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.evaluation.base import Evaluatio...
Get responses. Sync version of aget_responses.
36,730
import asyncio from collections import defaultdict from typing import Any, List, Optional, Tuple import numpy as np import pandas as pd from llama_index.legacy.async_utils import asyncio_module from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.evaluation.base import Evaluatio...
Get results df. Args: eval_results_list (List[EvaluationResult]): List of evaluation results. names (List[str]): Names of the evaluation results. metric_keys (List[str]): List of metric keys to get.
36,731
import asyncio from collections import defaultdict from typing import Any, List, Optional, Tuple import numpy as np import pandas as pd from llama_index.legacy.async_utils import asyncio_module from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.evaluation.base import Evaluatio...
Default parser function for evaluation response. Args: eval_response (str): The response string from the evaluation. Returns: Tuple[float, str]: A tuple containing the score as a float and the reasoning as a string.
36,732
from collections import defaultdict from typing import List, Optional, Tuple import pandas as pd from llama_index.legacy.evaluation import EvaluationResult from llama_index.legacy.evaluation.retrieval.base import RetrievalEvalResult DEFAULT_METRIC_KEYS = ["hit_rate", "mrr"] class RetrievalEvalResult(BaseModel): ""...
Display retrieval results.
36,733
from collections import defaultdict from typing import List, Optional, Tuple import pandas as pd from llama_index.legacy.evaluation import EvaluationResult from llama_index.legacy.evaluation.retrieval.base import RetrievalEvalResult The provided code snippet includes necessary dependencies for implementing the `get_ev...
Organizes EvaluationResults into a deep dataframe and computes the mean score. result: result_df: pd.DataFrame representing all the evaluation results mean_df: pd.DataFrame of average scores groupby names
36,734
import os from typing import Any, Callable, Dict, List, Literal, Optional, Type import numpy as np from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.evaluation.retrieval.metrics_base import ( BaseRetrievalMetric, RetrievalMetricResult, ) METRIC_REGISTRY: Dict[str, Type[Ba...
Resolve metrics from list of metric names.
36,735
import asyncio import multiprocessing import re import warnings from concurrent.futures import ProcessPoolExecutor from enum import Enum from functools import partial, reduce from hashlib import sha256 from itertools import repeat from pathlib import Path from typing import Any, Generator, List, Optional, Sequence, Uni...
Run a series of transformations on a set of nodes. Args: nodes: The nodes to transform. transformations: The transformations to apply to the nodes. Returns: The transformed nodes.
36,736
import asyncio import multiprocessing import re import warnings from concurrent.futures import ProcessPoolExecutor from enum import Enum from functools import partial, reduce from hashlib import sha256 from itertools import repeat from pathlib import Path from typing import Any, Generator, List, Optional, Sequence, Uni...
Wrapper for async run_transformation. To be used in loop.run_in_executor within a ProcessPoolExecutor.
36,737
import logging from typing import Callable, Dict, Optional, Union from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.indices.query.query_tr...
Default check stop function.
36,738
import logging from typing import Callable, Dict, Optional, Union from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.indices.query.query_tr...
Format SQL query.
36,739
from typing import Any, Dict, List, Optional, Sequence, Tuple from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.indices.multi_modal im...
null
36,740
from typing import Any, Callable, Optional from llama_index.legacy.query_engine.flare.schema import QueryTask from llama_index.legacy.types import BaseOutputParser The provided code snippet includes necessary dependencies for implementing the `default_parse_is_done_fn` function. Write a Python function `def default_pa...
Default parse is done function.
36,741
from typing import Any, Callable, Optional from llama_index.legacy.query_engine.flare.schema import QueryTask from llama_index.legacy.types import BaseOutputParser The provided code snippet includes necessary dependencies for implementing the `default_format_done_answer` function. Write a Python function `def default_...
Default format done answer.
36,742
import logging from typing import Any, Dict, Optional import numpy as np import pandas as pd from llama_index.legacy.exec_utils import safe_eval, safe_exec from llama_index.legacy.output_parsers.base import ChainableOutputParser from llama_index.legacy.output_parsers.utils import parse_code_markdown logger = logging.ge...
Process outputs in a default manner.
36,743
import asyncio import json import logging from typing import Any, Callable, Dict, List, Optional, Tuple from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import Response from llama_index.legacy.indices.struct_store.sql_retriever import ( BaseSQLParser...
Load the JSONalyzer. Args: use_async (bool): Whether to use async. custom_jsonalyzer (Callable): A custom JSONalyzer to use. Returns: Callable: The JSONalyzer.