id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
35,902
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings temporar...
null
35,903
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings class Te...
null
35,904
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings def add...
null
35,905
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings class Te...
null
35,906
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings tokenfil...
This function will log out if not logged in
35,907
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings tokenfil...
This function will return if the user is logged in logged_in = __is_logged_in(temp_folder) is not None
35,908
import argparse import sys import traceback import warnings import os import platform import runpy import time import requests import json import zipfile import tempfile import webbrowser from blankly.deployment.api import API from blankly.utils.utils import load_json_file, info_print, load_deployment_settings token = ...
null
35,909
import argparse import json import os.path import shutil import subprocess import sys import tempfile import traceback import webbrowser from pathlib import Path from typing import Optional import pkgutil from questionary import Choice from blankly.deployment.api import API from blankly.deployment.deploy import zip_dir...
null
35,910
import argparse import json import os.path import shutil import subprocess import sys import tempfile import traceback import webbrowser from pathlib import Path from typing import Optional import pkgutil from questionary import Choice from blankly.deployment.api import API from blankly.deployment.deploy import zip_dir...
null
35,911
import argparse import json import os.path import shutil import subprocess import sys import tempfile import traceback import webbrowser from pathlib import Path from typing import Optional import pkgutil from questionary import Choice from blankly.deployment.api import API from blankly.deployment.deploy import zip_dir...
null
35,912
import argparse import json import os.path import shutil import subprocess import sys import tempfile import traceback import webbrowser from pathlib import Path from typing import Optional import pkgutil from questionary import Choice from blankly.deployment.api import API from blankly.deployment.deploy import zip_dir...
null
35,913
import argparse import json import os.path import shutil import subprocess import sys import tempfile import traceback import webbrowser from pathlib import Path from typing import Optional import pkgutil from questionary import Choice from blankly.deployment.api import API from blankly.deployment.deploy import zip_dir...
null
35,914
import argparse import json import os.path import shutil import subprocess import sys import tempfile import traceback import webbrowser from pathlib import Path from typing import Optional import pkgutil from questionary import Choice from blankly.deployment.api import API from blankly.deployment.deploy import zip_dir...
null
35,915
import os import tempfile import sys import zipfile from typing import List def zipdir(path, ziph, ignore_files: list): # From https://stackoverflow.com/a/1855118/8087739 # Notice we're using this instead of shutil because it allows customization such as passwords and skipping # directories # ziph is zi...
null
35,916
import json import pathlib import sys import urllib.parse from http.server import BaseHTTPRequestHandler, HTTPServer from typing import Optional from blankly.deployment.api import API from blankly.deployment.ui import print_work, print_failure, print_success, show_spinner SUCCESS_URL = 'https://firebasestorage.googleap...
null
35,917
import json import pathlib import sys import urllib.parse from http.server import BaseHTTPRequestHandler, HTTPServer from typing import Optional from blankly.deployment.api import API from blankly.deployment.ui import print_work, print_failure, print_success, show_spinner def get_token_file() -> pathlib.Path: retur...
null
35,918
from typing import Dict, List import alpaca_trade_api from binance.client import Client as BinanceClient from questionary import Choice from blankly.deployment.ui import print_failure from blankly.exchanges.interfaces.alpaca import alpaca_api from blankly.exchanges.interfaces.coinbase_pro.coinbase_pro_api import API as...
null
35,919
from datetime import datetime as dt def is_datetime_naive(datetime_obj: dt): if datetime_obj.tzinfo is None or datetime_obj.tzinfo.utcoffset(datetime_obj) is None: return True return False
null
35,920
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def load_json_file(override_path=None): f = open(override_path, ) json_file = json....
null
35,921
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd backtest_settings = __BlanklySettings('./backtest.json', default_backtest_settings, ...
null
35,922
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd notify_settings = __BlanklySettings('./notify.json', default_notify_settings, ...
null
35,923
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `pretty_prin...
Json pretty printer for general string usage
35,924
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def epoch_from_iso8601(iso8601: str) -> float: import dateutil.parser as dp return d...
null
35,925
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def iso8601_from_epoch(epoch) -> str: return dt.utcfromtimestamp(epoch).isoformat() + '...
null
35,926
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def get_base_asset(symbol): # Gets the BTC of the BTC-USD return symbol.split('-')[0...
null
35,927
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `convert_epo...
If an epoch time is very long it means that it includes decimals - generally milliseconds. We like the decimal format because its unambiguous
35,928
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `compare_dic...
Compare two output dictionaries to check if they have the same keys (excluding "exchange_specific") Args: dict1 (dict): First dictionary to compare dict2 (dict): Second dictionary to compare force_exchange_specific (bool): Check if the the exchange_specific tag is in the dictionary Returns: bool: Are the non specific t...
35,929
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def update_progress(progress): # From this great post: https://stackoverflow.com/a/1586...
null
35,930
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def split_df(df, n): return df.groupby(np.arange(len(df)) // n) def get_ohlcv(candles, ...
null
35,931
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def split_df(df, n): return df.groupby(np.arange(len(df)) // n) The provided code snipp...
Aggregate history data (such as turn 1m data into 15m data) Args: history: A blankly generated dataframe aggregation_size: How many rows of history to aggregate - ex: aggregation_size=15 on 1m data produces 15m intervals
35,932
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `get_ohlcv_f...
Created with the purpose of parsing ticker data into a viable OHLCV pattern. The Args: tick_list (list): List of data containing price ticks. Needs to be at least: [{'price': 343, 'size': 3.4}, ...] The data must also be ordered oldest to most recent at the end last_price (float): The last price in case there isn't any...
35,933
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def ceil_date(date, **kwargs): secs = datetime.timedelta(**kwargs).total_seconds() ...
null
35,934
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def format_with_new_line(original_string, *components): for i in components: or...
null
35,935
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `trunc` func...
Truncate a number instead of rounding (ex: trunc(9.9999999, 2) == 9.99 instead of round(9.9999999, 2) == 10.0) Args: number (float): Number to truncate decimals (int): Number of decimals to keep: trunc(9.9999999, 2) == 9.99
35,936
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `count_decim...
Count the number of decimals in a given float: 1.4335 -> 4 or 3 -> 0
35,937
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `check_backt...
Tests if the environment is configured for backtesting. Primarily used for platform deployments but is applicable elsewhere
35,938
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def get_base_asset(symbol): # Gets the BTC of the BTC-USD return symbol.split('-')[0...
Used for get_account functions, this enforces that the user is always getting the base asset which is probably what the user meant
35,939
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `order_prote...
Decorator to provide protection against live orders inside backtest environment
35,940
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def get_base_asset(symbol): def get_quote_asset(symbol): def add_all_products(nonzero_produ...
null
35,941
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def increment_to_precision(increment: float) -> int: # quick maths # 0.0001 -> 4 ...
null
35,942
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def precision_to_increment(precision: int) -> float: return 10 ** (-precision)
null
35,943
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def aggregate_prices_by_resolution(price_dict, symbol_, resolution_, data_) -> dict: if...
null
35,944
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def trim_df_time_column(df, epoch_start: [int, float], epoch_stop: [int, float]): df = d...
null
35,945
import math import blankly import datetime import json import sys import decimal import os from datetime import datetime as dt from math import trunc as math_trunc from typing import Union import numpy as np import pandas as pd def build_order_info(price, side, size, symbol, type_) -> dict: order = { 'size...
null
35,946
from typing import Union from numpy import int64, int32 def build_second() -> int: return 1 def build_minute() -> int: return build_second() * 60 def build_hour() -> int: return build_minute() * 60 def build_day() -> int: return build_hour() * 24 def build_week() -> int: return build_day() * 7 def b...
Extract the number of seconds in an interval string
35,947
from typing import Union from numpy import int64, int32 def build_second() -> int: return 1 def build_minute() -> int: return build_second() * 60 def build_hour() -> int: return build_minute() * 60 def build_day() -> int: return build_hour() * 24 def build_week() -> int: return build_day() * 7 def b...
This function converts integer intervals into string intervals Example: 3600 -> 1h Args: interval: An integer representing the conversion time
35,948
from typing import Any, Dict, Optional, Sequence from llama_index.core.objects.base_node_mapping import ( DEFAULT_PERSIST_DIR, DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, ) from llama_index.core.schema import BaseNode, TextNode from llama_index.core.tools.query_engine import QueryEngineTool from llama_ind...
Function convert Tool to node.
35,949
import json from dataclasses import dataclass from typing import Any, List from dataclasses_json import DataClassJsonMixin from llama_index.core.output_parsers.base import ( OutputParserException, StructuredOutput, ) from llama_index.core.output_parsers.utils import _marshal_llm_to_json from llama_index.core.ty...
null
35,950
from typing import TYPE_CHECKING, Optional, Union import os from llama_index.core.llms.callbacks import CallbackManager from llama_index.core.llms.llm import LLM from llama_index.core.llms.mock import MockLLM LLMType = Union[str, LLM, "BaseLanguageModel"] class LLM(BaseLLM): system_prompt: Optional[str] = Field( ...
Resolve LLM from string or LLM instance.
35,951
from collections import ChainMap from typing import ( Any, Callable, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen,...
Convert a stream completion response to a stream of tokens.
35,952
from collections import ChainMap from typing import ( Any, Callable, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen,...
Convert a stream completion response to a stream of tokens.
35,953
from collections import ChainMap from typing import ( Any, Callable, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen,...
Convert a stream completion response to a stream of tokens.
35,954
from collections import ChainMap from typing import ( Any, Callable, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen,...
Convert a stream completion response to a stream of tokens.
35,955
from collections import ChainMap from typing import ( Any, Callable, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen,...
null
35,956
from typing import Dict, Type from llama_index.core.llms.custom import CustomLLM from llama_index.core.llms.llm import LLM from llama_index.core.llms.mock import MockLLM RECOGNIZED_LLMS: Dict[str, Type[LLM]] = { MockLLM.class_name(): MockLLM, CustomLLM.class_name(): CustomLLM, } class LLM(BaseLLM): system_...
Load LLM by name.
35,957
import asyncio from contextlib import contextmanager from typing import ( Any, AsyncGenerator, Callable, Generator, Sequence, cast, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, Compl...
null
35,958
import asyncio from contextlib import contextmanager from typing import ( Any, AsyncGenerator, Callable, Generator, Sequence, cast, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, Compl...
null
35,959
from typing import List, Optional, Sequence from llama_index.core.base.llms.types import ChatMessage, MessageRole B_SYS = "<|im_start|>system\n" B_USER = "<|im_start|>user\n" B_ASSISTANT = "<|im_start|>assistant\n" END = "<|im_end|>\n" DEFAULT_SYSTEM_PROMPT = """\ You are a helpful, respectful and honest assistant. \ A...
null
35,960
from typing import List, Optional, Sequence from llama_index.core.base.llms.types import ChatMessage, MessageRole B_SYS = "<|im_start|>system\n" B_USER = "<|im_start|>user\n" B_ASSISTANT = "<|im_start|>assistant\n" END = "<|im_end|>\n" DEFAULT_SYSTEM_PROMPT = """\ You are a helpful, respectful and honest assistant. \ A...
null
35,961
import json from typing import Sequence from llama_index.core.prompts.base import PromptTemplate from llama_index.core.question_gen.types import SubQuestion from llama_index.core.tools.types import ToolMetadata class ToolMetadata: description: str name: Optional[str] = None fn_schema: Optional[Type[BaseMod...
null
35,962
import base64 from io import BytesIO from typing import cast from PIL import Image The provided code snippet includes necessary dependencies for implementing the `img_2_b64` function. Write a Python function `def img_2_b64(image: Image, format: str = "JPEG") -> str` to solve the following problem: Convert a PIL.Image ...
Convert a PIL.Image to a base64 encoded image str.
35,963
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Get a new ID.
35,964
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Get a new integer ID.
35,965
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Temporary setter. Utility class for setting a temporary value for an attribute on a class. Taken from: https://tinyurl.com/2p89xymh
35,966
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Execute lambda function with retries and exponential backoff. Args: lambda_fn (Callable): Function to be called and output we want. errors_to_retry (List[ErrorToRetry]): List of errors to retry. At least one needs to be provided. max_tries (int): Maximum number of tries, including the first. Defaults to 10. min_backoff...
35,967
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Iterate over an iterable in batches. >>> list(iter_batch([1,2,3,4,5], 3)) [[1, 2, 3], [4, 5]]
35,968
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Append basename to dirname, avoiding backslashes when running on windows. os.path.join(dirname, basename) will add a backslash before dirname if basename does not end with a slash, so we make sure it does.
35,969
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Optionally get a tqdm iterable. Ensures tqdm.auto is used.
35,970
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
null
35,971
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Args: model_name(str): the model name of the tokenizer. For instance, fxmarty/tiny-llama-fast-tokenizer.
35,972
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Decorator for adding sync version of an async function. The sync version is added as a function attribute to the original function, func. Args: func(Any): the async function for which a sync variant will be built.
35,973
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Get a mapping of items to colors. Args: items (List[str]): List of items to be mapped to colors. use_llama_index_colors (bool, optional): Flag to indicate whether to use LlamaIndex colors or ANSI colors. Defaults to True. Returns: Dict[str, str]: Mapping of items to colors.
35,974
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
Infer the input to torch.device.
35,975
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
A function that returns a generator of a single element. Args: x (Any): the element to build yield Yields: Any: the single element
35,976
import asyncio import os import random import sys import time import traceback import uuid from contextlib import contextmanager from dataclasses import dataclass from functools import partial, wraps from itertools import islice from pathlib import Path from typing import ( Any, AsyncGenerator, Callable, ...
A function that returns a generator of a single element. Args: x (Any): the element to build yield Yields: Any: the single element
35,977
import json import os import re from pathlib import Path from typing import Dict, List, Tuple def upgrade_file(file_path: str) -> None: def _is_hidden(path: Path) -> bool: def upgrade_dir(input_dir: str) -> None: file_refs = list(Path(input_dir).rglob("*.py")) file_refs += list(Path(input_dir).rglob("*.ipynb")...
null
35,978
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast from deprecated import deprecated import llama_index.core from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.callbacks.base import CallbackManager from llama_index.core.base.embeddings.base import Bas...
Get default node parser.
35,979
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast from deprecated import deprecated import llama_index.core from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.callbacks.base import CallbackManager from llama_index.core.base.embeddings.base import Bas...
Get default prompt helper.
35,980
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast from deprecated import deprecated import llama_index.core from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.callbacks.base import CallbackManager from llama_index.core.base.embeddings.base import Bas...
Helper function to set the global service context.
35,981
from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, cast from llama_index.core.callbacks.base_handler import BaseCallbackHandler from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.core.utilities.token_counting import TokenCounter from llama_ind...
null
35,982
import asyncio import functools import logging from typing import Any, Callable, cast from llama_index.core.callbacks.base import CallbackManager logger = logging.getLogger(__name__) class CallbackManager(BaseCallbackHandler, ABC): """ Callback manager that handles callbacks for events within LlamaIndex. ...
Decorator to trace a method. Example: @trace_method("my_trace_id") def my_method(self): pass Assumes that the self instance has a CallbackManager instance in an attribute named `callback_manager`. This can be overridden by passing in a `callback_manager_attr` keyword argument.
35,983
from typing import Any from llama_index.core.callbacks.base_handler import BaseCallbackHandler from llama_index.core.callbacks.simple_llm_handler import SimpleLLMHandler def create_global_handler(eval_mode: str, **eval_params: Any) -> BaseCallbackHandler: """Get global eval handler.""" if eval_mode == "wandb": ...
Set global eval handlers.
35,984
import json import re import uuid from typing import Dict, List, Tuple from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.llms.utils import LLM from llama_index.core.schema import MetadataMode, TextNode from tqdm import tqdm class EmbeddingQAFinetuneDataset(BaseModel): """Embedding QA Fine...
Generate examples given a set of nodes.
35,985
import ast import copy from types import CodeType, ModuleType from typing import Any, Dict, Mapping, Sequence, Union ALLOWED_IMPORTS = { "math", "time", "datetime", "pandas", "scipy", "numpy", "matplotlib", "plotly", "seaborn", } def _restricted_import( name: str, globals: U...
null
35,986
import warnings from typing import Any, List, Type from llama_index.core.bridge.pydantic import BaseModel, Field, create_model from llama_index.core.llms.llm import LLM from llama_index.core.output_parsers.pydantic import PydanticOutputParser from llama_index.core.prompts.base import PromptTemplate from llama_index.cor...
Create a list version of an existing Pydantic object.
35,987
import warnings from typing import Any, List, Type from llama_index.core.bridge.pydantic import BaseModel, Field, create_model from llama_index.core.llms.llm import LLM from llama_index.core.output_parsers.pydantic import PydanticOutputParser from llama_index.core.prompts.base import PromptTemplate from llama_index.cor...
Get a program based on the compatible LLM.
35,988
from llama_index.core.extractors.metadata_extractors import ( BaseExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor, ) class TitleExtractor(BaseExtractor): """Title extractor. Useful for long documents. Extracts `document_title` metadata field. A...
null
35,989
import os from typing import TYPE_CHECKING, List, Optional, Union from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks import CallbackManager from llama_index.core.embeddings.mock_embed_model import MockEmbedding from llama_index.core.utils import get_cache_dir The provided c...
Save embedding to file.
35,990
import os from typing import TYPE_CHECKING, List, Optional, Union from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks import CallbackManager from llama_index.core.embeddings.mock_embed_model import MockEmbedding from llama_index.core.utils import get_cache_dir The provided c...
Load embedding from file. Will only return first embedding in file.
35,991
import os from typing import TYPE_CHECKING, List, Optional, Union from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks import CallbackManager from llama_index.core.embeddings.mock_embed_model import MockEmbedding from llama_index.core.utils import get_cache_dir EmbedType = Uni...
Resolve embed model.
35,992
from typing import Dict, Type from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding RECOGNIZED_EMBEDDINGS: Dict[str, Type[BaseEmbedding]] = { MockEmbedding.class_name(): MockEmbedding, } class BaseEmbedding(TransformComponent): ""...
Load Embedding by name.
35,993
from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, MessageRole, ) from llama_index.core.types import TokenGen class MessageRole(str, Enum): """Message role.""" SYSTEM = "system" USER = "user" ASSISTANT = "assistant" FUNCTION = "function" ...
null
35,994
import asyncio import logging import queue import time from abc import ABC, abstractmethod from dataclasses import dataclass, field from enum import Enum from threading import Event from typing import AsyncGenerator, Generator, List, Optional, Union from llama_index.core.base.llms.types import ( ChatMessage, Ch...
Utility for ChatMessage responses from OpenAI models.
35,995
import asyncio from itertools import zip_longest from typing import Any, Coroutine, Iterable, List The provided code snippet includes necessary dependencies for implementing the `run_async_tasks` function. Write a Python function `def run_async_tasks( tasks: List[Coroutine], show_progress: bool = False, pr...
Run a list of async tasks.
35,996
import asyncio from itertools import zip_longest from typing import Any, Coroutine, Iterable, List def chunks(iterable: Iterable, size: int) -> Iterable: args = [iter(iterable)] * size return zip_longest(*args, fillvalue=None) async def batch_gather( tasks: List[Coroutine], batch_size: int = 10, verbose: b...
null
35,997
import asyncio from itertools import zip_longest from typing import Any, Coroutine, Iterable, List def get_asyncio_module(show_progress: bool = False) -> Any: if show_progress: from tqdm.asyncio import tqdm_asyncio module = tqdm_asyncio else: module = asyncio return module DEFAULT_NU...
Run jobs. Args: jobs (List[Coroutine]): List of jobs to run. show_progress (bool): Whether to show progress bar. Returns: List[Any]: List of results.
35,998
from typing import TYPE_CHECKING, Optional def get_aws_service_client( service_name: Optional[str] = None, region_name: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, profile_name: Optional[str...
null
35,999
from collections.abc import Sequence from typing import Dict from llama_index.core.base.llms.types import ChatMessage, MessageRole ROLES_TO_GEMINI: Dict[MessageRole, MessageRole] = { MessageRole.USER: MessageRole.USER, MessageRole.ASSISTANT: MessageRole.MODEL, ## Gemini only has user and model roles. Put th...
null
36,000
import logging from typing import Any, Dict, List, Optional, Sequence from llama_index.core.bridge.pydantic import Field from llama_index.core.llms import LLM, ChatMessage, ChatResponse from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.prompts import BasePromptTemplate from ll...
null
36,001
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 forward nodes.