id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
36,102 | import logging
from abc import abstractmethod
from typing import List, Optional, Sequence
from llama_index.core.agent.react.prompts import (
CONTEXT_REACT_CHAT_SYSTEM_HEADER,
REACT_CHAT_SYSTEM_HEADER,
)
from llama_index.core.agent.react.types import (
BaseReasoningStep,
ObservationReasoningStep,
)
from ... | Tool. |
36,103 | import os
from abc import abstractmethod
from collections import deque
from typing import Any, Deque, Dict, List, Optional, Union, cast
from llama_index.core.agent.types import (
BaseAgent,
BaseAgentWorker,
Task,
TaskStep,
TaskStepOutput,
)
from llama_index.core.bridge.pydantic import BaseModel, Fie... | Validate step from args. |
36,104 | import uuid
from typing import (
Any,
List,
Optional,
cast,
)
from llama_index.core.agent.types import (
BaseAgentWorker,
Task,
TaskStep,
TaskStepOutput,
)
from llama_index.core.base.query_pipeline.query import QueryComponent
from llama_index.core.bridge.pydantic import BaseModel, Field
... | Get agent components. |
36,105 | import uuid
from functools import partial
from typing import Any, Dict, List, Optional, Protocol, Sequence, Tuple, cast
from llama_index.core.agent.react.formatter import ReActChatFormatter
from llama_index.core.agent.react.output_parser import ReActOutputParser
from llama_index.core.agent.react.types import (
Acti... | Add user step to reasoning. Adds both text input and image input to reasoning. |
36,106 | from llama_index.core.constants import DATA_KEY, TYPE_KEY
from llama_index.core.schema import (
BaseNode,
Document,
ImageDocument,
ImageNode,
IndexNode,
NodeRelationship,
RelatedNodeInfo,
TextNode,
)
TYPE_KEY = "__type__"
DATA_KEY = "__data__"
class BaseNode(BaseComponent):
"""Base... | null |
36,107 | from llama_index.core.constants import DATA_KEY, TYPE_KEY
from llama_index.core.schema import (
BaseNode,
Document,
ImageDocument,
ImageNode,
IndexNode,
NodeRelationship,
RelatedNodeInfo,
TextNode,
)
def legacy_json_to_doc(doc_dict: dict) -> BaseNode:
TYPE_KEY = "__type__"
DATA_KEY = "_... | null |
36,108 | from enum import Enum
from typing import Dict, Type
from llama_index.core.storage.docstore.simple_docstore import SimpleDocumentStore
from llama_index.core.storage.docstore.types import BaseDocumentStore
class SimpleDocumentStore(KVDocumentStore):
"""Simple Document (Node) store.
An in-memory store for Docume... | null |
36,109 | import json
from typing import Any, Dict, List, Optional, Tuple, Type
from urllib.parse import urlparse
from llama_index.core.storage.kvstore.types import (
DEFAULT_BATCH_SIZE,
DEFAULT_COLLECTION,
BaseKVStore,
)
The provided code snippet includes necessary dependencies for implementing the `get_data_model`... | This part create a dynamic sqlalchemy model with a new table. |
36,110 | import json
from typing import Any, Dict, List, Optional, Tuple, Type
from urllib.parse import urlparse
from llama_index.core.storage.kvstore.types import (
DEFAULT_BATCH_SIZE,
DEFAULT_COLLECTION,
BaseKVStore,
)
def params_from_uri(uri: str) -> dict:
result = urlparse(uri)
database = result.path[1:... | null |
36,111 | from llama_index.core.constants import DATA_KEY, TYPE_KEY
from llama_index.core.data_structs.data_structs import IndexStruct
from llama_index.core.data_structs.registry import (
INDEX_STRUCT_TYPE_TO_INDEX_STRUCT_CLASS,
)
TYPE_KEY = "__type__"
DATA_KEY = "__data__"
class IndexStruct(DataClassJsonMixin):
"""A b... | null |
36,112 | from llama_index.core.constants import DATA_KEY, TYPE_KEY
from llama_index.core.data_structs.data_structs import IndexStruct
from llama_index.core.data_structs.registry import (
INDEX_STRUCT_TYPE_TO_INDEX_STRUCT_CLASS,
)
TYPE_KEY = "__type__"
DATA_KEY = "__data__"
class IndexStruct(DataClassJsonMixin):
"""A b... | null |
36,113 | from llama_index.core.storage.chat_store.base import BaseChatStore
from llama_index.core.storage.chat_store.simple_chat_store import SimpleChatStore
RECOGNIZED_CHAT_STORES = {
SimpleChatStore.class_name(): SimpleChatStore,
}
class BaseChatStore(BaseComponent):
def class_name(cls) -> str:
"""Get class n... | Load a chat store from a dict. |
36,114 | import json
import logging
import os
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Mapping, Optional, cast
import fsspec
from dataclasses_json import DataClassJsonMixin
from llama_index.core.indices.query.embedding_utils import (
get_top_k_embeddings,
get_top_k_embedding... | Build metadata filter function. |
36,115 | import asyncio
from inspect import signature
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.tools.function_tool import FunctionTool
from llama_index.core.tools.types import ToolMetadata
from llama_index.c... | Patch sync function from async function. |
36,116 | from inspect import signature
from typing import Any, Callable, List, Optional, Tuple, Type, Union, cast
from llama_index.core.bridge.pydantic import BaseModel, FieldInfo, create_model
The provided code snippet includes necessary dependencies for implementing the `create_schema_from_function` function. Write a Python ... | Create schema from function. |
36,117 | 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.tools.tool_spec.base import BaseToolSpec
def download_integration(module_str: str, module_import_str: str, cls_name: str) -> Any:
""... | Download a single tool from Llama Hub. Args: tool_class: The name of the tool class you want to download, such as `GmailToolSpec`. refresh_cache: If true, the local cache will be skipped and the loader will be fetched directly from the remote repo. custom_path: Custom dirpath to download loader into. Returns: A Loader. |
36,118 | import asyncio
from inspect import signature
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional, Type
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput
from llama_index.core.tools.utils import create_schema_from_func... | Sync to async. |
36,119 | import json
import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import tqdm
from llama_index.core.download.utils import (
get_file_content,
get_file_content_bytes,
get_source_files_list,
initialize_directory,
)
LLAMA_DATASETS_URL = LLAMA_INDEX_CONTENTS_URL + LLAMA_DATA... | Download a module from LlamaHub. Can be a loader, tool, pack, or more. Args: loader_class: The name of the llama module class you want to download, such as `GmailOpenAIAgentPack`. refresh_cache: If true, the local cache will be skipped and the loader will be fetched directly from the remote repo. custom_dir: Custom dir... |
36,120 | import json
import logging
import os
import subprocess
import sys
from enum import Enum
from importlib import util
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import requests
from llama_index.core.download.utils import (
get_exports,
get_file_content,
initialize_directory,
... | Download a module from LlamaHub. Can be a loader, tool, pack, or more. Args: loader_class: The name of the llama module class you want to download, such as `GmailOpenAIAgentPack`. refresh_cache: If true, the local cache will be skipped and the loader will be fetched directly from the remote repo. custom_dir: Custom dir... |
36,121 | import re
from typing import Optional, Set
import pandas as pd
from llama_index.core.indices.utils import expand_tokens_with_subtokens
from llama_index.core.utils import globals_helper
def expand_tokens_with_subtokens(tokens: Set[str]) -> Set[str]:
"""Get subtokens from a list of tokens., filtering for stopwords."... | Extract keywords with RAKE. |
36,122 | import re
from typing import Optional, Set
import pandas as pd
from llama_index.core.indices.utils import expand_tokens_with_subtokens
from llama_index.core.utils import globals_helper
def expand_tokens_with_subtokens(tokens: Set[str]) -> Set[str]:
"""Get subtokens from a list of tokens., filtering for stopwords."... | Extract keywords given the GPT-generated response. Used by keyword table indices. Parses <start_token>: <word1>, <word2>, ... into [word1, word2, ...] Raises exception if response doesn't start with <start_token> |
36,123 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Get sorted node list. Used by tree-strutured indices. |
36,124 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Extract number given the GPT-generated response. Used by tree-structured indices. |
36,125 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Log vector store query result. |
36,126 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Default format node batch function. Assign each summary node a number, and format the batch of nodes. |
36,127 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Default parse choice select answer function. |
36,128 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Get embeddings of the given nodes, run embedding model if necessary. Args: nodes (Sequence[BaseNode]): The nodes to embed. embed_model (BaseEmbedding): The embedding model to use. show_progress (bool): Whether to show progress bar. Returns: Dict[str, List[float]]: A map from node id to embedding. |
36,129 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Get image embeddings of the given nodes, run image embedding model if necessary. Args: nodes (Sequence[ImageNode]): The nodes to embed. embed_model (MultiModalEmbedding): The embedding model to use. show_progress (bool): Whether to show progress bar. Returns: Dict[str, List[float]]: A map from node id to embedding. |
36,130 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Async get embeddings of the given nodes, run embedding model if necessary. Args: nodes (Sequence[BaseNode]): The nodes to embed. embed_model (BaseEmbedding): The embedding model to use. show_progress (bool): Whether to show progress bar. Returns: Dict[str, List[float]]: A map from node id to embedding. |
36,131 | import logging
import re
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.multi_modal_base import MultiModalEmbedding
from llama_index.core.schema import BaseNode, ImageNode, MetadataMode
from llama_index.core.utils import globals_helper, truncate_text
from llama_index.co... | Get image embeddings of the given nodes, run image embedding model if necessary. Args: nodes (Sequence[ImageNode]): The nodes to embed. embed_model (MultiModalEmbedding): The embedding model to use. show_progress (bool): Whether to show progress bar. Returns: Dict[str, List[float]]: A map from node id to embedding. |
36,132 | import logging
from typing import Any, List, Optional, Sequence
from llama_index.core.indices.base import BaseIndex
from llama_index.core.indices.composability.graph import ComposableGraph
from llama_index.core.indices.registry import INDEX_STRUCT_TYPE_TO_INDEX_CLASS
from llama_index.core.storage.storage_context import... | Load index from storage context. Args: storage_context (StorageContext): storage context containing docstore, index store and vector store. index_id (Optional[str]): ID of the index to load. Defaults to None, which assumes there's only a single index in the index store and load it. **kwargs: Additional keyword args to ... |
36,133 | import logging
from typing import Any, List, Optional, Sequence
from llama_index.core.indices.base import BaseIndex
from llama_index.core.indices.composability.graph import ComposableGraph
from llama_index.core.indices.registry import INDEX_STRUCT_TYPE_TO_INDEX_CLASS
from llama_index.core.storage.storage_context import... | Load composable graph from storage context. Args: storage_context (StorageContext): storage context containing docstore, index store and vector store. root_id (str): ID of the root index of the graph. **kwargs: Additional keyword args to pass to the index constructors. |
36,134 | from typing import List, Optional
from llama_index.core.node_parser.text import TokenTextSplitter
from llama_index.core.node_parser.text.utils import truncate_text
from llama_index.core.schema import BaseNode
def truncate_text(text: str, text_splitter: TextSplitter) -> str:
"""Truncate text to fit within the chunk... | Get text from nodes in the format of a numbered list. Used by tree-structured indices. |
36,135 | import logging
from typing import Any, Dict, List, Optional, cast
from llama_index.core.base.base_retriever import BaseRetriever
from llama_index.core.base.response.schema import Response
from llama_index.core.callbacks.base import CallbackManager
from llama_index.core.indices.prompt_helper import PromptHelper
from lla... | Get text from node. |
36,136 | import json
import logging
import re
from typing import Any, Callable, Dict, List, Optional, Union
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.base.response.schema import Response
from llama_index.core.llms.llm import LLM
from llama_index.core.prompts import BasePromptTempl... | Attempts to parse the JSON path prompt output. Only applicable if the default prompt is used. |
36,137 | import json
import logging
import re
from typing import Any, Callable, Dict, List, Optional, Union
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.base.response.schema import Response
from llama_index.core.llms.llm import LLM
from llama_index.core.prompts import BasePromptTempl... | Default output processor that extracts values based on JSON Path expressions. |
36,138 | import re
from typing import Any, Callable, Dict, Generic, Optional, Sequence, TypeVar
from llama_index.core.data_structs.table import BaseStructTable
from llama_index.core.indices.base import BaseIndex
from llama_index.core.prompts import BasePromptTemplate
from llama_index.core.prompts.default_prompts import DEFAULT_... | Parse output of schema extraction. Attempt to parse the following format from the default prompt: field1: <value>, field2: <value>, ... |
36,139 | import logging
from abc import abstractmethod
from typing import Any, Dict, List, Optional, Tuple, Union, cast
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.base.response.schema import Response
from llama_index.core.callbacks import CallbackManager
from llama_index.core.indic... | Validate prompt. |
36,140 | import heapq
import math
from typing import Any, Callable, List, Optional, Tuple
import numpy as np
from llama_index.core.base.embeddings.base import similarity as default_similarity_fn
from llama_index.core.vector_stores.types import VectorStoreQueryMode
class VectorStoreQueryMode(str, Enum):
"""Vector store quer... | Get top embeddings by fitting a learner against query. Inspired by Karpathy's SVM demo: https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb Can fit SVM, linear regression, and more. |
36,141 | import heapq
import math
from typing import Any, Callable, List, Optional, Tuple
import numpy as np
from llama_index.core.base.embeddings.base import similarity as default_similarity_fn
from llama_index.core.vector_stores.types import VectorStoreQueryMode
def similarity(
embedding1: Embedding,
embedding2: Embe... | Get top nodes by similarity to the query, discount by their similarity to previous results. A mmr_threshold of 0 will strongly avoid similarity to previous results. A mmr_threshold of 1 will check similarity the query and ignore previous results. |
36,142 | from typing import Generator
The provided code snippet includes necessary dependencies for implementing the `get_response_text` function. Write a Python function `def get_response_text(response_gen: Generator) -> str` to solve the following problem:
Get response text.
Here is the function:
def get_response_text(resp... | Get response text. |
36,143 | import textwrap
from pprint import pprint
from typing import Any, Dict
from llama_index.core.base.response.schema import Response
from llama_index.core.schema import NodeWithScore
from llama_index.core.utils import truncate_text
The provided code snippet includes necessary dependencies for implementing the `pprint_met... | Display metadata for jupyter notebook. |
36,144 | import textwrap
from pprint import pprint
from typing import Any, Dict
from llama_index.core.base.response.schema import Response
from llama_index.core.schema import NodeWithScore
from llama_index.core.utils import truncate_text
def pprint_source_node(
source_node: NodeWithScore, source_length: int = 350, wrap_widt... | Pretty print response for jupyter notebook. |
36,145 | import os
from io import BytesIO
from typing import Any, Dict, List, Tuple
import matplotlib.pyplot as plt
import requests
from IPython.display import Markdown, display
from llama_index.core.base.response.schema import Response
from llama_index.core.img_utils import b64_2_img
from llama_index.core.schema import ImageNo... | Display base64 encoded image str as image for jupyter notebook. |
36,146 | import os
from io import BytesIO
from typing import Any, Dict, List, Tuple
import matplotlib.pyplot as plt
import requests
from IPython.display import Markdown, display
from llama_index.core.base.response.schema import Response
from llama_index.core.img_utils import b64_2_img
from llama_index.core.schema import ImageNo... | Display response for jupyter notebook. |
36,147 | import os
from io import BytesIO
from typing import Any, Dict, List, Tuple
import matplotlib.pyplot as plt
import requests
from IPython.display import Markdown, display
from llama_index.core.base.response.schema import Response
from llama_index.core.img_utils import b64_2_img
from llama_index.core.schema import ImageNo... | For displaying a query and its multi-modal response. |
36,148 | from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence
from llama_index.core.base.base_selector import (
BaseSelector,
MultiSelection,
SelectorResult,
SingleSelection,
)
from llama_index.core.prompts.mixin import PromptDictType
from llama_index.core.schema import QueryBundle
from llama_index.co... | Convert pydantic output to selector result. Takes into account zero-indexing on answer indexes. |
36,149 | from typing import Optional
from llama_index.core.base.base_selector import BaseSelector
from llama_index.core.llms.llm import LLM
from llama_index.core.selectors.llm_selectors import (
LLMMultiSelector,
LLMSingleSelector,
)
from llama_index.core.selectors.pydantic_selectors import (
PydanticMultiSelector,
... | Get a selector from a service context. Prefers Pydantic selectors if possible. |
36,152 | from typing import Any, Dict, List, Optional, Sequence, cast
from llama_index.core.base.base_selector import (
BaseSelector,
SelectorResult,
SingleSelection,
)
from llama_index.core.output_parsers.base import StructuredOutput
from llama_index.core.output_parsers.selection import Answer, SelectionOutputParse... | Convert sequence of metadata to enumeration text. |
36,153 | from typing import Any, Dict, List, Optional, Sequence, cast
from llama_index.core.base.base_selector import (
BaseSelector,
SelectorResult,
SingleSelection,
)
from llama_index.core.output_parsers.base import StructuredOutput
from llama_index.core.output_parsers.selection import Answer, SelectionOutputParse... | Convert structured output to selector result. |
36,154 | import argparse
from typing import Any, Optional
from llama_index.cli.rag import RagCLI, default_ragcli_persist_dir
from llama_index.cli.upgrade import upgrade_dir, upgrade_file
from llama_index.core.ingestion import IngestionCache, IngestionPipeline
from llama_index.core.download.module import LLAMA_HUB_URL
from llama... | null |
36,155 | import argparse
from typing import Any, Optional
from llama_index.cli.rag import RagCLI, default_ragcli_persist_dir
from llama_index.cli.upgrade import upgrade_dir, upgrade_file
from llama_index.core.ingestion import IngestionCache, IngestionPipeline
from llama_index.core.download.module import LLAMA_HUB_URL
from llama... | null |
36,156 | import argparse
from typing import Any, Optional
from llama_index.cli.rag import RagCLI, default_ragcli_persist_dir
from llama_index.cli.upgrade import upgrade_dir, upgrade_file
from llama_index.core.ingestion import IngestionCache, IngestionPipeline
from llama_index.core.download.module import LLAMA_HUB_URL
from llama... | null |
36,157 | import argparse
from typing import Any, Optional
from llama_index.cli.rag import RagCLI, default_ragcli_persist_dir
from llama_index.cli.upgrade import upgrade_dir, upgrade_file
from llama_index.core.ingestion import IngestionCache, IngestionPipeline
from llama_index.core.download.module import LLAMA_HUB_URL
from llama... | null |
36,158 | 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.core import (
SimpleDirectoryReader,
VectorStoreIndex,
)
from llama_index.core.base.embeddings.base import Bas... | null |
36,159 | 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.core import (
SimpleDirectoryReader,
VectorStoreIndex,
)
from llama_index.core.base.embeddings.base import Bas... | null |
36,160 | 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.core import (
SimpleDirectoryReader,
VectorStoreIndex,
)
from llama_index.core.base.embeddings.base import Bas... | null |
36,161 | import json
import os
import re
from pathlib import Path
from typing import Dict, List, Tuple
def upgrade_file(file_path: str) -> None:
if file_path.endswith(".ipynb"):
upgrade_nb_file(file_path)
elif file_path.endswith((".py", ".md")):
upgrade_py_md_file(file_path)
else:
raise Excep... | null |
36,162 | from llama_index.core.schema import TextNode
from llama_index.core import Settings
from llama_index.core import VectorStoreIndex
import pandas as pd
from tqdm import tqdm
class TextNode(BaseNode):
text: str = Field(default="", description="Text content of the node.")
start_char_idx: Optional[int] = Field(
... | null |
36,163 | from llama_index.core.schema import TextNode
from llama_index.core import Settings
from llama_index.core import VectorStoreIndex
import pandas as pd
from tqdm import tqdm
The provided code snippet includes necessary dependencies for implementing the `display_results` function. Write a Python function `def display_resu... | Display results from evaluate. |
36,164 | from copy import deepcopy
from typing import TYPE_CHECKING, Any, Callable, Optional
from deprecated import deprecated
from llama_index.core.output_parsers.base import ChainableOutputParser
from guardrails import Guard
The provided code snippet includes necessary dependencies for implementing the `get_callable` functio... | Get callable. |
36,165 | import json
from typing import Any, Dict, Sequence, Tuple
import httpx
from httpx import Timeout
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseGen,
CompletionResponse,
CompletionResponseGen,
LLMMetadata,
MessageRole,
)
from llama_index.core.bridge.pyda... | null |
36,166 | import logging
from threading import Thread
from typing import Any, Callable, Dict, List, Optional, Sequence, Union
import torch
from huggingface_hub import AsyncInferenceClient, InferenceClient, model_info
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.inference._types import ConversationalOutput
fr... | Convert ChatMessages to keyword arguments for Inference API conversational. |
36,167 | from typing import List, Sequence
from llama_index.core.base.llms.types import ChatMessage, LLMMetadata, MessageRole
from llama_index.core.constants import AI21_J2_CONTEXT_WINDOW, COHERE_CONTEXT_WINDOW
from llama_index.llms.anyscale.utils import anyscale_modelname_to_contextsize
from llama_index.llms.fireworks.utils im... | null |
36,168 | from typing import List, Sequence
from llama_index.core.base.llms.types import ChatMessage, LLMMetadata, MessageRole
from llama_index.core.constants import AI21_J2_CONTEXT_WINDOW, COHERE_CONTEXT_WINDOW
from llama_index.llms.anyscale.utils import anyscale_modelname_to_contextsize
from llama_index.llms.fireworks.utils im... | null |
36,169 | from typing import List, Sequence
from llama_index.core.base.llms.types import ChatMessage, LLMMetadata, MessageRole
from llama_index.core.constants import AI21_J2_CONTEXT_WINDOW, COHERE_CONTEXT_WINDOW
from llama_index.llms.anyscale.utils import anyscale_modelname_to_contextsize
from llama_index.llms.fireworks.utils im... | Get LLM metadata from llm. |
36,170 | from typing import Optional
from llama_index.core.base.llms.types import ChatMessage
from typing_extensions import NotRequired, TypedDict
class ChatCompletionMessage(TypedDict):
class ChatMessage(BaseModel):
def __str__(self) -> str:
def from_str(
cls,
content: str,
role: ... | null |
36,171 | from typing import Optional
from llama_index.core.base.llms.types import ChatMessage
from typing_extensions import NotRequired, TypedDict
XINFERENCE_MODEL_SIZES = {
"baichuan": 2048,
"baichuan-chat": 2048,
"wizardlm-v1.0": 2048,
"vicuna-v1.3": 2048,
"orca": 2048,
"chatglm": 2048,
"chatglm2":... | null |
36,172 | import logging
from importlib.metadata import version
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type
import openai
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.base.llms.generic_utils import get_from_... | Use tenacity to retry the completion call. |
36,173 | import logging
from importlib.metadata import version
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type
import openai
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.base.llms.generic_utils import get_from_... | Convert generic messages to OpenAI message dicts. |
36,174 | import logging
from importlib.metadata import version
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type
import openai
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.base.llms.generic_utils import get_from_... | Convert openai message dicts to generic messages. |
36,175 | import logging
from importlib.metadata import version
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type
import openai
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.base.llms.generic_utils import get_from_... | Convert pydantic class to OpenAI function. |
36,176 | import logging
from importlib.metadata import version
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type
import openai
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.base.llms.generic_utils import get_from_... | "Resolve KonkoAI credentials. The order of precedence is: 1. param 2. env 3. konkoai module 4. default |
36,177 | import logging
from importlib.metadata import version
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type
import openai
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.base.llms.generic_utils import get_from_... | Use tenacity to retry the async completion call. |
36,178 | import logging
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Sequence
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.base.llms.generic_utils import (
prompt_to_messages,
)
from llama_index.llms.anthropic.utils import messages_to_anthropic_prompt
from... | null |
36,179 | import logging
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Sequence
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.base.llms.generic_utils import (
prompt_to_messages,
)
from llama_index.llms.anthropic.utils import messages_to_anthropic_prompt
from... | null |
36,180 | import logging
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Sequence
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.base.llms.generic_utils import (
prompt_to_messages,
)
from llama_index.llms.anthropic.utils import messages_to_anthropic_prompt
from... | Use tenacity to retry the completion call. |
36,181 | from typing import List, Optional, Sequence
from llama_index.core.base.llms.types import ChatMessage, MessageRole
BOS, EOS = "<s>", "</s>"
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. \
Always answer as... | null |
36,182 | from typing import List, Optional, Sequence
from llama_index.core.base.llms.types import ChatMessage, MessageRole
BOS, EOS = "<s>", "</s>"
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. \
Always answer as... | null |
36,183 | from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.base.llms.generic_utils import get_from_param_or_env
def is_function_calling_model(model: str) -> bool:
return "function" in model | null |
36,184 | from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.base.llms.generic_utils import get_from_param_or_env
def _message_to_fireworks_prompt(message: ChatMessage) -> Dict[str, Any]:
if message.role == MessageRole.USER... | null |
36,185 | from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.base.llms.generic_utils import get_from_param_or_env
DEFAULT_FIREWORKS_API_BASE = "https://api.fireworks.ai/inference/v1"
DEFAULT_FIREWORKS_API_VERSION = ""
def get_... | "Resolve OpenAI credentials. The order of precedence is: 1. param 2. env 3. openai module 4. default |
36,186 | from typing import TYPE_CHECKING, List
from llama_index.core.base.llms.types import LLMMetadata
from llama_index.llms.anthropic import Anthropic
from llama_index.llms.anthropic.utils import CLAUDE_MODELS
from llama_index.llms.openai import OpenAI
from llama_index.llms.openai.utils import (
AZURE_TURBO_MODELS,
G... | Generate metadata for a Language Model (LLM) instance. This function takes an instance of a Language Model (LLM) and generates metadata based on the provided instance. The metadata includes information such as the context window, number of output tokens, chat model status, and model name. Parameters: llm (LLM): An inst... |
36,187 | from typing import TYPE_CHECKING, List
from llama_index.core.base.llms.types import LLMMetadata
from llama_index.llms.anthropic import Anthropic
from llama_index.llms.anthropic.utils import CLAUDE_MODELS
from llama_index.llms.openai import OpenAI
from llama_index.llms.openai.utils import (
AZURE_TURBO_MODELS,
G... | null |
36,188 | from typing import Dict, List, Sequence
from llama_index.core.base.llms.types import (
ChatResponse,
CompletionResponse,
ChatMessage,
)
class ChatMessage(BaseModel):
"""Chat message."""
role: MessageRole = MessageRole.USER
content: Optional[Any] = ""
additional_kwargs: dict = Field(default... | null |
36,189 | from typing import Dict, List, Sequence
from llama_index.core.base.llms.types import (
ChatResponse,
CompletionResponse,
ChatMessage,
)
class CompletionResponse(BaseModel):
"""
Completion response.
Fields:
text: Text content of the response if not streaming, or if streaming,
... | null |
36,190 | from typing import Dict, List, Sequence
from llama_index.core.base.llms.types import (
ChatResponse,
CompletionResponse,
ChatMessage,
)
class ChatMessage(BaseModel):
"""Chat message."""
role: MessageRole = MessageRole.USER
content: Optional[Any] = ""
additional_kwargs: dict = Field(default... | null |
36,191 | from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.base.llms.generic_utils import get_from_param_or_env
def _message_to_anyscale_prompt(message: ChatMessage) -> Dict[str, Any]:
class ChatMessage(BaseModel):
def ... | null |
36,192 | from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.base.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_fr... | "Resolve OpenAI credentials. The order of precedence is: 1. param 2. env 3. openai module 4. default |
36,193 | from typing import Union
import google.ai.generativelanguage as glm
import google.generativeai as genai
import PIL
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
CompletionResponse,
)
from llama_index.core.utilities.gemini_utils import ROLES_FROM_GEMINI, ROLES_TO_GEMINI
def _error... | null |
36,194 | from typing import Union
import google.ai.generativelanguage as glm
import google.generativeai as genai
import PIL
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
CompletionResponse,
)
from llama_index.core.utilities.gemini_utils import ROLES_FROM_GEMINI, ROLES_TO_GEMINI
def _error... | null |
36,195 | from typing import Union
import google.ai.generativelanguage as glm
import google.generativeai as genai
import PIL
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
CompletionResponse,
)
from llama_index.core.utilities.gemini_utils import ROLES_FROM_GEMINI, ROLES_TO_GEMINI
try:
... | Convert ChatMessages to Gemini-specific history, including ImageDocuments. |
36,196 | from http import HTTPStatus
from typing import Any, Dict, List, Sequence
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
CompletionResponse,
)
class CompletionResponse(BaseModel):
"""
Completion response.
Fields:
text: Text content of the response if not strea... | null |
36,197 | from http import HTTPStatus
from typing import Any, Dict, List, Sequence
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
CompletionResponse,
)
class ChatMessage(BaseModel):
"""Chat message."""
role: MessageRole = MessageRole.USER
content: Optional[Any] = ""
additi... | null |
36,198 | from http import HTTPStatus
from typing import Any, Dict, List, Sequence
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
CompletionResponse,
)
class ChatMessage(BaseModel):
"""Chat message."""
role: MessageRole = MessageRole.USER
content: Optional[Any] = ""
additi... | null |
36,199 | from http import HTTPStatus
from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseGen,
CompletionResponse,
CompletionResponseGen,
LLMMetadata,
MessageRole,
)
from llama_index.core.bridge.pydantic im... | null |
36,200 | from typing import Any, Dict, Sequence
from llama_index.core.base.llms.types import ChatMessage
ALL_AVAILABLE_MODELS = {
**LLAMA_MODELS,
**MISTRAL_MODELS,
**GEMMA_MODELS,
}
The provided code snippet includes necessary dependencies for implementing the `friendli_modelname_to_contextsize` function. Write a P... | Get a context size of a model from its name. Args: modelname (str): The name of model. Returns: int: Context size of the model. |
36,201 | from typing import Any, Dict, Sequence
from llama_index.core.base.llms.types import ChatMessage
class ChatMessage(BaseModel):
"""Chat message."""
role: MessageRole = MessageRole.USER
content: Optional[Any] = ""
additional_kwargs: dict = Field(default_factory=dict)
def __str__(self) -> str:
... | Get messages for the Friendli chat request. |
36,202 | from typing import Union
COMPLETE_MODELS = {"j2-light": 8191, "j2-mid": 8191, "j2-ultra": 8191}
The provided code snippet includes necessary dependencies for implementing the `ai21_model_to_context_size` function. Write a Python function `def ai21_model_to_context_size(model: str) -> Union[int, None]` to solve the fol... | Calculate the maximum number of tokens possible to generate for a model. Args: model: The modelname we want to know the context size for. Returns: The maximum context size |
36,203 | from typing import Dict, Sequence, Tuple
from llama_index.core.base.llms.types import ChatMessage, MessageRole
CLAUDE_MODELS: Dict[str, int] = {
"claude-instant-1": 100000,
"claude-instant-1.2": 100000,
"claude-2": 100000,
"claude-2.0": 100000,
"claude-2.1": 200000,
"claude-3-opus-20240229": 180... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.