id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
16,497
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Binarize the dict by setting the values that are 1 to 0. Values greater than 1 stay untouched.
16,498
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Takes in a dataclass and outputs all of its fields and values in a list.
16,499
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Write lines out to a file at path file_path.
16,500
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Add `count` spaces before each line in `lines`.
16,501
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Return a version of the target_word where the case matches the source_word.
16,502
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
A wrapper for applying `process` to all `items`.
16,503
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Given `items` (a list of dictionaries), remove any (key, value) pairs that aren't necessary to distinguish the items, removing the keys not in `priority_keys` and then from the end of `priority_keys` first. Example: items = [{"model": "M1", stop: "#", n: 3}, {"model": "M1", stop: "\n", n: 3}, {"model": "M2", stop: "\n"...
16,504
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Generate a unique ID (e.g., 77437ea482144bf7b9275a0acee997db).
16,505
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Get the file name from a path (e.g., /path/to/image.png => image.png).
16,506
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
Creates a symlink at `dest`. `src` and `dest` can be relative paths.
16,507
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
null
16,508
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
null
16,509
from filelock import FileLock import json import os import shlex import subprocess import urllib import uuid import zstandard from typing import Any, Callable, Dict, List, Optional, TypeVar from datetime import datetime, date from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm import pyhocon from da...
null
16,510
import sys import time from typing import Any, Callable, List, Optional The provided code snippet includes necessary dependencies for implementing the `format_time` function. Write a Python function `def format_time(s: float) -> str` to solve the following problem: Return a nice string representation of `s` seconds. ...
Return a nice string representation of `s` seconds.
16,511
from typing import Any, Optional, Dict from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists from helm.clients.auto_client import AutoClient from helm.benchmark.model_deployment_registry import ModelDeployment, get_model_deployment from helm.tokeni...
null
16,512
from typing import Any, Optional, Dict from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists from helm.clients.auto_client import AutoClient from helm.benchmark.model_deployment_registry import ModelDeployment, get_model_deployment from helm.tokeni...
null
16,513
from typing import Any, Optional, Dict from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists from helm.clients.auto_client import AutoClient from helm.benchmark.model_deployment_registry import ModelDeployment, get_model_deployment from helm.tokeni...
null
16,514
from typing import Any, Optional, Dict from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists from helm.clients.auto_client import AutoClient from helm.benchmark.model_deployment_registry import ModelDeployment, get_model_deployment from helm.tokeni...
null
16,515
from typing import Any, Optional, Dict from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists from helm.clients.auto_client import AutoClient from helm.benchmark.model_deployment_registry import ModelDeployment, get_model_deployment from helm.tokeni...
null
16,516
import argparse import json from collections import defaultdict import os from typing import Dict from helm.common.cache import ( KeyValueStoreCacheConfig, MongoCacheConfig, SqliteCacheConfig, create_key_value_store, ) from helm.common.key_value_store import request_to_key from helm.common.hierarchical_...
Given a jsonl file with request and results, uploads request/result pairs to the cache at `cache_path`. We assume each line of the input jsonl file is structured {request: ..., result: ...}.
16,517
import argparse import json import os import typing from typing import List from collections import Counter from dacite import from_dict from helm.common.request import Request from helm.common.cache import ( KeyValueStoreCacheConfig, MongoCacheConfig, SqliteCacheConfig, create_key_value_store, ) from h...
Given a run suite folder, generates a jsonl file at `output_path` with raw queries where each line represents a single request.
16,518
import argparse from pymongo import MongoClient from helm.common.cache import create_key_value_store, MongoCacheConfig from helm.common.hierarchical_logger import hlog, htrack, htrack_block class MongoCacheConfig(KeyValueStoreCacheConfig): def cache_stats_key(self) -> str: def create_key_value_store(config:...
null
16,519
import argparse import json import os from sqlitedict import SqliteDict from helm.common.mongo_key_value_store import MongoKeyValueStore from helm.common.hierarchical_logger import hlog, htrack from typing import Optional _SQLITE_FILE_SUFFIX = ".sqlite" def copy_cache( cache_dir: str, mongo_host: str, organ...
null
16,520
import argparse import json import time from typing import Any, Callable, Dict, List from helm.common.cache import create_key_value_store, MongoCacheConfig from helm.common.general import parse_hocon from helm.common.hierarchical_logger import hlog, htrack from helm.clients.anthropic_client import AnthropicLegacyClient...
null
16,521
import argparse import json import time from typing import Any, Callable, Dict, List from helm.common.cache import create_key_value_store, MongoCacheConfig from helm.common.general import parse_hocon from helm.common.hierarchical_logger import hlog, htrack from helm.clients.anthropic_client import AnthropicLegacyClient...
null
16,522
import argparse from helm.common.cache import create_key_value_store, MongoCacheConfig from helm.common.hierarchical_logger import hlog, htrack class MongoCacheConfig(KeyValueStoreCacheConfig): """Configuration for a cache backed by a MongoDB collection.""" # URL for the MongoDB database that contains the col...
null
16,523
import argparse from datetime import datetime def generate_spec(scenario, model, tokenizer, num_prompt_tokens, num_output_tokens, random): random_str: str = "" if random is not None: random_str = f",random={random}" return ( f'"{scenario}:model={model},tokenizer={tokenizer},' f"num_...
null
16,524
import os from typing import Dict, List, Tuple from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists, ensure_file_downloaded, write, get_credentials from helm.common.tokenization_request import ( TokenizationRequest, TokenizationRequestResu...
null
16,525
import os from typing import Dict, List, Tuple from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists, ensure_file_downloaded, write, get_credentials from helm.common.tokenization_request import ( TokenizationRequest, TokenizationRequestResu...
Tokenizes each book using the requested tokenizer service.
16,526
import os from typing import Dict, List, Tuple from helm.common.cache_backend_config import SqliteCacheBackendConfig from helm.common.general import ensure_directory_exists, ensure_file_downloaded, write, get_credentials from helm.common.tokenization_request import ( TokenizationRequest, TokenizationRequestResu...
Generates the synthetic efficiency instances given the tokenized book sources.
16,527
import argparse import csv import json import os import random import shutil import requests import statistics from typing import Any, Dict, List from tqdm import tqdm from helm.common.hierarchical_logger import hlog, htrack_block random.seed(0) QUESTION_TYPE_TO_INFOS = { "alignment": { "instruction": "Plea...
Given a human eval results folder from HEIM, generates a dataset that can be used to evaluate VLMs. vhelm_image_critique: reasoning and knowledge scenarios - alignment vhelm_image_critique_aesthetics: MSCOCO perturbations - alignment - aesthetics vhelm_image_critique_originality_subject_aesthetics: originality scenario...
16,528
import os from typing import Dict from scaleapi import ScaleClient def get_credentials(path: str) -> Dict[str, str]: # Reads the credentials from the given path with open(path, "r") as f: # Read line by line, replaces the spaces, splits on the first ":" # The first part is the key, the second pa...
null
16,529
import os import json from typing import Iterator, Dict, List import pandas as pd from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `batch_line_generator` function. Write a Python function `def batch_line_generator(fname, batch_size)` to solve the following problem...
Returns generator for jsonl file with batched lines
16,530
import os import json from typing import Iterator, Dict, List import pandas as pd from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `append_to_jsonl_file` function. Write a Python function `def append_to_jsonl_file(data, file)` to solve the following problem: Appen...
Appends json dictionary as new line to file
16,531
import os import json from typing import Iterator, Dict, List import pandas as pd from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `get_batch_files` function. Write a Python function `def get_batch_files(fdir: Path) -> List[str]` to solve the following problem: Fo...
For each file in fdir, returns full filepath. Args: fdir (str): path to directory Returns: List[str]: filepaths for files in fdir
16,532
import os import json from typing import Iterator, Dict, List import pandas as pd from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `create_dir` function. Write a Python function `def create_dir(out_dir)` to solve the following problem: Creates new directory if it ...
Creates new directory if it doesn't already exist
16,533
import os import json from typing import Iterator, Dict, List import pandas as pd from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `load_seed_relations` function. Write a Python function `def load_seed_relations(fdir: Path) -> pd.DataFrame` to solve the following ...
Returns a dataframe containing seed relations and associated information. Args: fdir (str): path to folder containined seed relations TSV files Returns: pd.DataFrame: dataframe for data in tsv files.
16,534
import os import json from typing import Iterator, Dict, List import pandas as pd from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `save_jsonl` function. Write a Python function `def save_jsonl(fpath: Path, data: List[Dict[str, str]]) -> None` to solve the followi...
Saves data to file in JSONL format. Args: fpath (Path): path to file. data (List[Dict[str, str]]): data to save. Must be list of dictionaries.
16,535
import argparse from collections import defaultdict import numpy as np from tqdm import tqdm from pathlib import Path from utils import jsonl_generator, load_seed_relations, save_jsonl def get_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument( "--benchmark_folder", type=str, default=...
null
16,536
import argparse from collections import defaultdict import numpy as np from tqdm import tqdm from pathlib import Path from utils import jsonl_generator, load_seed_relations, save_jsonl def jsonl_generator(fname: str) -> Iterator[Dict[str, str]]: """Returns an iterator over a jsonl file.""" for line in open(fna...
null
16,537
import argparse from collections import defaultdict import numpy as np from tqdm import tqdm from pathlib import Path from utils import jsonl_generator, load_seed_relations, save_jsonl def load_relations(fpath): rels = [] with open(fpath) as in_file: for line in in_file: rels.append(line.st...
null
16,538
import argparse from tqdm import tqdm from typing import Set, List, Dict from pathlib import Path from utils import get_batch_files, jsonl_generator, load_seed_relations, save_jsonl def get_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument( "--processed_wik...
null
16,539
import argparse from tqdm import tqdm from typing import Set, List, Dict from pathlib import Path from utils import get_batch_files, jsonl_generator, load_seed_relations, save_jsonl def jsonl_generator(fname: str) -> Iterator[Dict[str, str]]: """Returns an iterator over a jsonl file.""" for line in open(fname,...
Returns triples with relation in seed_rels Args: seed_rels (Set[str]): filtering set of relations. filepath (str): path to jsonl file with triple data Returns: List[Dict[str, str]]: list of filtered triples.
16,540
import argparse from tqdm import tqdm from typing import Set, List, Dict from pathlib import Path from utils import get_batch_files, jsonl_generator, load_seed_relations, save_jsonl def jsonl_generator(fname: str) -> Iterator[Dict[str, str]]: """Returns an iterator over a jsonl file.""" for line in open(fname,...
null
16,541
import argparse from collections import defaultdict import json from tqdm import tqdm from pathlib import Path from utils import get_batch_files, jsonl_generator, save_jsonl def get_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument( "--processed_wikidata", type=str, help="Path to pro...
null
16,542
import argparse from collections import defaultdict import json from tqdm import tqdm from pathlib import Path from utils import get_batch_files, jsonl_generator, save_jsonl The provided code snippet includes necessary dependencies for implementing the `bad_alias` function. Write a Python function `def bad_alias(alias...
Returns true if an entity has a "bad" alias and false otherwise. An alias is bad if it corresponds to a category, stub, disambiguation, stub, template, or list page. We just check for these keywords in the title. Args: aliases (list): list of aliases for an entity. Returns: bool: whether or not the entity has a bad ali...
16,543
import argparse import os import shutil import subprocess from typing import List, Optional from helm.common.hierarchical_logger import hlog, htrack, htrack_block OUTPUT_PATH_TEMPLATE = "benchmark_output/runs/{suite}" DRYRUN_SUITE1: str = "dryrun_results1" DRYRUN_SUITE2: str = "dryrun_results2" def do_dry_run( dryr...
null
16,544
from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Todo from django.http import HttpResponseRedirect class Todo(models.Model): title = models.CharField(max_length=100) created_at = models.DateTimeField('Created', auto_now_add=True) update_a...
null
16,545
from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Todo from django.http import HttpResponseRedirect class Todo(models.Model): title = models.CharField(max_length=100) created_at = models.DateTimeField('Created', auto_now_add=True) update_a...
null
16,546
from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Todo from django.http import HttpResponseRedirect class Todo(models.Model): title = models.CharField(max_length=100) created_at = models.DateTimeField('Created', auto_now_add=True) update_a...
null
16,547
from django.shortcuts import redirect def index(request): return redirect('/todos')
null
16,548
from typing import Optional from nemoguardrails.actions import action async def check_blocked_terms(context: Optional[dict] = None): bot_response = context.get("bot_message") # A quick hard-coded list of proprietary terms. You can also read this from a file. proprietary_terms = ["proprietary", "proprietar...
null
16,553
import csv import json from nemoguardrails.server.api import register_logger The provided code snippet includes necessary dependencies for implementing the `custom_logger` function. Write a Python function `async def custom_logger(item)` to solve the following problem: Custom logger that writes the ratings to a CSV fi...
Custom logger that writes the ratings to a CSV file in the current directory.
16,554
from functools import lru_cache from torch import bfloat16 from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_provider, ) The provided code snippet includes necessary dependencies for implementing the `get_falco...
Loads the Falcon 7B Instruct LLM.
16,555
from functools import lru_cache from torch import bfloat16 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, pipeline from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_provider, ) def ge...
null
16,556
import os import os.path import torch from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_pro...
null
16,557
from functools import lru_cache from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, pipeline from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_provider, ) def get_dolly_v2_3b_llm(streaming...
null
16,558
from functools import lru_cache from torch import float16 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, pipeline from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_provider, ) The pro...
Loads the Vicuna 7B LLM.
16,559
from functools import lru_cache from torch import float16 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, pipeline from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_provider, ) The pro...
Loads the Vicuna 13B LLM.
16,560
from functools import lru_cache from torch import float16 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, pipeline from nemoguardrails.llm.helpers import get_llm_instance_wrapper from nemoguardrails.llm.providers import ( HuggingFacePipelineCompatible, register_llm_provider, ) def _loa...
Loads the Vicuna 13B LLM from a local path.
16,561
import logging import os from datetime import datetime from typing import Optional import pinecone from langchain.chains import RetrievalQA from langchain.docstore.document import Document from langchain.embeddings.openai import OpenAIEmbeddings from langchain.llms import BaseLLM from langchain.vectorstores import Pine...
null
16,562
import asyncio from typing import Any, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM The provided code snippet includes necessary dependencies for implementing the `query_tabular_data` function. Writ...
Answer a question based on some tabular data.
16,563
import os.path import pickle from pathlib import Path from typing import Optional import faiss import pandas as pd import torch from gpt4pandas import GPT4Pandas from langchain.chains import RetrievalQA from langchain.embeddings import HuggingFaceEmbeddings from langchain.llms import BaseLLM from langchain.text_splitte...
null
16,564
from langchain.llms.base import BaseLLM from langchain.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from nemoguardrails import LLMRails from nemoguardrails.actions.actions import ActionResult from nemoguardrails.kb.kb import KnowledgeBase async def rag(context: dict, llm: Base...
null
16,565
import os.path from nemoguardrails import LLMRails, RailsConfig The provided code snippet includes necessary dependencies for implementing the `demo_input_checking` function. Write a Python function `def demo_input_checking()` to solve the following problem: Demo using the Python API and a config that only has input r...
Demo using the Python API and a config that only has input rails.
16,566
import os.path from nemoguardrails import LLMRails, RailsConfig The provided code snippet includes necessary dependencies for implementing the `demo_output_checking` function. Write a Python function `def demo_output_checking()` to solve the following problem: Demo using the Python API and a config that only has outpu...
Demo using the Python API and a config that only has output rails.
16,567
import asyncio import logging from typing import Optional from langchain_core.language_models import BaseLLM from langchain_core.runnables import RunnableConfig from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions import action from nemoguardrails.context import streaming_handler_var from nemogu...
Demo using the streaming of response chunks directly.
16,568
import asyncio import logging from typing import Optional from langchain_core.language_models import BaseLLM from langchain_core.runnables import RunnableConfig from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions import action from nemoguardrails.context import streaming_handler_var from nemogu...
Demo of using the streaming of chunks with the final response as well.
16,569
import asyncio import logging from typing import Optional from langchain_core.language_models import BaseLLM from langchain_core.runnables import RunnableConfig from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions import action from nemoguardrails.context import streaming_handler_var from nemogu...
Demo for streaming of response chunks directly with HuggingFacePipline deployed LLMs.
16,570
import asyncio import logging from typing import Optional from langchain_core.language_models import BaseLLM from langchain_core.runnables import RunnableConfig from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions import action from nemoguardrails.context import streaming_handler_var from nemogu...
Demo of using the streaming of chunks from custom actions.
16,571
from typing import Any, Callable, Coroutine from langchain.llms.base import BaseLLM from nemoguardrails import LLMRails, RailsConfig COLANG_CONFIG = """ define user express greeting "hi" define user express ill intent "I hate you" "I want to destroy the world" define bot express cannot respond "I'm sorry I cann...
null
16,572
import os from langchain.chains import LLMMathChain from langchain.prompts import ChatPromptTemplate from langchain_core.tools import Tool from langchain_openai.chat_models import ChatOpenAI from pydantic import BaseModel, Field from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.integrations.langchain...
Basic setup with a prompt and a model.
16,573
import os from langchain.chains import LLMMathChain from langchain.prompts import ChatPromptTemplate from langchain_core.tools import Tool from langchain_openai.chat_models import ChatOpenAI from pydantic import BaseModel, Field from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.integrations.langchain...
Basic setup invoking LLM rails directly.
16,574
import os from langchain.chains import LLMMathChain from langchain.prompts import ChatPromptTemplate from langchain_core.tools import Tool from langchain_openai.chat_models import ChatOpenAI from pydantic import BaseModel, Field from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.integrations.langchain...
Basic setup combining the two above. Wraps the model with a rails configuration
16,575
import os from langchain.chains import LLMMathChain from langchain.prompts import ChatPromptTemplate from langchain_core.tools import Tool from langchain_openai.chat_models import ChatOpenAI from pydantic import BaseModel, Field from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.integrations.langchain...
Experiment with adding a tool as an action to a RunnableRails instance. This is essentially an Agent! An Agent is LangChain is a chain + an executor (AgentExecutor). - the chain is responsible for predicting the next step - the executor is responsible for invoking the tools if needed, and re-invoking the chain Since th...
16,576
import os import subprocess import traceback EXAMPLES_FOLDER = os.path.join(os.path.dirname(os.path.dirname(__file__)), "examples") The provided code snippet includes necessary dependencies for implementing the `create_chatter` function. Write a Python function `def create_chatter(name, configname, logger)` to solve t...
Create a NeMo Guardrails chatter specified with the configuration
16,577
import os import subprocess import traceback The provided code snippet includes necessary dependencies for implementing the `close_chatter` function. Write a Python function `def close_chatter(chatter)` to solve the following problem: Close the given chatter Here is the function: def close_chatter(chatter): """C...
Close the given chatter
16,578
def are_strings_semantically_same(string1, string2): from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity vectorizer = TfidfVectorizer().fit_transform([string1, string2]) similarity = cosine_similarity(vectorizer) # Determine if the si...
null
16,579
import os import random import time import pandas as pd from tqdm import tqdm from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.logging.stats import llm_stats def build_run_configs(): run_configs = [] for test_config in TEST_CONFIGS: config = RailsConfig.from_path(os.path.join(CONFIGS...
null
16,580
import logging The provided code snippet includes necessary dependencies for implementing the `create_logger` function. Write a Python function `def create_logger(filename)` to solve the following problem: Create a logger specified by the filename Here is the function: def create_logger(filename): """Create a lo...
Create a logger specified by the filename
16,581
import asyncio import dataclasses import json import uuid from collections import namedtuple from datetime import datetime, timezone from enum import Enum from typing import Any, Dict, List, Tuple, Union import yaml Property = namedtuple("Property", ["name", "type"]) def _has_property(e: Dict[str, Any], p: Property) -...
null
16,582
import asyncio import dataclasses import json import uuid from collections import namedtuple from datetime import datetime, timezone from enum import Enum from typing import Any, Dict, List, Tuple, Union import yaml _event_validators = [ Validator("Events need to provide 'type'", lambda e: "type" in e), Validat...
Performs a basic event validation and returns True if the event conforms.
16,583
import asyncio import dataclasses import json import uuid from collections import namedtuple from datetime import datetime, timezone from enum import Enum from typing import Any, Dict, List, Tuple, Union import yaml The provided code snippet includes necessary dependencies for implementing the `get_or_create_event_loo...
Helper to return the current asyncio loop. If one does not exist, it will be created.
16,584
import contextvars from typing import List from nemoguardrails.logging.explain import LLMCallInfo from nemoguardrails.rails.llm.options import ( ActivatedRail, ExecutedAction, GenerationLog, ) class ExecutedAction(BaseModel): """Information about an action that was executed.""" action_name: str = ...
Computes the GenerationLog based on the processing log. The processing log is a raw sequence of all the relevant events. The generation log is a more structured, curated, version of it.
16,585
from typing import List import yaml The provided code snippet includes necessary dependencies for implementing the `split_markdown_in_topic_chunks` function. Write a Python function `def split_markdown_in_topic_chunks( content: str, max_chunk_size: int = 400 ) -> List[dict]` to solve the following problem: Splits ...
Splits a markdown content into topic chunks. This function takes a markdown content as input and divides it into topic chunks based on headings and subsections. Each chunk includes a title and body, with an optional maximum size. Parameters: - content (str): The markdown content to be split. - max_chunk_size (int): The...
16,586
import json from typing import List The provided code snippet includes necessary dependencies for implementing the `get_history_cache_key` function. Write a Python function `def get_history_cache_key(messages: List[dict]) -> str` to solve the following problem: Compute the cache key for a sequence of messages. Args: m...
Compute the cache key for a sequence of messages. Args: messages: The list of messages. Returns: A unique string that can be used as a key for the provides sequence of messages.
16,587
import logging import os from typing import Any, Dict, List, Optional, Set, Tuple, Union import yaml from pydantic import BaseModel, ValidationError, root_validator from pydantic.fields import Field from nemoguardrails.colang import parse_colang_file, parse_flow_elements from nemoguardrails.colang.v2_x.lang.colang_ast ...
Load recursively all the imported path in the specified raw_config. Args: raw_config: The starting raw configuration (i.e., a dict) colang_files: The current set of colang files which will be extended as new configurations are loaded.
16,588
import logging import os from typing import Any, Dict, List, Optional, Set, Tuple, Union import yaml from pydantic import BaseModel, ValidationError, root_validator from pydantic.fields import Field from nemoguardrails.colang import parse_colang_file, parse_flow_elements from nemoguardrails.colang.v2_x.lang.colang_ast ...
Helper to join two rails configuration.
16,589
import logging from typing import Optional from langchain.chains import LLMChain from langchain.llms.base import BaseLLM from langchain.prompts import PromptTemplate from langchain_openai import OpenAI from nemoguardrails.actions import action from nemoguardrails.actions.llm.utils import ( get_multiline_response, ...
Checks if the last bot response is a hallucination by checking multiple completions for self-consistency. :return: True if hallucination is detected, False otherwise.
16,590
import logging from functools import lru_cache import spacy from nemoguardrails import RailsConfig from nemoguardrails.actions import action from nemoguardrails.rails.llm.config import ( SensitiveDataDetection, SensitiveDataDetectionOptions, ) def _get_analyzer(): try: from presidio_analyzer import ...
Checks whether the provided text contains any sensitive data. Args source: The source for the text, i.e. "input", "output", "retrieval". text: The text to check. config: The rails configuration object. Returns True if any sensitive data has been detected, False otherwise.
16,591
import logging from functools import lru_cache import spacy from nemoguardrails import RailsConfig from nemoguardrails.actions import action from nemoguardrails.rails.llm.config import ( SensitiveDataDetection, SensitiveDataDetectionOptions, ) def _get_analyzer(): try: from presidio_analyzer import ...
Checks whether the provided text contains any sensitive data. Args source: The source for the text, i.e. "input", "output", "retrieval". text: The text to check. config: The rails configuration object. Returns The altered text, if applicable.
16,592
import json import logging import os from typing import Optional import aiohttp from nemoguardrails.actions import action from nemoguardrails.colang.v1_0.lang.utils import new_uuid log = logging.getLogger(__name__) def new_uuid() -> str: """Helper to generate new UUID v4. In testing mode, it will generate a p...
null
16,593
import logging from typing import Optional from langchain.llms import BaseLLM from nemoguardrails.actions import action from nemoguardrails.library.factchecking.align_score.request import alignscore_request from nemoguardrails.library.self_check.facts.actions import self_check_facts from nemoguardrails.llm.taskmanager ...
Checks the facts for the bot response using an information alignment score.
16,594
import os from functools import lru_cache from typing import List import nltk import typer import uvicorn from alignscore import AlignScore from fastapi import FastAPI from pydantic import BaseModel def hello_world(): welcome_str = ( f"This is a development server to host AlignScore models.\n" + f"...
null
16,595
import os from functools import lru_cache from typing import List import nltk import typer import uvicorn from alignscore import AlignScore from fastapi import FastAPI from pydantic import BaseModel def get_model(model: str): """Initialize a model. Args model: The type of the model to be loaded, i.e. "b...
null
16,596
import os from functools import lru_cache from typing import List import nltk import typer import uvicorn from alignscore import AlignScore from fastapi import FastAPI from pydantic import BaseModel def get_model(model: str): class AlignScoreRequest(BaseModel): def get_alignscore(model, evidence: str, claim: str) -> di...
null
16,597
import os from functools import lru_cache from typing import List import nltk import typer import uvicorn from alignscore import AlignScore from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() def get_model(model: str): """Initialize a model. Args model: The type of the model to be...
null
16,598
import logging from typing import Optional from nemoguardrails.actions import action from nemoguardrails.library.jailbreak_detection.request import ( jailbreak_detection_heuristics_request, ) from nemoguardrails.llm.taskmanager import LLMTaskManager log = logging.getLogger(__name__) async def jailbreak_detection_h...
Checks the user's prompt to determine if it is attempt to jailbreak the model.
16,599
import os from typing import Optional import typer import uvicorn from fastapi import FastAPI from heuristics import checks from pydantic import BaseModel def hello_world(): welcome_str = ( "This is a development server for jailbreak detection.\n" "Hit the /heuristics endpoint to run all heuristics...
null
16,600
import os from typing import Optional import typer import uvicorn from fastapi import FastAPI from heuristics import checks from pydantic import BaseModel class JailbreakCheckRequest(BaseModel): def lp_heuristic_check(request: JailbreakCheckRequest): return checks.check_jailbreak_length_per_perplexity( req...
null