id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
16,601
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): """ prompt (str): User utterance to the model lp_threshold (float): Threshold value for length-perplexity heurist...
null
16,602
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): """ prompt (str): User utterance to the model lp_threshold (float): Threshold value for length-perplexity heurist...
null
16,603
import os from typing import Optional import typer import uvicorn from fastapi import FastAPI from heuristics import checks from pydantic import BaseModel app = FastAPI() def start( port: int = typer.Option( default=1337, help="The port that the server should listen on." ), host: str = typer.Option...
null
16,604
import logging from typing import List, Optional, Tuple from langchain.llms import BaseLLM from nemoguardrails.actions import action from nemoguardrails.actions.llm.utils import llm_call from nemoguardrails.context import llm_call_info_var from nemoguardrails.llm.params import llm_params from nemoguardrails.llm.taskman...
Checks user messages using the configured Llama Guard model and the configured prompt containing the safety guidelines.
16,605
import logging from typing import List, Optional, Tuple from langchain.llms import BaseLLM from nemoguardrails.actions import action from nemoguardrails.actions.llm.utils import llm_call from nemoguardrails.context import llm_call_info_var from nemoguardrails.llm.params import llm_params from nemoguardrails.llm.taskman...
Check the bot response using the configured Llama Guard model and the configured prompt containing the safety guidelines.
16,606
import logging from typing import Optional from langchain.llms.base import BaseLLM from nemoguardrails.actions import action from nemoguardrails.actions.llm.utils import llm_call from nemoguardrails.context import llm_call_info_var from nemoguardrails.llm.params import llm_params from nemoguardrails.llm.taskmanager imp...
Checks if the output from the bot. Prompt the LLM, using the `self_check_output` task prompt, to determine if the output from the bot should be allowed or not. The LLM call should return "yes" if the output is bad and should be blocked (this is consistent with self_check_input_prompt). Returns: True if the output shoul...
16,607
import logging from typing import Optional from langchain.llms.base import BaseLLM from nemoguardrails.actions.actions import ActionResult, action from nemoguardrails.actions.llm.utils import llm_call from nemoguardrails.context import llm_call_info_var from nemoguardrails.llm.params import llm_params from nemoguardrai...
Checks the input from the user. Prompt the LLM, using the `check_input` task prompt, to determine if the input from the user should be allowed or not. Returns: True if the input should be allowed, False otherwise.
16,608
import logging from typing import Dict, Optional from fastapi import FastAPI from pydantic import BaseModel, Field from nemoguardrails.actions.action_dispatcher import ActionDispatcher log = logging.getLogger(__name__) app = FastAPI( title="Guardrails Action Server API", description=api_description, version...
Execute the specified action and return the result. Args: body (RequestBody): The request body containing action_name and action_parameters. Returns: dict: The response containing the execution status and result.
16,609
import logging from typing import Dict, Optional from fastapi import FastAPI from pydantic import BaseModel, Field from nemoguardrails.actions.action_dispatcher import ActionDispatcher app = FastAPI( title="Guardrails Action Server API", description=api_description, version="0.1.0", license_info={"name"...
Returns the list of available actions.
16,610
import copy import logging import random import re import time from collections import deque from datetime import datetime, timedelta from functools import partial from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast from nemoguardrails.colang.v2_x.lang.colang_ast import ( Abort, Assignment, ...
Initialize the state to make it ready for the story start.
16,611
import copy import logging import random import re import time from collections import deque from datetime import datetime, timedelta from functools import partial from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast from nemoguardrails.colang.v2_x.lang.colang_ast import ( Abort, Assignment, ...
Compute the next state of the flow-driven system.
16,612
import copy import logging import random import re import time from collections import deque from datetime import datetime, timedelta from functools import partial from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast from nemoguardrails.colang.v2_x.lang.colang_ast import ( Abort, Assignment, ...
Return a list of all active heads that point to an event 'match' element.
16,613
import copy import logging import random import re import time from collections import deque from datetime import datetime, timedelta from functools import partial from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast from nemoguardrails.colang.v2_x.lang.colang_ast import ( Abort, Assignment, ...
Returns 'FinishFlow' internal event
16,614
import copy import logging import random import re import time from collections import deque from datetime import datetime, timedelta from functools import partial from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast from nemoguardrails.colang.v2_x.lang.colang_ast import ( Abort, Assignment, ...
Returns 'StopFlow' internal event
16,615
from functools import lru_cache from lark import Lark from lark.indenter import PythonIndenter The provided code snippet includes necessary dependencies for implementing the `load_lark_parser` function. Write a Python function `def load_lark_parser(grammar_path: str)` to solve the following problem: Helper to load a L...
Helper to load a Lark parser. The result is cached so that it's faster in subsequent times. Args: grammar_path: The path to the .lark file with the grammar. Returns: A Lark parser instance.
16,616
import uuid from dataclasses import asdict, is_dataclass from typing import Any The provided code snippet includes necessary dependencies for implementing the `new_uuid` function. Write a Python function `def new_uuid() -> str` to solve the following problem: Helper to generate new UUID v4. In testing mode, it will ge...
Helper to generate new UUID v4. In testing mode, it will generate a predictable set of UUIDs to help debugging.
16,617
import uuid from dataclasses import asdict, is_dataclass from typing import Any def dataclass_to_dict(obj: Any) -> Any: if is_dataclass(obj): return {k: dataclass_to_dict(v) for k, v in asdict(obj).items()} elif isinstance(obj, list): return [dataclass_to_dict(v) for v in obj] elif isinstan...
null
16,618
from dataclasses import dataclass, field from enum import Enum from typing import Any, Dict, List, Optional, Union from dataclasses_json import dataclass_json class Element: """Base class for all elements in the AST.""" _type: str _source: Optional[Source] = None def __getitem__(self, key): retu...
Make all subtypes of Element hashable.
16,619
import logging import os import re import yaml from nemoguardrails.colang.v2_x.lang.colang_ast import Flow from nemoguardrails.colang.v2_x.lang.grammar.load import load_lark_parser from nemoguardrails.colang.v2_x.lang.transformer import ColangTransformer from nemoguardrails.utils import CustomDumper class ColangParser:...
Parse the content of a .co.
16,620
import uuid from dataclasses import dataclass, field from enum import Enum from time import time from typing import Dict, List, Optional from nemoguardrails.colang.v1_0.runtime.eval import eval_expression from nemoguardrails.colang.v1_0.runtime.sliding import slide from nemoguardrails.utils import new_event_dict class ...
Computes the next step in a flow-driven system given a history of events. Args: history (List[dict]): The history of events. flow_configs (Dict[str, FlowConfig]): Flow configurations. rails_config (RailsConfig): Rails configuration. processing_log (List[dict]): The processing log so far. This will be mutated. Returns: ...
16,621
import uuid from dataclasses import dataclass, field from enum import Enum from time import time from typing import Dict, List, Optional from nemoguardrails.colang.v1_0.runtime.eval import eval_expression from nemoguardrails.colang.v1_0.runtime.sliding import slide from nemoguardrails.utils import new_event_dict The p...
Computes the context given a history of events. Special context variables: - $last_user_message: the last message sent by the user. - $last_bot_message: the last message sent by the bot. Args: history (List[dict]): The history of events. Returns: dict: The computed context.
16,622
import uuid from typing import List, Optional, Text, Tuple def word_split(text: str, word: str): """A simple logic that splits by word but takes strings into accounts.""" parts = [] # Edge case if text == "": return [""] # The current position i = 0 # The start of the current part ...
Helper to returned numbered lines. Comments and empty lines are ignored.
16,623
import uuid from typing import List, Optional, Text, Tuple def split_max(text, separator, max_instances): """Helper to simulate the behavior of .split(..., max_instances). This implementation is meant to transpile correctly to the JS> """ parts = text.split(separator) if len(parts) > max_instances +...
Helper to remove a token
16,624
import uuid from typing import List, Optional, Text, Tuple def split_max(text, separator, max_instances): """Helper to simulate the behavior of .split(..., max_instances). This implementation is meant to transpile correctly to the JS> """ parts = text.split(separator) if len(parts) > max_instances +...
Helper to extract the main token from a line
16,625
import uuid from typing import List, Optional, Text, Tuple The provided code snippet includes necessary dependencies for implementing the `char_split` function. Write a Python function `def char_split( text: str, c: str, ignore_parenthesis=False, ignore_strings=False ) -> List[str]` to solve the following problem:...
Helper method to split a string by a given character. :param text: The text to split. :param c: The character to use as the separator :param ignore_parenthesis: If set, it will now account for lists i.e. starting with [], () or {} :param ignore_strings: If set, it will not take into account strings.
16,626
import uuid from typing import List, Optional, Text, Tuple The provided code snippet includes necessary dependencies for implementing the `params_tokenize` function. Write a Python function `def params_tokenize(text)` to solve the following problem: Tokenizer specific to the params parsing. Here is the function: def...
Tokenizer specific to the params parsing.
16,627
import uuid from typing import List, Optional, Text, Tuple The provided code snippet includes necessary dependencies for implementing the `get_first_key` function. Write a Python function `def get_first_key(d: dict)` to solve the following problem: Helper to get the first key, which transpiles correctly. Here is the ...
Helper to get the first key, which transpiles correctly.
16,628
import uuid from typing import List, Optional, Text, Tuple def split_max(text, separator, max_instances): """Helper to simulate the behavior of .split(..., max_instances). This implementation is meant to transpile correctly to the JS> """ parts = text.split(separator) if len(parts) > max_instances +...
Helper to extract the object from the definition of a topic. Supported expressions is_open_source is_open_source for @roboself is_open_source for $company is_open_source($roboself) is_open_source(@roboself)
16,629
import uuid from typing import List, Optional, Text, Tuple def split_max(text, separator, max_instances): """Helper to simulate the behavior of .split(..., max_instances). This implementation is meant to transpile correctly to the JS> """ parts = text.split(separator) if len(parts) > max_instances +...
Helper to extract a normalized package name.
16,630
import uuid from typing import List, Optional, Text, Tuple The provided code snippet includes necessary dependencies for implementing the `string_hash` function. Write a Python function `def string_hash(s)` to solve the following problem: A simple string hash with an equivalent implementation in javascript. module.exp...
A simple string hash with an equivalent implementation in javascript. module.exports.string_hash = function(s){ let hash = 0; if (s.length === 0) return hash; for (let i = 0; i < s.length; i++) { let char = s.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } if (hash < 0) ha...
16,631
import logging import textwrap from typing import List, Optional from nemoguardrails.colang.v1_0.lang.colang_parser import ( parse_coflows_to_yml_flows, parse_snippets_and_imports, ) from nemoguardrails.colang.v1_0.lang.comd_parser import parse_md_file from nemoguardrails.colang.v1_0.lang.coyml_parser import pa...
Parse the content of a .co file into the CoYML format.
16,632
import json import re from ast import literal_eval from typing import List from .utils import get_stripped_tokens, split_args, split_max, word_split def _dict_to_element(d): """Helper to turn a short-hand dictionary into an event structure. :param d: A dictionary in one of the supported formats :return: ...
Helper to convert a list of events data to 'full events
16,633
import functools import hashlib import json import logging from abc import ABC, abstractmethod from functools import singledispatchmethod from pathlib import Path from typing import Dict, List from nemoguardrails.rails.llm.config import EmbeddingsCacheConfig class EmbeddingsCache: def __init__( self, ...
Decorator to cache the embeddings. This decorator caches the embeddings in the cache store. It uses the `cache_config` attribute of the class to configure the cache. If the class does not have a `cache_config` attribute, it will use the `EmbeddingsCacheConfig` by default. This decorator can be applied to the `_get_embe...
16,634
import logging from typing import Dict, Type from langchain.base_language import BaseLanguageModel class LLMParams: """Context manager to temporarily modify the parameters of a language model.""" def __init__(self, llm: BaseLanguageModel, **kwargs): self.llm = llm self.altered_params = kwargs ...
Register a parameter manager.
16,635
def _replace_prefix(s: str, prefix: str, repl: str): """Helper function to replace a prefix from a string.""" if s.startswith(prefix): return repl + s[len(prefix) :].strip() return s The provided code snippet includes necessary dependencies for implementing the `user_intent_parser` function. Write ...
Parses the user intent.
16,636
def _replace_prefix(s: str, prefix: str, repl: str): """Helper function to replace a prefix from a string.""" if s.startswith(prefix): return repl + s[len(prefix) :].strip() return s The provided code snippet includes necessary dependencies for implementing the `bot_intent_parser` function. Write a...
Parses the bot intent.
16,637
def _replace_prefix(s: str, prefix: str, repl: str): """Helper function to replace a prefix from a string.""" if s.startswith(prefix): return repl + s[len(prefix) :].strip() return s The provided code snippet includes necessary dependencies for implementing the `bot_message_parser` function. Write ...
Parses the bot messages.
16,638
def _replace_prefix(s: str, prefix: str, repl: str): """Helper function to replace a prefix from a string.""" if s.startswith(prefix): return repl + s[len(prefix) :].strip() return s The provided code snippet includes necessary dependencies for implementing the `verbose_v1_parser` function. Write a...
Parses completions generated using the `verbose_v1` formatter. This will convert text from the following format: User message: "Hello" User intent: express greeting Bot intent: express greeting Bot message: "Hi" To: user "Hello" express greeting bot express greeting "Hi"
16,639
import os from typing import List, Union import yaml from nemoguardrails.llm.types import Task from nemoguardrails.rails.llm.config import RailsConfig, TaskPrompt CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) class TaskPrompt(BaseModel): """Configuration for prompts that will be used for a specific task...
Load the predefined prompts from the `prompts` directory.
16,640
import os from typing import List, Union import yaml from nemoguardrails.llm.types import Task from nemoguardrails.rails.llm.config import RailsConfig, TaskPrompt _prompts = _load_prompts() def _get_prompt( task_name: str, model: str, prompting_mode: str, prompts: List ) -> TaskPrompt: """Return the prompt for ...
Return the prompt for the given task.
16,641
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) def get_colang_history( events: List[dict], include_texts: bool = True, remove_retrieval_events: bool = False, ) -> str: """Creates a history ...
Filter that turns an array of events into a colang history.
16,642
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) def get_colang_history( events: List[dict], include_texts: bool = True, remove_retrieval_events: bool = False, ) -> str: """Creates a history ...
Filter that turns an array of events into a colang history.
16,643
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `to_messages` function. Write a Python function `def to_messages(colang_history...
Filter that given a history in colang format, returns all messages.
16,644
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `verbose_v1` function. Write a Python function `def verbose_v1(colang_history: ...
Filter that given a history in colang format, returns a verbose version of the history.
16,645
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `user_assistant_sequence` function. Write a Python function `def user_assistant...
Filter that turns an array of events into a sequence of user/assistant messages. The output will look like: ``` User: hi Assistant: Hello there! User: What can you do? Assistant: I can help with many things. ```
16,646
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `remove_text_messages` function. Write a Python function `def remove_text_messa...
Filters that given a history in colang format, removes all texts.
16,647
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `first_turns` function. Write a Python function `def first_turns(colang_history...
Returns the first n turns from a given colang history.
16,648
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `last_turns` function. Write a Python function `def last_turns(colang_history: ...
Returns the last n turns from a given colang history.
16,649
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `indent` function. Write a Python function `def indent(text: str, n_spaces: int...
Indents the provided text with the provided number of spaces.
16,650
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `user_assistant_sequence_nemollm` function. Write a Python function `def user_a...
Filter that turns an array of events into a sequence of user/assistant messages. The output will look like: ``` <extra_id_1>User hi <extra_id_1>Assistant Hello there! <extra_id_1>User What can you do? <extra_id_1>Assistant I can help with many things. ```
16,651
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) def _previous_line(lines: List[str], i: int): """Returns the previous lines, skipping comments.""" i = i - 1 while i > 0 and lines[i].strip().start...
Filter that given a history in colang format, returns a messages string in the chat format used by NeMo LLM models.
16,652
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) def remove_trailing_new_line(s: str): if s.endswith("\n"): s = s[:-1] return s
null
16,653
import re import textwrap from typing import List from nemoguardrails.actions.llm.utils import ( get_colang_history, remove_action_intent_identifiers, ) The provided code snippet includes necessary dependencies for implementing the `conversation_to_events` function. Write a Python function `def conversation_to...
Filter that given a conversation, returns a list of events.
16,654
import asyncio import logging from typing import Any, Dict, List, Optional, Type from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.llms.huggingface_pipeline...
Automatically discover all LLM providers from LangChain.
16,655
import asyncio import logging from typing import Any, Dict, List, Optional, Type from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.llms.huggingface_pipeline...
Register an additional LLM provider.
16,656
import asyncio import logging from typing import Any, Dict, List, Optional, Type from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.llms.huggingface_pipeline...
null
16,657
import asyncio import logging from typing import Any, Dict, List, Optional, Type from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.llms.huggingface_pipeline...
Returns the list of supported LLM providers.
16,658
import asyncio import os from typing import Dict, List, Optional import aiohttp from prompt_toolkit import PromptSession from prompt_toolkit.patch_stdout import patch_stdout from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.colang.v2_x.runtime.eval import eval_expression from nemoguardrails.logging i...
Run a chat session in the terminal. Args: config_path (Optional[str]): The path to the configuration file. Defaults to None. verbose (bool): Whether to run in verbose mode. Defaults to False. verbose_llm_calls (bool): Whether to print the prompts and the completions. Defaults to False. streaming (bool): Whether to enab...
16,659
import asyncio import os import nest_asyncio nest_asyncio_patch_applied = False def apply(): global nest_asyncio_patch_applied if os.environ.get("DISABLE_NEST_ASYNCIO", "true").lower() not in [ "true", "1", "yes", ]: nest_asyncio.apply() nest_asyncio_patch_applied =...
null
16,660
import asyncio import os import nest_asyncio nest_asyncio_patch_applied = False The provided code snippet includes necessary dependencies for implementing the `check_sync_call_from_async_loop` function. Write a Python function `def check_sync_call_from_async_loop()` to solve the following problem: Helper to check if a...
Helper to check if a sync call is made from an async loop. Returns True if a sync call is made from an async loop.
16,661
import logging from typing import Optional from nemoguardrails.actions.actions import ActionResult, action from nemoguardrails.utils import new_event_dict class ActionResult: """Data class representing the result of an action. Attributes: return_value (Optional[Any]): The value returned by the action....
Creates an event for the bot based on the provided data. Args: event (dict): The input event data. context (Optional[dict]): The context for the action. Defaults to None. Returns: ActionResult: An action result containing the created event.
16,662
import logging import os from typing import Optional from urllib import parse import aiohttp from nemoguardrails.actions import action from nemoguardrails.actions.actions import ActionResult from nemoguardrails.utils import new_event_dict log = logging.getLogger(__name__) APP_ID = os.environ.get("WOLFRAM_ALPHA_APP_ID")...
Makes a request to the Wolfram Alpha API. Args: query (Optional[str]): The query for Wolfram Alpha. Defaults to None. context (Optional[dict]): The context for the execution of the action. Defaults to None. Returns: ActionResult or str: The result of the Wolfram Alpha request. Raises: Exception: If no query is provided...
16,663
from dataclasses import dataclass, field from typing import Any, List, Optional The provided code snippet includes necessary dependencies for implementing the `action` function. Write a Python function `def action( is_system_action: bool = False, name: Optional[str] = None, execute_async: bool = False, )` ...
Decorator to mark a function or class as an action. Args: is_system_action (bool): Flag indicating if the action is a system action. name (Optional[str]): The name to associate with the action. execute_async: Whether the function should be executed in async mode. Returns: callable: The decorated function or class.
16,664
import logging import re from ast import literal_eval from typing import Any, List, Optional from langchain.llms import BaseLLM from nemoguardrails.actions.actions import action from nemoguardrails.actions.llm.generation import LLMGenerationActions from nemoguardrails.actions.llm.utils import ( escape_flow_name, ...
Remove the leading empty lines if they exist. A line is considered empty if it has only white spaces.
16,665
import json import re from typing import List from urllib.parse import quote from .filter_secrets import contains_secrets MAX_LEN = 50 The provided code snippet includes necessary dependencies for implementing the `validate_input` function. Write a Python function `def validate_input(attribute: str, validators: List[s...
A generic decorator that can be used by any action (class method or function) for input validation. Supported validation choices are: length and quote.
16,666
import json import re from typing import List from urllib.parse import quote from .filter_secrets import contains_secrets MAX_LEN = 50 def _is_default_resp(resp): """Helper for detecting a default response from LangChain tools.""" pattern = re.compile(r"^No good.*result(?: was)? found$", re.IGNORECASE) matc...
A generic decorator that can be used by any action (class method or function) for response validation. Supported validation choices are: length, ip_filter, is_default_resp
16,667
import logging from typing import Optional from nemoguardrails.actions.actions import ActionResult, action from nemoguardrails.kb.kb import KnowledgeBase class ActionResult: """Data class representing the result of an action. Attributes: return_value (Optional[Any]): The value returned by the action. ...
Retrieve relevant knowledge chunks and update the context. Args: context (Optional[dict]): The context for the execution of the action. Defaults to None. kb (Optional[KnowledgeBase]): The KnowledgeBase to search for relevant chunks. Defaults to None. Returns: ActionResult: An action result containing the retrieved rele...
16,668
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Converts a flow to colang format. Example flow: ``` - user: ask capabilities - bot: inform capabilities ``` to colang: ``` user ask capabilities bot inform capabilities ```
16,669
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the retrieved chunks for current user utterance from the events.
16,670
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the last user utterance from the events.
16,671
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the last user utterance from the events.
16,672
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the last user intent from the events.
16,673
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the last user intent from the events.
16,674
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the last bot utterance from the events.
16,675
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Helper that given a history in colang format, removes all texts.
16,676
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Helper that returns the first non-empty line from a string
16,677
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Helper that returns a list with the top k non-empty lines from a string. If there are less than k non-empty lines, it returns a smaller number of lines.
16,678
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Returns the first action before an empty line.
16,679
import re from typing import List, Optional, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import AsyncCallbackHandler, BaseCallbackManager from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.schema import AIM...
Escape invalid keywords in flow names.
16,680
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
Returns the list of available rails configurations.
16,681
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
Chat completion for the provided conversation. TODO: add support for explicit state object.
16,682
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
Returns the list of available challenges for red teaming.
16,683
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
Registers a DataStore to be used by the server.
16,684
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
Register any additional challenges, if available at startup.
16,685
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
Register an additional logger
16,686
import asyncio import contextvars import importlib.util import json import logging import os.path import time from typing import List, Optional from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Fi...
null
16,687
import json from nemoguardrails.llm.providers import get_llm_provider, get_llm_provider_names from nemoguardrails.rails.llm.config import Model class Model(BaseModel): """Configuration of a model used by the rails engine. Typically, the main model is configured e.g.: { "type": "main", "eng...
Initializes the model from LLM provider.
16,688
import json from nemoguardrails.llm.providers import get_llm_provider, get_llm_provider_names from nemoguardrails.rails.llm.config import Model The provided code snippet includes necessary dependencies for implementing the `load_dataset` function. Write a Python function `def load_dataset(dataset_path: str)` to solve ...
Loads a dataset from a file.
16,689
import json import typer def load_dataset(input_path, split="harmful"): """ Loads the dataset from the given path. Args: input_path (str): The path to the dataset. split (str, optional): The split of the dataset (harmful or helpful). Defaults to "harmful". Returns: dict or list: ...
Extracts the first turn harmful prompts from the red team attempts dataset. Args: input_path (str): The path to the dataset. rating (float): The harmfulness rating. Returns: None
16,690
import json import typer def load_dataset(input_path, split="harmful"): """ Loads the dataset from the given path. Args: input_path (str): The path to the dataset. split (str, optional): The split of the dataset (harmful or helpful). Defaults to "harmful". Returns: dict or list: ...
Extracts the first turn helpful prompts from the helpful-base dataset. Args: input_path (str): The path to the dataset. Returns: None
16,691
import logging from typing import List import typer from nemoguardrails.eval.evaluate_factcheck import FactCheckEvaluation from nemoguardrails.eval.evaluate_hallucination import HallucinationRailsEvaluation from nemoguardrails.eval.evaluate_moderation import ModerationRailsEvaluation from nemoguardrails.eval.evaluate_t...
Evaluates the performance of the topical rails defined in a Guardrails application. Computes accuracy for canonical form detection, next step generation, and next bot message generation. Only a single Guardrails application can be specified in the config option. Args: config (List[str], optional): Path to a directory c...
16,692
import logging from typing import List import typer from nemoguardrails.eval.evaluate_factcheck import FactCheckEvaluation from nemoguardrails.eval.evaluate_hallucination import HallucinationRailsEvaluation from nemoguardrails.eval.evaluate_moderation import ModerationRailsEvaluation from nemoguardrails.eval.evaluate_t...
Evaluate the performance of the moderation rails defined in a Guardrails application. This command computes accuracy for jailbreak detection and output moderation. Args: config (str): The path to the guardrails config. Defaults to "config". dataset_path (str): Path to the dataset containing prompts. Defaults to "nemogu...
16,693
import logging from typing import List import typer from nemoguardrails.eval.evaluate_factcheck import FactCheckEvaluation from nemoguardrails.eval.evaluate_hallucination import HallucinationRailsEvaluation from nemoguardrails.eval.evaluate_moderation import ModerationRailsEvaluation from nemoguardrails.eval.evaluate_t...
Evaluate the performance of the hallucination rails defined in a Guardrails application. This command computes accuracy for hallucination detection. Args: config (str): The path to the guardrails config. Defaults to "config". dataset_path (str): Dataset path. Defaults to "nemoguardrails/eval/data/hallucination/sample.t...
16,694
import logging from typing import List import typer from nemoguardrails.eval.evaluate_factcheck import FactCheckEvaluation from nemoguardrails.eval.evaluate_hallucination import HallucinationRailsEvaluation from nemoguardrails.eval.evaluate_moderation import ModerationRailsEvaluation from nemoguardrails.eval.evaluate_t...
Evaluate the performance of the fact-checking rails defined in a Guardrails application. This command computes accuracy for fact-checking. Negatives can be created synthetically by an LLM that acts as an adversary and modifies the answer to make it incorrect. Args: config (str): The path to the guardrails config. Defau...
16,695
import asyncio import json import os import random import textwrap from typing import Dict, List, Optional import numpy as np from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions.llm.utils import ( get_last_bot_intent_event, get_last_bot_utterance_event, get_last_user_intent_event, )...
Wrapper for the evaluate_topical_rails method which is async.
16,696
import asyncio import json import os import random import textwrap from typing import Dict, List, Optional import numpy as np from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions.llm.utils import ( get_last_bot_intent_event, get_last_bot_utterance_event, get_last_user_intent_event, )...
Compute the dot product between two embeddings using numpy functions.
16,697
import asyncio import json import os import random import textwrap from typing import Dict, List, Optional import numpy as np from nemoguardrails import LLMRails, RailsConfig from nemoguardrails.actions.llm.utils import ( get_last_bot_intent_event, get_last_bot_utterance_event, get_last_user_intent_event, )...
Extracts a test set of user messages from a config. Args: config: The config from which the test set will be extracted. test_set_percentage: The percentage used for the test set. test_set: A dictionary where the test set will be added. max_samples_per_intent: A limit on the number of samples per intent to be enforced.
16,698
import os import re import subprocess from pathlib import Path import typer import yaml def run_nbdoc_build(srcdir, force_all): try: # Run the nbdoc_build command with specified arguments subprocess.run( ["nbdoc_build", "--srcdir", srcdir, "--force_all", str(force_all)], chec...
Convert a Jupyter notebook in the provided folder to .md. It creates a README.md file next to the Jupyter notebook.
16,699
import torch import numpy as np from PIL import Image from controlnet_aux import OpenposeDetector from model_util import get_torch_device import cv2 from transformers import DPTImageProcessor, DPTForDepthEstimation depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device) feature_extr...
null
16,700
import torch import numpy as np from PIL import Image from controlnet_aux import OpenposeDetector from model_util import get_torch_device import cv2 from transformers import DPTImageProcessor, DPTForDepthEstimation def get_canny_image(image, t1=100, t2=200): image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)...
null