id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
36,744
from typing import Any, Callable, Dict, List, Optional, Tuple, cast from llama_index.legacy.callbacks.schema import CBEventType, EventPayload from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE from llama_index.legacy.indices.query.quer...
Stop function for multi-step query combiner.
36,745
import logging from typing import Callable, List, Optional, Sequence from llama_index.legacy.async_utils import run_async_tasks from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload...
Combine multiple response from sub-engines.
36,746
import logging from typing import Callable, List, Optional, Sequence from llama_index.legacy.async_utils import run_async_tasks from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload...
Async combine multiple response from sub-engines.
36,747
import logging from typing import Callable, List, Optional, Sequence from llama_index.legacy.async_utils import run_async_tasks from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload...
Default node to metadata function. We use the node's text as the Tool description.
36,748
from string import Formatter from typing import List from llama_index.legacy.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 probl...
Get template variables from a template string.
36,749
from string import Formatter from typing import List from llama_index.legacy.llms.base import BaseLLM class BaseLLM(ChainableMixin, BaseComponent): """LLM interface.""" callback_manager: CallbackManager = Field( default_factory=CallbackManager, exclude=True ) class Config: arbitrary_t...
null
36,750
from contextlib import contextmanager from typing import TYPE_CHECKING, Callable, Iterator from llama_index.legacy.llms.huggingface import HuggingFaceLLM from llama_index.legacy.llms.llama_cpp import LlamaCPP from llama_index.legacy.llms.llm import LLM class HuggingFaceLLM(CustomLLM): """HuggingFace LLM.""" m...
Prepare for using the LM format enforcer. This builds the processing function that will be injected into the LLM to activate the LM Format Enforcer.
36,751
from contextlib import contextmanager from typing import TYPE_CHECKING, Callable, Iterator from llama_index.legacy.llms.huggingface import HuggingFaceLLM from llama_index.legacy.llms.llama_cpp import LlamaCPP from llama_index.legacy.llms.llm import LLM class HuggingFaceLLM(CustomLLM): """HuggingFace LLM.""" m...
Activate the LM Format Enforcer for the given LLM. with activate_lm_format_enforcer(llm, lm_format_enforcer_fn): llm.complete(...)
36,752
from typing import List from llama_index.legacy.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...
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,753
from llama_index.legacy.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...
Display prompt dict. Args: prompts_dict: prompt dict
36,754
from typing import Optional, Type, TypeVar from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.output_parsers.base import OutputParserException from llama_index.legacy.output_parsers.utils import parse_json_markdown The provided code snippet includes necessary dependencies for implementing...
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,755
from typing import Optional, Type, TypeVar from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.output_parsers.base import OutputParserException from llama_index.legacy.output_parsers.utils import parse_json_markdown def json_schema_to_guidance_output_template( schema: dict, key: Opt...
Convert a pydantic model to guidance output template.
36,756
from typing import Optional, Type, TypeVar from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.output_parsers.base import OutputParserException from llama_index.legacy.output_parsers.utils import parse_json_markdown def wrap_json_markdown(text: str) -> str: """Wrap text in json markdown...
Convert a pydantic model to guidance output template wrapped in json markdown.
36,757
from typing import Optional, Type, TypeVar from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.output_parsers.base import OutputParserException from llama_index.legacy.output_parsers.utils import parse_json_markdown Model = TypeVar("Model", bound=BaseModel) class OutputParserException(Exce...
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,758
from typing import Any, Dict, List from llama_index.legacy.bridge.langchain import BaseTool from llama_index.legacy.bridge.pydantic import BaseModel, Field from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.response.schema import RESPONSE_TYPE from llama_index.legacy.sche...
Return a response with source node info.
36,759
from typing import Any, Optional from llama_index.legacy.bridge.langchain import ( AgentExecutor, AgentType, BaseCallbackManager, BaseLLM, initialize_agent, ) from llama_index.legacy.langchain_helpers.agents.toolkits import LlamaToolkit def create_llama_agent( toolkit: LlamaToolkit, llm: Bas...
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,760
from typing import Any, Dict, List, Optional from llama_index.legacy.bridge.langchain import ( AIMessage, BaseChatMemory, BaseMessage, HumanMessage, ) from llama_index.legacy.bridge.langchain import BaseMemory as Memory from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.indices...
Get prompt input key. Copied over from langchain.
36,761
from typing import Callable, Optional from llama_index.legacy.bridge.pydantic import BaseModel from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.prompts import BasePromptTemplate from llama_index.legacy.prompts.default_prompt_selectors import ( DEFAULT_REFINE_PROMPT_SEL, DEFA...
Get a response synthesizer.
36,762
import base64 import logging from typing import List, Sequence import requests from llama_index.legacy.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...
null
36,763
import base64 import logging from typing import List, Sequence import requests from llama_index.legacy.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-...
null
36,764
from typing import Any, Dict, Sequence, Tuple from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.constants import DEFAULT_CONTEXT_WINDOW, DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, C...
null
36,765
from typing import Any, Dict, Sequence, Tuple from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.constants import DEFAULT_CONTEXT_WINDOW, DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, C...
Convert messages to dicts. For use in ollama API
36,766
from http import HTTPStatus from typing import Any, Dict, List, Sequence from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ) from llama_index.legacy.schema import ImageDocument class CompletionResponse(BaseModel): """ Completion response. Fields: ...
null
36,767
from http import HTTPStatus from typing import Any, Dict, List, Sequence from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ) from llama_index.legacy.schema import ImageDocument class ChatMessage(BaseModel): """Chat message.""" role: MessageRole = Messa...
null
36,768
from http import HTTPStatus from typing import Any, Dict, List, Sequence from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ) from llama_index.legacy.schema import ImageDocument class ChatMessage(BaseModel): """Chat message.""" role: MessageRole = Messa...
null
36,769
from http import HTTPStatus from typing import Any, Dict, List, Sequence from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ) from llama_index.legacy.schema import ImageDocument class ChatMessage(BaseModel): """Chat message.""" role: MessageRole = Messa...
null
36,770
from http import HTTPStatus from typing import Any, Dict, List, Sequence from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ) from llama_index.legacy.schema import ImageDocument class ImageDocument(Document, ImageNode): """Data document containing an image."...
null
36,771
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.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatRe...
null
36,772
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.legacy.async_utils import run_jobs from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks i...
Add input to module deps inputs.
36,773
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.legacy.async_utils import run_jobs from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks i...
Add input to module deps inputs.
36,774
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.legacy.async_utils import run_jobs from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks i...
Print debug input.
36,775
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.legacy.async_utils import run_jobs from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks i...
Print debug input.
36,776
import json import uuid from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, get_args, ) import networkx from llama_index.legacy.async_utils import run_jobs from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks i...
null
36,777
from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple, cast 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, OutputK...
Get parameters from function. Returns: Tuple[Set[str], Set[str]]: required and optional parameters
36,778
from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple, cast 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, OutputK...
Default agent input function.
36,779
import json import re from typing import Any, Generator, List, Optional from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document import json The provided code snippet includes necessary dependencies for implementing the `_depth_first_yield` function. Write a Python functio...
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,780
import asyncio import logging import os from typing import List, Optional from llama_index.legacy.readers.base import BasePydanticReader from llama_index.legacy.schema import Document logger = logging.getLogger(__name__) class Document(TextNode): """Generic interface for a data document. This document connect...
Async read channel. Note: This is our hack to create a synchronous interface to the async discord.py API. We use the `asyncio` module to run this function with `asyncio.get_event_loop().run_until_complete`.
36,781
import logging import re from typing import TYPE_CHECKING, Any, List, Optional, Pattern import numpy as np _logger = logging.getLogger(__name__) REDIS_REQUIRED_MODULES = [ {"name": "search", "ver": 20400}, {"name": "searchlight", "ver": 20400}, ] The provided code snippet includes necessary dependencies for im...
Check if the correct Redis modules are installed.
36,782
import logging import re from typing import TYPE_CHECKING, Any, List, Optional, Pattern import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_redis_query` function. Write a Python function `def get_redis_query( return_fields: List[str], top_k: int = 20, vect...
Create a vector query for use with a SearchIndex. Args: return_fields (t.List[str]): A list of fields to return in the query results top_k (int, optional): The number of results to return. Defaults to 20. vector_field (str, optional): The name of the vector field in the index. Defaults to "vector". sort (bool, optional...
36,783
import logging import re from typing import TYPE_CHECKING, Any, List, Optional, Pattern import numpy as np def convert_bytes(data: Any) -> Any: if isinstance(data, bytes): return data.decode("ascii") if isinstance(data, dict): return dict(map(convert_bytes, data.items())) if isinstance(data...
null
36,784
import logging import re from typing import TYPE_CHECKING, Any, List, Optional, Pattern import numpy as np def array_to_buffer(array: List[float], dtype: Any = np.float32) -> bytes: return np.array(array).astype(dtype).tobytes()
null
36,785
import logging import mimetypes import multiprocessing import os import warnings from datetime import datetime from functools import reduce from itertools import repeat from pathlib import Path from typing import Any, Callable, Dict, Generator, List, Optional, Type from tqdm import tqdm from llama_index.legacy.readers....
Get some handy metadate from filesystem. Args: file_path: str: file path in str
36,786
import asyncio import os import time from abc import ABC, abstractmethod from typing import List, Tuple from llama_index.legacy.readers.github_readers.github_api_client import ( GitBlobResponseModel, GithubClient, GitTreeResponseModel, ) The provided code snippet includes necessary dependencies for impleme...
Log message if verbose is True.
36,787
import asyncio import os import time from abc import ABC, abstractmethod from typing import List, Tuple from llama_index.legacy.readers.github_readers.github_api_client import ( GitBlobResponseModel, GithubClient, GitTreeResponseModel, ) The provided code snippet includes necessary dependencies for impleme...
Get file extension.
36,788
import asyncio import base64 import binascii import logging import os import pathlib import tempfile from typing import Any, Callable, Dict, List, Optional, Tuple from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.readers.file.base import DEFAULT_FILE_READER_CLS from llama_index.legacy.reade...
Time a function.
36,789
import asyncio import base64 import binascii import logging import os import pathlib import tempfile from typing import Any, Callable, Dict, List, Optional, Tuple from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.readers.file.base import DEFAULT_FILE_READER_CLS from llama_index.legacy.reade...
Load data from a commit.
36,790
import asyncio import base64 import binascii import logging import os import pathlib import tempfile from typing import Any, Callable, Dict, List, Optional, Tuple from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.readers.file.base import DEFAULT_FILE_READER_CLS from llama_index.legacy.reade...
Load data from a branch.
36,791
from typing import Any, Dict, Type from llama_index.legacy.readers.base import BasePydanticReader from llama_index.legacy.readers.discord_reader import DiscordReader from llama_index.legacy.readers.elasticsearch import ElasticsearchReader from llama_index.legacy.readers.google_readers.gdocs import GoogleDocsReader from...
null
36,792
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.readers.base import BaseReader LLAMA_HUB_URL = LLAMA_HUB_CONTENTS_URL + LLAMA_HUB_PATH class MODULE_TYPE(str, Enum): LO...
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,793
import logging from typing import Any, Callable, Dict, List, Optional, Tuple import requests from llama_index.legacy.bridge.pydantic import PrivateAttr from llama_index.legacy.readers.base import BasePydanticReader from llama_index.legacy.schema import Document The provided code snippet includes necessary dependencies...
Extract text from Substack blog post.
36,794
import logging from typing import Any, List, Optional from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document def escape_str(value: str) -> str: BS = "\\" must_escape = (BS, "'") return ( "".join(f"{BS}{c}" if c in must_escape else c for c in value) if ...
null
36,795
import logging from typing import Any, List, Optional from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document def format_list_to_string(lst: List) -> str: return "[" + ",".join(str(item) for item in lst) + "]"
null
36,796
from typing import List, Optional, Union import numpy as np from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document distance_metric_map = { "l2": lambda a, b: np.linalg.norm(a - b, axis=1, ord=2), "l1": lambda a, b: np.linalg.norm(a - b, axis=1, ord=1), "max": l...
Naive search for nearest neighbors args: query_vector: Union[List, np.ndarray] data_vectors: np.ndarray limit (int): number of nearest neighbors distance_metric: distance function 'L2' for Euclidean, 'L1' for Nuclear, 'Max' l-infinity distance, 'cos' for cosine similarity, 'dot' for dot product returns: nearest_indices...
36,797
from typing import Dict, Type from llama_index.legacy.node_parser.file.html import HTMLNodeParser from llama_index.legacy.node_parser.file.json import JSONNodeParser from llama_index.legacy.node_parser.file.markdown import MarkdownNodeParser from llama_index.legacy.node_parser.file.simple_file import SimpleFileNodePars...
null
36,798
import logging import uuid from typing import List, Optional, Protocol, runtime_checkable from llama_index.legacy.schema import ( BaseNode, Document, ImageDocument, ImageNode, NodeRelationship, TextNode, ) from llama_index.legacy.utils import truncate_text logger = logging.getLogger(__name__) cl...
Build nodes from splits.
36,799
import logging from typing import Callable, List from llama_index.legacy.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 = [s...
Split text by separator.
36,800
import logging from typing import Callable, List from llama_index.legacy.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 ...
Split text by character.
36,801
import logging from typing import Callable, List from llama_index.legacy.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 ...
null
36,802
import logging from typing import Callable, List from llama_index.legacy.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 depe...
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,803
from typing import Any, Dict, List, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload from llama_index.legacy.node_parser.interface import NodeParser from llama_i...
Add parent/child relationship between nodes.
36,804
from typing import Any, Dict, List, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload from llama_index.legacy.node_parser.interface import NodeParser from llama_i...
Get leaf nodes.
36,805
from typing import Any, Dict, List, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.callbacks.schema import CBEventType, EventPayload from llama_index.legacy.node_parser.interface import NodeParser from llama_i...
Get root nodes.
36,806
from typing import Any, Callable, List, Optional import pandas as pd from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.node_parser.relational.base_element import ( DEFAULT_SUMMARY_QUERY_STR, BaseElementNodeParser, Element, ) from llama_index.legacy.schema import BaseNode,...
Convert HTML to dataframe.
36,807
from io import StringIO from typing import Any, Callable, List, Optional import pandas as pd from llama_index.legacy.node_parser.relational.base_element import ( BaseElementNodeParser, Element, ) from llama_index.legacy.schema import BaseNode, TextNode The provided code snippet includes necessary dependencies ...
Convert Markdown to dataframe.
36,808
import asyncio import json import logging import time from typing import Any, Dict, List, Optional, Tuple, Union, cast from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_index.legacy.callbacks import ( CallbackManager, CBEventTy...
From OpenAI thread messages.
36,809
import asyncio import json import logging import time from typing import Any, Dict, List, Optional, Tuple, Union, cast from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_index.legacy.callbacks import ( CallbackManager, CBEventTy...
Call a function and return the output as a string.
36,810
import asyncio import json import logging import time from typing import Any, Dict, List, Optional, Tuple, Union, cast from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_index.legacy.callbacks import ( CallbackManager, CBEventTy...
Call an async function and return the output as a string.
36,811
import asyncio import json import logging import time from typing import Any, Dict, List, Optional, Tuple, Union, cast from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_index.legacy.callbacks import ( CallbackManager, CBEventTy...
Process files.
36,812
import asyncio import json import logging import uuid from threading import Thread from typing import Any, Dict, List, Optional, Tuple, Union, cast, get_args from llama_index.legacy.agent.openai.utils import resolve_tool_choice from llama_index.legacy.agent.types import ( BaseAgentWorker, Task, TaskStep, ...
Call a function and return the output as a string.
36,813
import asyncio import json import logging import uuid from threading import Thread from typing import Any, Dict, List, Optional, Tuple, Union, cast, get_args from llama_index.legacy.agent.openai.utils import resolve_tool_choice from llama_index.legacy.agent.types import ( BaseAgentWorker, Task, TaskStep, ...
Call a function and return the output as a string.
36,814
from llama_index.legacy.agent.types import TaskStep from llama_index.legacy.core.llms.types import MessageRole from llama_index.legacy.llms.base import ChatMessage from llama_index.legacy.memory import BaseMemory class TaskStep(BaseModel): """Agent task step. Represents a single input step within the executio...
Add user step to memory.
36,815
import re from typing import Tuple from llama_index.legacy.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.legacy.output_parsers.utils import extract_json_str from llama_index.legacy.types import BaseOutputParser def extract_final_response(input_...
null
36,816
import re from typing import Tuple from llama_index.legacy.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.legacy.output_parsers.utils import extract_json_str from llama_index.legacy.types import BaseOutputParser def extract_tool_use(input_text: s...
Parse an action reasoning step from the LLM output.
36,817
import asyncio import uuid from itertools import chain from threading import Thread from typing import ( Any, AsyncGenerator, Dict, Generator, List, Optional, Sequence, Tuple, cast, ) from llama_index.legacy.agent.react.formatter import ReActChatFormatter from llama_index.legacy.agen...
Add user step to memory.
36,818
import logging from abc import abstractmethod from typing import List, Optional, Sequence from llama_index.legacy.agent.react.prompts import ( CONTEXT_REACT_CHAT_SYSTEM_HEADER, REACT_CHAT_SYSTEM_HEADER, ) from llama_index.legacy.agent.react.types import ( BaseReasoningStep, ObservationReasoningStep, ) f...
Tool.
36,819
import asyncio import json import logging from abc import abstractmethod from threading import Thread from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast, get_args from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_in...
Call a function and return the output as a string.
36,820
import asyncio import json import logging from abc import abstractmethod from threading import Thread from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast, get_args from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_in...
Call a function and return the output as a string.
36,821
import asyncio import json import logging from abc import abstractmethod from threading import Thread from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast, get_args from llama_index.legacy.agent.openai.utils import get_function_by_name from llama_index.legacy.agent.types import BaseAgent from llama_in...
Resolve tool choice. If tool_choice is a function name string, return the appropriate dict.
36,822
from abc import abstractmethod from collections import deque from typing import Any, Deque, Dict, List, Optional, Union, cast from llama_index.legacy.agent.types import ( BaseAgent, BaseAgentWorker, Task, TaskStep, TaskStepOutput, ) from llama_index.legacy.bridge.pydantic import BaseModel, Field fro...
Validate step from args.
36,823
import uuid from typing import ( Any, List, Optional, cast, ) from llama_index.legacy.agent.types import ( BaseAgentWorker, Task, TaskStep, TaskStepOutput, ) from llama_index.legacy.bridge.pydantic import BaseModel, Field from llama_index.legacy.callbacks import ( CallbackManager, ...
Get agent components.
36,824
import uuid from typing import ( Any, Dict, List, Optional, Sequence, Tuple, cast, ) from llama_index.legacy.agent.react.formatter import ReActChatFormatter from llama_index.legacy.agent.react.output_parser import ReActOutputParser from llama_index.legacy.agent.react.types import ( Actio...
Add user step to reasoning. Adds both text input and image input to reasoning.
36,825
import logging import os from string import Template from typing import Any, Dict, List, Optional from tenacity import retry, stop_after_attempt, wait_random_exponential from llama_index.legacy.graph_stores.types import GraphStore def hash_string_to_rank(string: str) -> int: # get signed 64-bit hash value sign...
null
36,826
import logging import os from string import Template from typing import Any, Dict, List, Optional from tenacity import retry, stop_after_attempt, wait_random_exponential from llama_index.legacy.graph_stores.types import GraphStore logger = logging.getLogger(__name__) The provided code snippet includes necessary depend...
Prepare parameters for query.
36,827
import logging import os from string import Template from typing import Any, Dict, List, Optional from tenacity import retry, stop_after_attempt, wait_random_exponential from llama_index.legacy.graph_stores.types import GraphStore The provided code snippet includes necessary dependencies for implementing the `escape_s...
Escape String for NebulaGraph Query.
36,828
from llama_index.legacy.constants import DATA_KEY, TYPE_KEY from llama_index.legacy.schema import ( BaseNode, Document, ImageDocument, ImageNode, IndexNode, NodeRelationship, RelatedNodeInfo, TextNode, ) TYPE_KEY = "__type__" DATA_KEY = "__data__" class BaseNode(BaseComponent): de...
null
36,829
from llama_index.legacy.constants import DATA_KEY, TYPE_KEY from llama_index.legacy.schema import ( BaseNode, Document, ImageDocument, ImageNode, IndexNode, NodeRelationship, RelatedNodeInfo, TextNode, ) def legacy_json_to_doc(doc_dict: dict) -> BaseNode: """Todo: Deprecated legacy s...
null
36,830
from enum import Enum from typing import Dict, Type from llama_index.legacy.storage.docstore.mongo_docstore import MongoDocumentStore from llama_index.legacy.storage.docstore.simple_docstore import SimpleDocumentStore from llama_index.legacy.storage.docstore.types import BaseDocumentStore class SimpleDocumentStore(KVD...
null
36,831
from __future__ import annotations import os from decimal import Decimal from typing import Any, Dict, List, Set, Tuple from llama_index.legacy.storage.kvstore.types import DEFAULT_COLLECTION, BaseKVStore def parse_schema(table: Any) -> Tuple[str, str]: key_hash: str | None = None key_range: str | None = None ...
null
36,832
from __future__ import annotations import os from decimal import Decimal from typing import Any, Dict, List, Set, Tuple from llama_index.legacy.storage.kvstore.types import DEFAULT_COLLECTION, BaseKVStore def convert_float_to_decimal(obj: Any) -> Any: if isinstance(obj, List): return [convert_float_to_deci...
null
36,833
from __future__ import annotations import os from decimal import Decimal from typing import Any, Dict, List, Set, Tuple from llama_index.legacy.storage.kvstore.types import DEFAULT_COLLECTION, BaseKVStore def convert_decimal_to_int_or_float(obj: Any) -> Any: if isinstance(obj, List): return [convert_decima...
null
36,834
import json from typing import Any, Dict, List, Optional, Tuple, Type from urllib.parse import urlparse from llama_index.legacy.storage.kvstore.types import ( DEFAULT_BATCH_SIZE, DEFAULT_COLLECTION, BaseKVStore, ) The provided code snippet includes necessary dependencies for implementing the `get_data_mode...
This part create a dynamic sqlalchemy model with a new table.
36,835
import json from typing import Any, Dict, List, Optional, Tuple, Type from urllib.parse import urlparse from llama_index.legacy.storage.kvstore.types import ( DEFAULT_BATCH_SIZE, DEFAULT_COLLECTION, BaseKVStore, ) def params_from_uri(uri: str) -> dict: result = urlparse(uri) database = result.path[...
null
36,836
from llama_index.legacy.constants import DATA_KEY, TYPE_KEY from llama_index.legacy.data_structs.data_structs import IndexStruct from llama_index.legacy.data_structs.registry import ( INDEX_STRUCT_TYPE_TO_INDEX_STRUCT_CLASS, ) TYPE_KEY = "__type__" DATA_KEY = "__data__" class IndexStruct(DataClassJsonMixin): ...
null
36,837
from llama_index.legacy.constants import DATA_KEY, TYPE_KEY from llama_index.legacy.data_structs.data_structs import IndexStruct from llama_index.legacy.data_structs.registry import ( INDEX_STRUCT_TYPE_TO_INDEX_STRUCT_CLASS, ) TYPE_KEY = "__type__" DATA_KEY = "__data__" class IndexStruct(DataClassJsonMixin): ...
null
36,838
import json import logging import sys from typing import TYPE_CHECKING, Any, List, Optional from urllib.parse import urlparse from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.llms import ChatMessage from llama_index.legacy.storage.chat_store.base import BaseChatStore def _message_to_dict(me...
null
36,839
import json import logging import sys from typing import TYPE_CHECKING, Any, List, Optional from urllib.parse import urlparse from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.llms import ChatMessage from llama_index.legacy.storage.chat_store.base import BaseChatStore def _dict_to_message(d:...
null
36,840
from llama_index.legacy.storage.chat_store.base import BaseChatStore from llama_index.legacy.storage.chat_store.simple_chat_store import SimpleChatStore RECOGNIZED_CHAT_STORES = { SimpleChatStore.class_name(): SimpleChatStore, } class BaseChatStore(BaseComponent): def class_name(cls) -> str: """Get cla...
Load a chat store from a dict.
36,841
import logging from collections import Counter from functools import partial from typing import Any, Callable, Dict, List, Optional, cast from llama_index.legacy.bridge.pydantic import PrivateAttr from llama_index.legacy.schema import BaseNode, MetadataMode, TextNode from llama_index.legacy.vector_stores.pinecone_utils...
Generate sparse vectors from a batch of contexts. NOTE: taken from https://www.pinecone.io/learn/hybrid-search-intro/.
36,842
import logging from collections import Counter from functools import partial from typing import Any, Callable, Dict, List, Optional, cast from llama_index.legacy.bridge.pydantic import PrivateAttr from llama_index.legacy.schema import BaseNode, MetadataMode, TextNode from llama_index.legacy.vector_stores.pinecone_utils...
Get default tokenizer. NOTE: taken from https://www.pinecone.io/learn/hybrid-search-intro/.
36,843
import logging from collections import Counter from functools import partial from typing import Any, Callable, Dict, List, Optional, cast from llama_index.legacy.bridge.pydantic import PrivateAttr from llama_index.legacy.schema import BaseNode, MetadataMode, TextNode from llama_index.legacy.vector_stores.pinecone_utils...
Convert from standard dataclass to pinecone filter dict.