id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
36,002
import logging from typing import Dict, List, Optional, cast from llama_index.core.bridge.pydantic import Field, validator from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.prompts.base import PromptTemplate from llama_index.core.response_synthesizers import ( ResponseMode...
Get backward nodes.
36,003
from __future__ import annotations import asyncio import re from typing import Any, Callable, Optional, Sequence, Tuple from llama_index.core.indices.service_context import ServiceContext from llama_index.core.evaluation.base import BaseEvaluator, EvaluationResult from llama_index.core.llms.llm import LLM from llama_in...
null
36,004
from __future__ import annotations import asyncio import re from typing import Any, Callable, Optional, Sequence, Tuple 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.core.llms.ll...
null
36,005
import asyncio from typing import Any, Dict, List, Optional, Sequence, Tuple, cast from llama_index.core.async_utils import asyncio_module from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.evaluation.base i...
Get aevaluate_response tasks with semaphore.
36,006
import asyncio from typing import Any, Dict, List, Optional, Sequence, Tuple, cast from llama_index.core.async_utils import asyncio_module from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.evaluation.base i...
Get aevaluate tasks with semaphore.
36,007
import asyncio from typing import Any, Dict, List, Optional, Sequence, Tuple, cast from llama_index.core.async_utils import asyncio_module from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.evaluation.base i...
Get aquery tasks with semaphore.
36,008
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.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from ...
null
36,009
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.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from ...
null
36,010
import asyncio from enum import Enum from typing import Any, Callable, Optional, Sequence, Tuple, Union from llama_index.core import ServiceContext from llama_index.core.evaluation.base import ( BaseEvaluator, EvaluationResult, ) from llama_index.core.llms.llm import LLM from llama_index.core.prompts import ( ...
null
36,011
import asyncio import os import subprocess import tempfile from collections import defaultdict from typing import Any, List, Optional, Tuple, TYPE_CHECKING import numpy as np import pandas as pd from llama_index_client import ProjectCreate from llama_index_client.client import PlatformApi from llama_index_client.types....
Get responses. Sync version of aget_responses.
36,012
import asyncio import os import subprocess import tempfile from collections import defaultdict from typing import Any, List, Optional, Tuple, TYPE_CHECKING import numpy as np import pandas as pd from llama_index_client import ProjectCreate from llama_index_client.client import PlatformApi from llama_index_client.types....
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,013
import asyncio import os import subprocess import tempfile from collections import defaultdict from typing import Any, List, Optional, Tuple, TYPE_CHECKING import numpy as np import pandas as pd from llama_index_client import ProjectCreate from llama_index_client.client import PlatformApi from llama_index_client.types....
Upload questions to platform dataset.
36,014
import asyncio import os import subprocess import tempfile from collections import defaultdict from typing import Any, List, Optional, Tuple, TYPE_CHECKING import numpy as np import pandas as pd from llama_index_client import ProjectCreate from llama_index_client.client import PlatformApi from llama_index_client.types....
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,015
from collections import defaultdict from typing import List, Optional, Tuple import pandas as pd from llama_index.core.evaluation import EvaluationResult from llama_index.core.evaluation.retrieval.base import RetrievalEvalResult DEFAULT_METRIC_KEYS = ["hit_rate", "mrr"] class RetrievalEvalResult(BaseModel): """Ret...
Display retrieval results.
36,016
from collections import defaultdict from typing import List, Optional, Tuple import pandas as pd from llama_index.core.evaluation import EvaluationResult from llama_index.core.evaluation.retrieval.base import RetrievalEvalResult The provided code snippet includes necessary dependencies for implementing the `get_eval_r...
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,017
import os from typing import Any, Callable, Dict, List, Literal, Optional, Type import numpy as np from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.evaluation.retrieval.metrics_base import ( BaseRetrievalMetric, RetrievalMetricResult, ) METRIC_REGISTRY: Dict[str, Type[BaseRe...
Resolve metrics from list of metric names.
36,018
import os from typing import List, Optional from llama_index_client import ( ConfigurableDataSourceNames, ConfigurableTransformationNames, ConfiguredTransformationItem, DataSourceCreate, PipelineCreate, PipelineType, ProjectCreate, ) from llama_index_client.client import AsyncPlatformApi, Pl...
Default transformations.
36,019
import os from typing import List, Optional from llama_index_client import ( ConfigurableDataSourceNames, ConfigurableTransformationNames, ConfiguredTransformationItem, DataSourceCreate, PipelineCreate, PipelineType, ProjectCreate, ) from llama_index_client.client import AsyncPlatformApi, Pl...
Get the sync platform API client.
36,020
import os from typing import List, Optional from llama_index_client import ( ConfigurableDataSourceNames, ConfigurableTransformationNames, ConfiguredTransformationItem, DataSourceCreate, PipelineCreate, PipelineType, ProjectCreate, ) from llama_index_client.client import AsyncPlatformApi, Pl...
Get the async platform API client.
36,021
import os from typing import List, Optional from llama_index_client import ( ConfigurableDataSourceNames, ConfigurableTransformationNames, ConfiguredTransformationItem, DataSourceCreate, PipelineCreate, PipelineType, ProjectCreate, ) from llama_index_client.client import AsyncPlatformApi, Pl...
Get a pipeline create object.
36,022
from enum import Enum from typing import Generic, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel, Field, GenericModel from llama_index.core.vector_stores.types import BasePydanticVectorStore class DataSink(BaseModel): """ A class containing metadata for a type of data sink. """ nam...
Build an enum of configurable data sinks. But conditional on if the corresponding vector store is available.
36,023
import uuid from enum import Enum from pathlib import Path from typing import Any, Generic, Iterable, List, Optional, Type, TypeVar, cast from llama_index.core.bridge.pydantic import BaseModel, Field, GenericModel from llama_index.core.readers.base import BasePydanticReader, ReaderConfig from llama_index.core.schema im...
Build an enum of configurable data sources. But conditional on if the corresponding reader is available.
36,024
from enum import Enum from typing import Generic, Sequence, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel, Field, GenericModel from llama_index.core.node_parser import ( CodeSplitter, HTMLNodeParser, JSONNodeParser, MarkdownNodeParser, SentenceSplitter, SimpleFileNodeParse...
Build an enum of configurable transformations. But conditional on if the corresponding component is available.
36,025
import asyncio import multiprocessing import os 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, Seq...
null
36,026
import asyncio import multiprocessing import os 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, Seq...
null
36,027
import asyncio import multiprocessing import os 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, Seq...
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,028
import asyncio import multiprocessing import os 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, Seq...
Wrapper for async run_transformation. To be used in loop.run_in_executor within a ProcessPoolExecutor.
36,029
import logging from typing import Callable, Dict, Optional, Union from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.query.query_transform....
Default check stop function.
36,030
import logging from typing import Callable, Dict, Optional, Union from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.query.query_transform....
Format SQL query.
36,031
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 Mul...
null
36,032
from typing import Any, Callable, Optional from llama_index.core.query_engine.flare.schema import QueryTask from llama_index.core.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_parse_...
Default parse is done function.
36,033
from typing import Any, Callable, Optional from llama_index.core.query_engine.flare.schema import QueryTask from llama_index.core.types import BaseOutputParser The provided code snippet includes necessary dependencies for implementing the `default_format_done_answer` function. Write a Python function `def default_form...
Default format done answer.
36,034
import logging from typing import Any, Dict, Optional import numpy as np import pandas as pd from llama_index.core.exec_utils import safe_eval, safe_exec from llama_index.core.output_parsers.base import ChainableOutputParser from llama_index.core.output_parsers.utils import parse_code_markdown logger = logging.getLogge...
Process outputs in a default manner.
36,035
import asyncio import json import logging from typing import Any, Callable, Dict, List, Optional, Tuple from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import Response from llama_index.core.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.
36,036
from typing import Any, Callable, Dict, List, Optional, Tuple, cast from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.core.indices.query.query_transf...
Stop function for multi-step query combiner.
36,037
import logging from typing import Callable, List, Optional, Sequence, Any from llama_index.core.async_utils import run_async_tasks from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.base_selector import BaseSelect...
Combine multiple response from sub-engines.
36,038
import logging from typing import Callable, List, Optional, Sequence, Any from llama_index.core.async_utils import run_async_tasks from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.base_selector import BaseSelect...
Async combine multiple response from sub-engines.
36,039
import logging from typing import Callable, List, Optional, Sequence, Any from llama_index.core.async_utils import run_async_tasks from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.base_selector import BaseSelect...
Default node to metadata function. We use the node's text as the Tool description.
36,040
import logging from abc import ABC, abstractmethod from collections import ChainMap from typing import Any, Dict, List, Optional, Union from llama_index.core.base.llms.types import ( ChatMessage, LLMMetadata, MessageRole, ) from llama_index.core.bridge.pydantic import BaseModel, PrivateAttr from llama_index...
Load predictor by class name.
36,041
from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, List, Optional from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks.base import BaseCallbackHandler, CallbackManager from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model ...
Get settings from either settings or context.
36,042
from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, List, Optional from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks.base import BaseCallbackHandler, CallbackManager from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model ...
Get settings from either settings or context.
36,043
from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, List, Optional from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks.base import BaseCallbackHandler, CallbackManager from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model ...
Get settings from either settings or context.
36,044
from string import Formatter from typing import List from llama_index.core.base.llms.base import BaseLLM The provided code snippet includes necessary dependencies for implementing the `get_template_vars` function. Write a Python function `def get_template_vars(template_str: str) -> List[str]` to solve the following pr...
Get template variables from a template string.
36,045
from string import Formatter from typing import List from llama_index.core.base.llms.base import BaseLLM class BaseLLM(ChainableMixin, BaseComponent): def _validate_callback_manager(cls, v: CallbackManager) -> CallbackManager: def metadata(self) -> LLMMetadata: def chat(self, messages: Sequence[ChatMess...
null
36,046
from typing import List from llama_index.core.prompts.base import BasePromptTemplate def get_empty_prompt_txt(prompt: BasePromptTemplate) -> str: """Get empty prompt text. Substitute empty strings in parts of the prompt that have not yet been filled out. Skip variables that have already been partially f...
Get biggest prompt. Oftentimes we need to fetch the biggest prompt, in order to be the most conservative about chunking text. This is a helper utility for that.
36,047
from llama_index.core.prompts.mixin import PromptDictType PromptDictType = Dict[str, BasePromptTemplate] The provided code snippet includes necessary dependencies for implementing the `display_prompt_dict` function. Write a Python function `def display_prompt_dict(prompts_dict: PromptDictType) -> None` to solve the f...
Display prompt dict. Args: prompts_dict: prompt dict
36,048
from typing import Optional, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.output_parsers.base import OutputParserException from llama_index.core.output_parsers.utils import parse_json_markdown The provided code snippet includes necessary dependencies for implementing the `...
Convert a python format string to handlebars-style template. In python format string, single braces {} are used for variable substitution, and double braces {{}} are used for escaping actual braces (e.g. for JSON dict) In handlebars template, double braces {{}} are used for variable substitution, and single braces are ...
36,049
from typing import Optional, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.output_parsers.base import OutputParserException from llama_index.core.output_parsers.utils import parse_json_markdown def json_schema_to_guidance_output_template( schema: dict, key: Optional[...
Convert a pydantic model to guidance output template.
36,050
from typing import Optional, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.output_parsers.base import OutputParserException from llama_index.core.output_parsers.utils import parse_json_markdown def wrap_json_markdown(text: str) -> str: """Wrap text in json markdown forma...
Convert a pydantic model to guidance output template wrapped in json markdown.
36,051
from typing import Optional, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.output_parsers.base import OutputParserException from llama_index.core.output_parsers.utils import parse_json_markdown Model = TypeVar("Model", bound=BaseModel) class OutputParserException(Exception)...
Parse output from guidance program. This is a temporary solution for parsing a pydantic object out of an executed guidance program. NOTE: right now we assume the output is the last markdown formatted json block NOTE: a better way is to extract via Program.variables, but guidance does not support extracting nested objec...
36,052
from typing import Any, Dict, List from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE from llama_index.core.bridge.langchain import BaseTool from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.schema import ...
Return a response with source node info.
36,053
from typing import Any, Optional from llama_index.core.bridge.langchain import ( AgentExecutor, AgentType, BaseCallbackManager, BaseLLM, initialize_agent, ) from llama_index.core.langchain_helpers.agents.toolkits import LlamaToolkit def create_llama_agent( toolkit: LlamaToolkit, llm: BaseLLM...
Load a chat llama agent given a Llama Toolkit and LLM. Args: toolkit: LlamaToolkit to use. llm: Language model to use as the agent. callback_manager: CallbackManager to use. Global callback manager is used if not provided. Defaults to None. agent_kwargs: Additional key word arguments to pass to the underlying agent **k...
36,054
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 import Field from llama_index.core.indices.base im...
Get prompt input key. Copied over from langchain.
36,055
import logging from abc import abstractmethod from typing import Any, Dict, Generator, List, Optional, Sequence, Union from llama_index.core.base.query_pipeline.query import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.core.base.respons...
null
36,056
from typing import Callable, Optional from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.prompt_helper import PromptHelper from llama_index.core.prompts import BasePromptTemplate from llama_index.core.prompts.default_prompt_se...
Get a response synthesizer.
36,057
import base64 import logging from typing import List, Sequence import requests from llama_index.core.schema import ImageDocument class ImageDocument(Document, ImageNode): """Data document containing an image.""" def class_name(cls) -> str: return "ImageDocument" def load_image_urls(image_urls: List[s...
null
36,058
import base64 import logging from typing import List, Sequence import requests from llama_index.core.schema import ImageDocument logger = logging.getLogger(__name__) def encode_image(image_path: str) -> str: with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8"...
null
36,059
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.core.async_utils import run_jobs from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks import ...
Add input to module deps inputs.
36,060
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.core.async_utils import run_jobs from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks import ...
Add input to module deps inputs.
36,061
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.core.async_utils import run_jobs from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks import ...
Print debug input.
36,062
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.core.async_utils import run_jobs from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks import ...
Print debug input.
36,063
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.core.async_utils import run_jobs from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks import ...
null
36,064
from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks.base import CallbackMan...
Get parameters from function. Returns: Tuple[Set[str], Set[str]]: required and optional parameters
36,065
from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple, cast from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks.base import Callb...
Get parameters from function. Returns: Tuple[Set[str], Set[str]]: required and optional parameters
36,066
from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple, cast from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks.base import Callb...
Default agent input function.
36,067
import json import re from typing import Any, Dict, Generator, List, Optional from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document import json The provided code snippet includes necessary dependencies for implementing the `_depth_first_yield` function. Write a Python funct...
Do depth first yield of all of the leaf nodes of a JSON. Combines keys in the JSON tree using spaces. If levels_back is set to 0, prints all levels. If collapse_length is not None and the json_data is <= that number of characters, then we collapse it into one line.
36,068
import os import logging import mimetypes import multiprocessing import warnings from datetime import datetime from functools import reduce from itertools import repeat from pathlib import Path import fsspec from fsspec.implementations.local import LocalFileSystem from typing import Any, Callable, Dict, Generator, List...
null
36,069
import os import logging import mimetypes import multiprocessing import warnings from datetime import datetime from functools import reduce from itertools import repeat from pathlib import Path import fsspec from fsspec.implementations.local import LocalFileSystem from typing import Any, Callable, Dict, Generator, List...
Get some handy metadate from filesystem. Args: file_path: str: file path in str
36,070
import os import logging import mimetypes import multiprocessing import warnings from datetime import datetime from functools import reduce from itertools import repeat from pathlib import Path import fsspec from fsspec.implementations.local import LocalFileSystem from typing import Any, Callable, Dict, Generator, List...
null
36,071
from typing import Any, Dict, Type from llama_index.core.readers.base import BasePydanticReader from llama_index.core.readers.string_iterable import StringIterableReader ALL_READERS: Dict[str, Type[BasePydanticReader]] = { StringIterableReader.class_name(): StringIterableReader, } class BasePydanticReader(BaseRead...
null
36,072
import json import os from typing import Optional, Type from deprecated import deprecated from llama_index.core.download.integration import download_integration from llama_index.core.readers.base import BaseReader import json def download_integration(module_str: str, module_import_str: str, cls_name: str) -> Any: ...
Download a single loader from the Loader Hub. Args: loader_class: The name of the loader class you want to download, such as `SimpleWebPageReader`. refresh_cache: If true, the local cache will be skipped and the loader will be fetched directly from the remote repo. use_gpt_index_import: If true, the loader files will u...
36,073
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) class Ch...
Convert messages to a history string.
36,074
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def messa...
Convert a completion function to a chat function.
36,075
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def messa...
Convert a completion function to a chat function.
36,076
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def promp...
Convert a chat function to a completion function.
36,077
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def promp...
Convert a chat function to a completion function.
36,078
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def messa...
Convert a completion function to a chat function.
36,079
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def promp...
Convert a chat function to a completion function.
36,080
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def messa...
Convert a completion function to a chat function.
36,081
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) def promp...
Convert a chat function to a completion function.
36,082
import os from typing import Any, Awaitable, Callable, List, Optional, Sequence from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) class Me...
Convert a stream completion response to a stream chat response.
36,083
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.core.base.query_pipeline.query import ( ChainableMixin, QueryComponent, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.mixin import PromptMixin, PromptMixinType from llama_index....
null
36,084
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.core.base.query_pipeline.query import ( ChainableMixin, QueryComponent, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.mixin import PromptMixin, PromptMixinType from llama_index....
null
36,085
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.core.bridge.pydantic import Field, validator from llama_index.core.callbacks.base import CallbackManager from llama_index.core.callbacks.schema impor...
Mean aggregation for embeddings.
36,086
from abc import ABC, abstractmethod from typing import ( Any, Callable, Dict, Generator, List, Optional, Set, Union, cast, get_args, ) from llama_index.core.base.llms.types import ( ChatResponse, CompletionResponse, ) from llama_index.core.base.response.schema import Resp...
null
36,087
from typing import Dict, Type from llama_index.core.node_parser.file.html import HTMLNodeParser from llama_index.core.node_parser.file.json import JSONNodeParser from llama_index.core.node_parser.file.markdown import MarkdownNodeParser from llama_index.core.node_parser.file.simple_file import SimpleFileNodeParser from ...
null
36,088
import logging import uuid from typing import List, Optional, Protocol, runtime_checkable from llama_index.core.schema import ( BaseNode, Document, ImageDocument, ImageNode, NodeRelationship, TextNode, ) from llama_index.core.utils import truncate_text logger = logging.getLogger(__name__) class ...
Build nodes from splits.
36,089
import logging from typing import Callable, List from llama_index.core.node_parser.interface import TextSplitter def split_text_keep_separator(text: str, separator: str) -> List[str]: """Split text with separator and keep the separator at the end of each split.""" parts = text.split(separator) result = [sep...
Split text by separator.
36,090
import logging from typing import Callable, List from llama_index.core.node_parser.interface import TextSplitter The provided code snippet includes necessary dependencies for implementing the `split_by_char` function. Write a Python function `def split_by_char() -> Callable[[str], List[str]]` to solve the following pr...
Split text by character.
36,091
import logging from typing import Callable, List from llama_index.core.node_parser.interface import TextSplitter def split_by_sentence_tokenizer() -> Callable[[str], List[str]]: import nltk tokenizer = nltk.tokenize.PunktSentenceTokenizer() # get the spans and then return the sentences # using the st...
null
36,092
import logging from typing import Callable, List from llama_index.core.node_parser.interface import TextSplitter def split_by_regex(regex: str) -> Callable[[str], List[str]]: """Split text by regex.""" import re return lambda text: re.findall(regex, text) The provided code snippet includes necessary depend...
Split text by phrase regex. This regular expression will split the sentences into phrases, where each phrase is a sequence of one or more non-comma, non-period, and non-semicolon characters, followed by an optional comma, period, or semicolon. The regular expression will also capture the delimiters themselves as separa...
36,093
from typing import Any, Dict, List, Optional, Sequence from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks.base import CallbackManager from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.core.node_parser.interface import NodeParser from llama_index.cor...
Add parent/child relationship between nodes.
36,094
from typing import Any, Dict, List, Optional, Sequence from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks.base import CallbackManager from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.core.node_parser.interface import NodeParser from llama_index.cor...
Get leaf nodes.
36,095
from typing import Any, Dict, List, Optional, Sequence from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks.base import CallbackManager from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.core.node_parser.interface import NodeParser from llama_index.cor...
Get children of root nodes in given nodes that have given depth.
36,096
from typing import Any, Callable, List, Optional, Dict from llama_index.core.bridge.pydantic import Field import pandas as pd from llama_index.core.callbacks.base import CallbackManager from llama_index.core.node_parser.relational.base_element import ( DEFAULT_SUMMARY_QUERY_STR, BaseElementNodeParser, Eleme...
Convert HTML to dataframe.
36,097
from io import StringIO from typing import Any, Callable, List, Optional import pandas as pd from llama_index.core.node_parser.relational.base_element import ( BaseElementNodeParser, Element, ) from llama_index.core.schema import BaseNode, TextNode The provided code snippet includes necessary dependencies for ...
Convert Markdown to dataframe.
36,098
from llama_index.core.agent.types import TaskStep from llama_index.core.base.llms.types import ChatMessage, MessageRole from llama_index.core.memory import BaseMemory class TaskStep(BaseModel): """Agent task step. Represents a single input step within the execution run ("Task") of an agent given a user in...
Add user step to memory.
36,099
import re from typing import Tuple from llama_index.core.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.core.output_parsers.utils import extract_json_str from llama_index.core.types import BaseOutputParser def extract_final_response(input_text: ...
null
36,100
import re from typing import Tuple from llama_index.core.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.core.output_parsers.utils import extract_json_str from llama_index.core.types import BaseOutputParser def extract_tool_use(input_text: str) ->...
Parse an action reasoning step from the LLM output.
36,101
import asyncio import uuid from functools import partial from itertools import chain from threading import Thread from typing import ( Any, AsyncGenerator, Dict, Generator, List, Optional, Sequence, Tuple, cast, ) from llama_index.core.agent.react.formatter import ReActChatFormatter ...
Add user step to memory.