id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
27,830 | from typing import Any, Optional
import torch
def flash_attn_func(q, k, v, dropout=0.0, bias=None, softmax_scale=None, is_causal=False):
assert bias is None
attn, lse, _ = _flash_attn_func(q, k, v, dropout_p=dropout, softmax_scale=softmax_scale, causal=is_causal, return_attn_probs=True)... | null |
27,831 | import math
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from .moe_layer import fused_cumsum_sub_one, has_tutel
EVAL_CAPACITY_TOKEN_FRACTION = 0.25
SAMPLE_FRACTION = 0.2
def one_hot(indices: torch.Tensor, num_classes: int, unsqueeze_indices=Fal... | Implements Top2Gating on logits. |
27,832 | import math
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from .moe_layer import fused_cumsum_sub_one, has_tutel
SAMPLE_FRACTION = 0.2
def gumbel_rsample(shape: Tuple, device: torch.device) -> Tensor:
gumbel = gumbel_map.get(device)
if g... | Implements Top2Gating on logits. |
27,833 | import torch.distributed as dist
def _find_my_group_index(grouped_ranks):
my_rank = dist.get_rank()
for i, group in enumerate(grouped_ranks):
if my_rank in group:
return i
raise RuntimeError
def get_all2all_group(moe_expert_count):
if dist.is_initialized():
if not hasattr(ge... | null |
27,834 | import copy
import torch
import torch.nn as nn
class MultiwayNetwork(nn.Module):
def __init__(self, module, dim=1):
super().__init__()
self.dim = dim
self.A = module
self.B = copy.deepcopy(module)
self.B.reset_parameters()
self.split_position = -1
def forward(self... | null |
27,835 | import copy
import torch
import torch.nn as nn
def set_split_position(position):
def apply_fn(module):
if hasattr(module, "split_position"):
module.split_position = position
return apply_fn | null |
27,836 | import torch
import torch.nn.functional as F
from torch import nn
from .rms_norm import RMSNorm
from .multiway_network import MultiwayWrapper
The provided code snippet includes necessary dependencies for implementing the `duplicate_interleave` function. Write a Python function `def duplicate_interleave(m)` to solve th... | A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy. |
27,837 | import torch
import torch.nn.functional as F
from torch import nn
from .rms_norm import RMSNorm
from .multiway_network import MultiwayWrapper
def rotate_every_two(x):
x1 = x[:, :, :, ::2]
x2 = x[:, :, :, 1::2]
x = torch.stack((-x2, x1), dim=-1)
return x.flatten(-2) # in einsum notation: rearrange(x, '.... | null |
27,838 | import torch
import torch.nn.functional as F
from torch import nn
from .rms_norm import RMSNorm
from .multiway_network import MultiwayWrapper
def get_activation_fn(activation):
if activation == "swish":
return F.silu
elif activation == "gelu":
return F.gelu
else:
raise NotImplemente... | null |
27,839 | import torch.nn as nn
from torchscale.component.multihead_attention import MultiheadAttention
from torchscale.component.multiway_network import MultiwayNetwork
class MultiheadAttention(nn.Module):
def __init__(
self,
args,
embed_dim,
num_heads,
dropout=0.0,
self_atte... | null |
27,840 | from flask import Flask
import time
import random
import boto3
def log_metric(metric_name, value):
# Send custom metric to CloudWatch
cloudwatch.put_metric_data(
Namespace='OnlineStore',
MetricData=[{
'MetricName': metric_name,
'Value': value,
'Unit': 'Count'
... | null |
27,841 | from flask import Flask
import time
import random
import boto3
products = {
'1': {'name': 'Product 1', 'price': 10.99},
'2': {'name': 'Product 2', 'price': 19.99},
'3': {'name': 'Product 3', 'price': 5.49}
}
def log_metric(metric_name, value):
# Send custom metric to CloudWatch
cloudwatch.put_metric... | null |
27,842 | import time
def simulate_cpu_spike(duration=30, cpu_percent=80):
print(f"Simulating CPU spike at {cpu_percent}%...")
start_time = time.time()
# Calculate the number of iterations needed to achieve the desired CPU utilization
target_percent = cpu_percent / 100
total_iterations = int(target_percent ... | null |
27,843 | import boto3
import json
def lambda_handler(event, context):
# Get the specific EC2 instance.
ec2_client = boto3.client('ec2')
# Assume compliant by default
compliance_status = "COMPLIANT"
# Extract the configuration item from the invokingEvent
config = json.loads(event['invokingEv... | null |
27,844 | from flask import Flask
def hello():
return 'Hello, world!' | null |
27,845 | import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Get all EBS snapshots
response = ec2.describe_snapshots(OwnerIds=['self'])
# Get all active EC2 instance IDs
instances_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
... | null |
27,846 | from flask import Flask
def hello():
return 'Hello, Flask on Docker!' | null |
27,847 | from flask import Flask
def greet(name):
return f'Hello, {name}! Welcome to Flask on Docker.' | null |
27,848 | server_config = {
'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'},
'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'},
'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'}
}
def get_server_status(server_name):
return server_config.get(server_name, {}).... | null |
27,849 | from flask import Flask
def hello_world():
return 'Hello, World!' | null |
27,850 | import requests
from requests.auth import HTTPBasicAuth
import json
from flask import Flask
def createJira():
url = "https://veeramallaabhishek.atlassian.net/rest/api/3/issue"
API_TOKEN=""
auth = HTTPBasicAuth("", API_TOKEN)
headers = {
"Accept": "application/json",
"Content-Type": ... | null |
27,851 |
def update_server_config(file_path, key, value):
# Read the existing content of the server configuration file
with open(file_path, 'r') as file:
lines = file.readlines()
# Update the configuration value for the specified key
with open(file_path, 'w') as file:
for line in lines:
... | null |
27,852 | import os
def list_files_in_folder(folder_path):
try:
files = os.listdir(folder_path)
return files, None
except FileNotFoundError:
return None, "Folder not found"
except PermissionError:
return None, "Permission denied" | null |
27,853 | import importlib
import inspect
import os
import sys
import typing
from enum import Enum
from pathlib import Path
from typing import Dict, List, Literal, Optional, Sequence, TypedDict, Union
import toml
from pydantic import BaseModel
def _load_package_modules(
package_directory: Union[str, Path], submodule: Optiona... | Create a rst file for building of documentation. Args: package_name: Can be either "langchain" or "core" or "experimental". |
27,854 | import json
import os
import sys
from pathlib import Path
import toml
from docutils import nodes
from sphinx.util.docutils import SphinxDirective
class ExampleLinksDirective(SphinxDirective):
"""Directive to generate a list of links to examples.
We have a script that extracts links to API reference docs
fro... | null |
27,855 | import os
from pathlib import Path
from langchain_community import chat_models, llms
from langchain_core.language_models.chat_models import BaseChatModel, SimpleChatModel
from langchain_core.language_models.llms import LLM, BaseLLM
LLM_IGNORE = ("FakeListLLM", "OpenAIChat", "PromptLayerOpenAIChat")
LLM_FEAT_TABLE_CORRE... | null |
27,856 | import os
from pathlib import Path
from langchain_community import chat_models, llms
from langchain_core.language_models.chat_models import BaseChatModel, SimpleChatModel
from langchain_core.language_models.llms import LLM, BaseLLM
CHAT_MODEL_IGNORE = ("FakeListChatModel", "HumanInputChatModel")
CHAT_MODEL_FEAT_TABLE_C... | null |
27,857 | import os
import re
import sys
from pathlib import Path
DOCS_DIR = Path(os.path.abspath(__file__)).parents[1]
def update_links(doc_path, docs_link):
with open(DOCS_DIR / doc_path, "r") as f:
content = f.read()
# replace relative links
content = re.sub("\]\(\.\/", f"]({docs_link}", content)
wi... | null |
27,858 | import argparse
import importlib
import inspect
import json
import logging
import os
import re
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `find_files` function. Write a Python function `def find_files(path)` to solve the following problem:
Find all MDX files... | Find all MDX files in the given path |
27,859 | import argparse
import importlib
import inspect
import json
import logging
import os
import re
from pathlib import Path
_DOCS_DIR = _CURRENT_PATH / "docs"
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--docs_dir",
type=str,
default=_DOCS_DIR,
help="Dir... | null |
27,860 | import argparse
import importlib
import inspect
import json
import logging
import os
import re
from pathlib import Path
logger = logging.getLogger(__name__)
_BASE_URL = "https://api.python.langchain.com/en/latest/"
code_block_re = re.compile(r"^(```python\n)(.*?)(```\n)", re.DOTALL | re.MULTILINE)
_IMPORT_RE = re.compi... | Replace imports in each Python code block with links to their documentation and append the import info in a comment |
27,861 | import re
import xml.etree.ElementTree as ET
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union
from langchain_core.exceptions import OutputParserException
from langchain_core.messages import BaseMessage
from langchain_core.output_parsers.transform import BaseTransformOutputParser
from langcha... | Get nested element from path. |
27,862 | from __future__ import annotations
import json
import re
from json import JSONDecodeError
from typing import Any, Callable, List, Optional, Type
import jsonpatch
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers.format_instructions import JSON_FORMAT_INSTRUCTIONS
from langc... | Parse a JSON string from a Markdown string and check that it contains the expected keys. Args: text: The Markdown string. expected_keys: The expected keys in the JSON string. Returns: The parsed JSON object as a Python dictionary. |
27,863 | from __future__ import annotations
import re
from abc import abstractmethod
from collections import deque
from typing import AsyncIterator, Deque, Iterator, List, TypeVar, Union
from langchain_core.messages import BaseMessage
from langchain_core.output_parsers.transform import BaseTransformOutputParser
T = TypeVar("T")... | Drop the last n elements of an iterator. |
27,864 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type
from langchain_core.example_selectors.base import BaseExampleSelector
from langchain_core.pydantic_v1 import BaseModel, Extra
from langchain_core.vectorstores import VectorStore
The provided code snippet includes neces... | Return a list of values in dict sorted by key. |
27,865 | import re
from typing import Callable, Dict, List
from langchain_core.example_selectors.base import BaseExampleSelector
from langchain_core.prompts.prompt import PromptTemplate
from langchain_core.pydantic_v1 import BaseModel, validator
def _get_length_based(text: str) -> int:
return len(re.split("\n| ", text)) | null |
27,866 | from __future__ import annotations
import asyncio
import functools
import inspect
import json
import logging
import uuid
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
O... | Convert a sync iterator into an async iterator. |
27,867 | from __future__ import annotations
import asyncio
import functools
import inspect
import json
import logging
import uuid
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
O... | Get prompts that are already cached. |
27,868 | from __future__ import annotations
import asyncio
import functools
import inspect
import json
import logging
import uuid
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
O... | Get prompts that are already cached. Async version. |
27,869 | from __future__ import annotations
import asyncio
import functools
import inspect
import json
import logging
import uuid
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
O... | Update the cache and get the LLM output. |
27,870 | from __future__ import annotations
import asyncio
import functools
import inspect
import json
import logging
import uuid
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
O... | Update the cache and get the LLM output. Async version |
27,871 | from __future__ import annotations
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Mapping,
Optional,
Sequence,
Set,
Type,
TypeVar,
Union,
)
from typing_extensions import TypeAlias
from langchain_core._a... | Encode the text into token IDs. |
27,872 | from __future__ import annotations
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Mapping,
Optional,
Sequence,
Set,
Type,
TypeVar,
Union,
)
from typing_extensions import TypeAlias
from langchain_core._a... | null |
27,873 | from __future__ import annotations
import asyncio
import inspect
import uuid
import warnings
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Union,
cast,
)
from... | Generate from a stream. |
27,874 | from __future__ import annotations
import asyncio
import inspect
import uuid
import warnings
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Union,
cast,
)
from... | Async generate from a stream. |
27,875 | from __future__ import annotations
import asyncio
import inspect
import uuid
import warnings
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Union,
cast,
)
from... | Convert a sync iterator into an async iterator. |
27,876 | from __future__ import annotations
import asyncio
import inspect
import uuid
import warnings
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Union,
cast,
)
from... | null |
27,877 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
from langchain_core.load.serializable import Serializable
from langchain_core.pydantic_v1 import Extra, Field
from langchain_core.utils import get_bolded_text
from langchain_core.utils._merge import merge_dic... | Merge two message contents. Args: first_content: The first content. second_content: The second content. Returns: The merged content. |
27,878 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
from langchain_core.load.serializable import Serializable
from langchain_core.pydantic_v1 import Extra, Field
from langchain_core.utils import get_bolded_text
from langchain_core.utils._merge import merge_dic... | Convert a sequence of Messages to a list of dictionaries. Args: messages: Sequence of messages (as BaseMessages) to convert. Returns: List of messages as dicts. |
27,879 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
from langchain_core.load.serializable import Serializable
from langchain_core.pydantic_v1 import Extra, Field
from langchain_core.utils import get_bolded_text
from langchain_core.utils._merge import merge_dic... | Get a title representation for a message. Args: title: The title. bold: Whether to bold the title. Returns: The title representation. |
27,880 | from __future__ import annotations
import asyncio
import functools
import logging
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import copy_context
from typing import (
TYPE_CHECKING,
... | Get a callback manager for a chain group in a context manager. Useful for grouping different calls together as a single run even if they aren't composed in a single chain. Args: group_name (str): The name of the chain group. callback_manager (CallbackManager, optional): The callback manager to use. inputs (Dict[str, An... |
27,881 | from __future__ import annotations
import asyncio
import functools
import logging
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import copy_context
from typing import (
TYPE_CHECKING,
... | Get an async callback manager for a chain group in a context manager. Useful for grouping different async calls together as a single run even if they aren't composed in a single chain. Args: group_name (str): The name of the chain group. callback_manager (AsyncCallbackManager, optional): The async callback manager to u... |
27,882 | from __future__ import annotations
import asyncio
import functools
import logging
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import copy_context
from typing import (
TYPE_CHECKING,
... | Makes so an awaitable method is always shielded from cancellation |
27,883 | from __future__ import annotations
import asyncio
import functools
import logging
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import copy_context
from typing import (
TYPE_CHECKING,
... | Generic event handler for CallbackManager. Note: This function is used by langserve to handle events. Args: handlers: The list of handlers that will handle the event event_name: The name of the event (e.g., "on_llm_start") ignore_condition_name: Name of the attribute defined on handler that if True will cause the handl... |
27,884 | from __future__ import annotations
import asyncio
import functools
import logging
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import copy_context
from typing import (
TYPE_CHECKING,
... | Generic event handler for AsyncCallbackManager. Note: This function is used by langserve to handle events. Args: handlers: The list of handlers that will handle the event event_name: The name of the event (e.g., "on_llm_start") ignore_condition_name: Name of the attribute defined on handler that if True will cause the ... |
27,885 | from __future__ import annotations
import asyncio
import functools
import logging
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import copy_context
from typing import (
TYPE_CHECKING,
... | Configure the callback manager. Args: callback_manager_cls (Type[T]): The callback manager class. inheritable_callbacks (Optional[Callbacks], optional): The inheritable callbacks. Defaults to None. local_callbacks (Optional[Callbacks], optional): The local callbacks. Defaults to None. verbose (bool, optional): Whether ... |
27,886 | from __future__ import annotations
import inspect
import uuid
import warnings
from abc import abstractmethod
from inspect import signature
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union
from langchain_core.callbacks import (
AsyncCallbackManager,
AsyncCallbackManagerForToo... | Create a pydantic schema from a function's signature. Args: model_name: Name to assign to the generated pydandic schema func: Function to generate the schema from Returns: A pydantic model with the same arguments as the function |
27,887 | import json
from typing import Any, Callable, List
from langchain_core.tracers.base import BaseTracer
from langchain_core.tracers.schemas import Run
from langchain_core.utils.input import get_bolded_text, get_colored_text
The provided code snippet includes necessary dependencies for implementing the `try_json_stringif... | Try to stringify an object to JSON. Args: obj: Object to stringify. fallback: Fallback string to return if the object cannot be stringified. Returns: A JSON string if the object can be stringified, otherwise the fallback string. |
27,888 | import json
from typing import Any, Callable, List
from langchain_core.tracers.base import BaseTracer
from langchain_core.tracers.schemas import Run
from langchain_core.utils.input import get_bolded_text, get_colored_text
The provided code snippet includes necessary dependencies for implementing the `elapsed` function... | Get the elapsed time of a run. Args: run: any object with a start_time and end_time attribute. Returns: A string with the elapsed time in seconds or milliseconds if time is less than a second. |
27,889 | from __future__ import annotations
import datetime
import warnings
from typing import Any, Dict, List, Optional, Type
from uuid import UUID
from langsmith.schemas import RunBase as BaseRunV2
from langsmith.schemas import RunTypeEnum as RunTypeEnumDep
from langchain_core._api import deprecated
from langchain_core.output... | RunTypeEnum. |
27,890 | from __future__ import annotations
import logging
import os
from typing import Any, Dict, Optional, Union
import requests
from langchain_core._api import deprecated
from langchain_core.messages import get_buffer_string
from langchain_core.tracers.base import BaseTracer
from langchain_core.tracers.schemas import (
C... | Get the headers for the LangChain API. |
27,891 | from __future__ import annotations
import logging
import os
from typing import Any, Dict, Optional, Union
import requests
from langchain_core._api import deprecated
from langchain_core.messages import get_buffer_string
from langchain_core.tracers.base import BaseTracer
from langchain_core.tracers.schemas import (
C... | null |
27,892 | from __future__ import annotations
import logging
import threading
import weakref
from concurrent.futures import Future, ThreadPoolExecutor, wait
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
from uuid import UUID
import langsmith
from langsmith.evaluation.evaluator import EvaluationResult,... | Wait for all tracers to finish. |
27,893 | from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from uuid import UUID
from langsmith import Client
from langsmith import utils as ls_utils
from tenacity import (... | Log an error once. |
27,894 | from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from uuid import UUID
from langsmith import Client
from langsmith import utils as ls_utils
from tenacity import (... | Wait for all tracers to finish. |
27,895 | from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from uuid import UUID
from langsmith import Client
from langsmith import utils as ls_utils
from tenacity import (... | Get the client. |
27,896 | from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from uuid import UUID
from langsmith import Client
from langsmith import utils as ls_utils
from tenacity import (... | Get the executor. |
27,897 | from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from uuid import UUID
from langsmith import Client
from langsmith import utils as ls_utils
from tenacity import (... | null |
27,898 | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import (
TYPE_CHECKING,
Any,
Generator,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from uuid import UUID
from langsmith import utils as ls_utils
from langsmith.run... | Get the Deprecated LangChainTracer in a context manager. Args: session_name (str, optional): The name of the session. Defaults to "default". Returns: TracerSessionV1: The LangChainTracer session. Example: >>> with tracing_enabled() as session: ... # Use the LangChainTracer session |
27,899 | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import (
TYPE_CHECKING,
Any,
Generator,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from uuid import UUID
from langsmith import utils as ls_utils
from langsmith.run... | Instruct LangChain to log all runs in context to LangSmith. Args: project_name (str, optional): The name of the project. Defaults to "default". example_id (str or UUID, optional): The ID of the example. Defaults to None. tags (List[str], optional): The tags to add to the run. Defaults to None. client (LangSmithClient, ... |
27,900 | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import (
TYPE_CHECKING,
Any,
Generator,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from uuid import UUID
from langsmith import utils as ls_utils
from langsmith.run... | Collect all run traces in context. Returns: run_collector.RunCollectorCallbackHandler: The run collector callback handler. Example: >>> with collect_runs() as runs_cb: chain.invoke("foo") run_id = runs_cb.traced_runs[0].id |
27,901 | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import (
TYPE_CHECKING,
Any,
Generator,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from uuid import UUID
from langsmith import utils as ls_utils
from langsmith.run... | Register a configure hook. Args: context_var (ContextVar[Optional[Any]]): The context variable. inheritable (bool): Whether the context variable is inheritable. handle_class (Optional[Type[BaseCallbackHandler]], optional): The callback handler class. Defaults to None. env_var (Optional[str], optional): The environment ... |
27,902 | from __future__ import annotations
import asyncio
import copy
import threading
from collections import defaultdict
from typing import (
Any,
AsyncIterator,
Dict,
List,
Literal,
Optional,
Sequence,
TypeVar,
Union,
overload,
)
from uuid import UUID
import jsonpatch
from typing_ext... | Extract standardized inputs from a run. Standardizes the inputs based on the type of the runnable used. Args: run: Run object schema_format: The schema format to use. Returns: Valid inputs are only dict. By conventions, inputs always represented invocation using named arguments. A None means that the input is not yet k... |
27,903 | from __future__ import annotations
import asyncio
import copy
import threading
from collections import defaultdict
from typing import (
Any,
AsyncIterator,
Dict,
List,
Literal,
Optional,
Sequence,
TypeVar,
Union,
overload,
)
from uuid import UUID
import jsonpatch
from typing_ext... | Extract standardized output from a run. Standardizes the outputs based on the type of the runnable used. Args: log: The log entry. schema_format: The schema format to use. Returns: An output if returned, otherwise a None |
27,904 | from __future__ import annotations
import asyncio
import copy
import threading
from collections import defaultdict
from typing import (
Any,
AsyncIterator,
Dict,
List,
Literal,
Optional,
Sequence,
TypeVar,
Union,
overload,
)
from uuid import UUID
import jsonpatch
from typing_ext... | null |
27,905 | from __future__ import annotations
import asyncio
import copy
import threading
from collections import defaultdict
from typing import (
Any,
AsyncIterator,
Dict,
List,
Literal,
Optional,
Sequence,
TypeVar,
Union,
overload,
)
from uuid import UUID
import jsonpatch
from typing_ext... | null |
27,906 | from __future__ import annotations
import asyncio
import copy
import threading
from collections import defaultdict
from typing import (
Any,
AsyncIterator,
Dict,
List,
Literal,
Optional,
Sequence,
TypeVar,
Union,
overload,
)
from uuid import UUID
import jsonpatch
from typing_ext... | Implementation of astream_log for a given runnable. The implementation has been factored out (at least temporarily) as both astream_log and astream_events relies on it. |
27,907 | from __future__ import annotations
import json
from typing import Any, List, Literal, Sequence, Union
from langchain_core.load.serializable import Serializable
from langchain_core.messages import (
AIMessage,
BaseMessage,
FunctionMessage,
HumanMessage,
)
class AgentAction(Serializable):
"""A full de... | Convert an agent action to a message. This code is used to reconstruct the original AI message from the agent action. Args: agent_action: Agent action to convert. Returns: AIMessage that corresponds to the original tool invocation. |
27,908 | import warnings
from typing import TYPE_CHECKING, Optional
_verbose: bool = False
The provided code snippet includes necessary dependencies for implementing the `set_verbose` function. Write a Python function `def set_verbose(value: bool) -> None` to solve the following problem:
Set a new value for the `verbose` globa... | Set a new value for the `verbose` global setting. |
27,909 | import warnings
from typing import TYPE_CHECKING, Optional
_debug: bool = False
The provided code snippet includes necessary dependencies for implementing the `set_debug` function. Write a Python function `def set_debug(value: bool) -> None` to solve the following problem:
Set a new value for the `debug` global settin... | Set a new value for the `debug` global setting. |
27,910 | import warnings
from typing import TYPE_CHECKING, Optional
_llm_cache: Optional["BaseCache"] = None
The provided code snippet includes necessary dependencies for implementing the `set_llm_cache` function. Write a Python function `def set_llm_cache(value: Optional["BaseCache"]) -> None` to solve the following problem:
... | Set a new LLM cache, overwriting the previous value, if any. |
27,911 | from abc import ABC
from typing import (
Any,
Dict,
List,
Literal,
Optional,
TypedDict,
Union,
cast,
)
from typing_extensions import NotRequired
from langchain_core.pydantic_v1 import BaseModel, PrivateAttr
The provided code snippet includes necessary dependencies for implementing the `... | Try to determine if a value is different from the default. Args: value: The value. key: The key. model: The model. Returns: Whether the value is different from the default. |
27,912 | from abc import ABC
from typing import (
Any,
Dict,
List,
Literal,
Optional,
TypedDict,
Union,
cast,
)
from typing_extensions import NotRequired
from langchain_core.pydantic_v1 import BaseModel, PrivateAttr
def _replace_secrets(
root: Dict[Any, Any], secrets_map: Dict[str, str]
) ->... | null |
27,913 | import asyncio
import threading
from collections import defaultdict
from functools import partial
from itertools import groupby
from typing import (
Any,
Awaitable,
Callable,
DefaultDict,
Dict,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
from langchain_core... | Asynchronously patch a runnable config with context getters and setters. Args: config: The runnable config. steps: The runnable steps. Returns: The patched runnable config. |
27,914 | import asyncio
import threading
from collections import defaultdict
from functools import partial
from itertools import groupby
from typing import (
Any,
Awaitable,
Callable,
DefaultDict,
Dict,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
from langchain_core... | Patch a runnable config with context getters and setters. Args: config: The runnable config. steps: The runnable steps. Returns: The patched runnable config. |
27,915 | import asyncio
import threading
from collections import defaultdict
from functools import partial
from itertools import groupby
from typing import (
Any,
Awaitable,
Callable,
DefaultDict,
Dict,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
from langchain_core... | null |
27,916 | import asyncio
import threading
from collections import defaultdict
from functools import partial
from itertools import groupby
from typing import (
Any,
Awaitable,
Callable,
DefaultDict,
Dict,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
from langchain_core... | null |
27,917 | from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
Dict,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypedDict,
TypeVar,
Union,
cast,
overload,
)
from langchain_core._api import deprecated
from lan... | Instantiate a message from a variety of message formats. The message format can be one of the following: - BaseMessagePromptTemplate - BaseMessage - 2-tuple of (role string, template); e.g., ("human", "{user_input}") - 2-tuple of (message class, template) - string: shorthand for ("human", template); e.g., "{user_input}... |
27,918 | import json
import logging
from pathlib import Path
from typing import Callable, Dict, Union
import yaml
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.prompts.few_... | Load the "few shot" prompt from the config. |
27,919 | import json
import logging
from pathlib import Path
from typing import Callable, Dict, Union
import yaml
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.prompts.few_... | Load the prompt template from config. |
27,920 | import json
import logging
from pathlib import Path
from typing import Callable, Dict, Union
import yaml
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.prompts.few_... | Load chat prompt from config |
27,921 | from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
List,
Mapping,
Optional,
Type,
TypeVar,
Union,
)
import yaml
from langchain_core.output_parsers.base i... | Format a document into a string based on a prompt template. First, this pulls information from the document from two sources: 1. `page_content`: This takes the information from the `document.page_content` and assigns it to a variable named `page_content`. 2. metadata: This takes information from `document.metadata` and... |
27,922 | from typing import Any, Dict, List, Tuple
from langchain_core.prompt_values import PromptValue
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.prompts.chat import BaseChatPromptTemplate
from langchain_core.pydantic_v1 import root_validator
def _get_inputs(inputs: dict, input_variables: L... | null |
27,923 | from __future__ import annotations
import warnings
from abc import ABC
from string import Formatter
from typing import Any, Callable, Dict, List, Set
from langchain_core.prompt_values import PromptValue, StringPromptValue
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.utils import get_co... | Format a template using jinja2. *Security warning*: As of LangChain 0.0.329, this method uses Jinja2's SandboxedEnvironment by default. However, this sand-boxing should be treated as a best-effort approach rather than a guarantee of security. Do not accept jinja2 templates from untrusted sources as they may lead to arb... |
27,924 | from __future__ import annotations
import warnings
from abc import ABC
from string import Formatter
from typing import Any, Callable, Dict, List, Set
from langchain_core.prompt_values import PromptValue, StringPromptValue
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.utils import get_co... | Validate that the input variables are valid for the template. Issues a warning if missing or extra variables are found. Args: template: The template string. input_variables: The input variables. |
27,925 | from __future__ import annotations
import warnings
from abc import ABC
from string import Formatter
from typing import Any, Callable, Dict, List, Set
from langchain_core.prompt_values import PromptValue, StringPromptValue
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.utils import get_co... | Check that template string is valid. Args: template: The template string. template_format: The template format. Should be one of "f-string" or "jinja2". input_variables: The input variables. Raises: ValueError: If the template format is not supported. |
27,926 | from __future__ import annotations
import warnings
from abc import ABC
from string import Formatter
from typing import Any, Callable, Dict, List, Set
from langchain_core.prompt_values import PromptValue, StringPromptValue
from langchain_core.prompts.base import BasePromptTemplate
from langchain_core.utils import get_co... | Get the variables from the template. Args: template: The template string. template_format: The template format. Should be one of "f-string" or "jinja2". Returns: The variables from the template. Raises: ValueError: If the template format is not supported. |
27,927 | from typing import Sequence
The provided code snippet includes necessary dependencies for implementing the `print_sys_info` function. Write a Python function `def print_sys_info(*, additional_pkgs: Sequence[str] = tuple()) -> None` to solve the following problem:
Print information about the environment for debugging p... | Print information about the environment for debugging purposes. |
27,928 | import contextlib
import functools
import inspect
import warnings
from typing import Any, Callable, Generator, Type, TypeVar
from langchain_core._api.internal import is_caller_internal
T = TypeVar("T", Type, Callable)
def warn_beta(
*,
message: str = "",
name: str = "",
obj_type: str = "",
addendum:... | Decorator to mark a function, a class, or a property as beta. When marking a classmethod, a staticmethod, or a property, the ``@beta`` decorator should go *under* ``@classmethod`` and ``@staticmethod`` (i.e., `beta` should directly decorate the underlying callable), but *over* ``@property``. When marking a class ``C`` ... |
27,929 | import contextlib
import functools
import inspect
import warnings
from typing import Any, Callable, Generator, Type, TypeVar
from langchain_core._api.internal import is_caller_internal
class LangChainBetaWarning(DeprecationWarning):
"""A class for issuing beta warnings for LangChain users."""
The provided code sni... | Context manager to suppress LangChainDeprecationWarning. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.