id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
141,861 | import logging
import os
import tempfile
import urllib.parse
import urllib.robotparser
from typing import List, Optional, Set, Tuple
from urllib.parse import urldefrag, urljoin, urlparse
import fire
import requests
from bs4 import BeautifulSoup
from pydantic import BaseModel, HttpUrl, ValidationError, parse_obj_as
from... | null |
141,862 | from functools import reduce
from typing import Callable, List
import tiktoken
from pydantic import BaseSettings
from pygments import lex
from pygments.lexers import get_lexer_by_name
from pygments.token import Token
from langroid.mytypes import Document
The provided code snippet includes necessary dependencies for im... | Chunk code into smaller pieces, so that we don't exceed the maximum number of tokens allowed by the embedding model. Args: code: string of code language: str as a file extension, e.g. "py", "yml" max_tokens: max tokens per chunk len_fn: function to get the length of a string in token units Returns: |
141,863 | import difflib
from typing import List, Tuple
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from rank_bm25 import BM25Okapi
from thefuzz import fuzz, process
from langroid.mytypes import Document
from .utils import download_nltk_resource
def get_cont... | Find approximate matches of the query in the docs and return surrounding characters. Args: query (str): The search string. docs (List[Document]): List of Document objects to search through. k (int): Number of best matches to return. words_before (int|None): Number of words to include before each match. Default None => ... |
141,864 | import difflib
from typing import List, Tuple
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from rank_bm25 import BM25Okapi
from thefuzz import fuzz, process
from langroid.mytypes import Document
from .utils import download_nltk_resource
def preproce... | Finds the k closest approximate matches using the BM25 algorithm. Args: docs (List[Document]): List of Documents to search through. docs_clean (List[Document]): List of cleaned Documents query (str): The search query. k (int, optional): Number of matches to retrieve. Defaults to 5. Returns: List[Tuple[Document,float]]:... |
141,865 | import difflib
from typing import List, Tuple
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from rank_bm25 import BM25Okapi
from thefuzz import fuzz, process
from langroid.mytypes import Document
from .utils import download_nltk_resource
The provide... | Eliminate near duplicate text passages from a given list using MinHash and LSH. TODO: this has not been tested and the datasketch lib is not a dependency. Args: passages (List[str]): A list of text passages. threshold (float, optional): Jaccard similarity threshold to consider two passages as near-duplicates. Default i... |
141,866 | from typing import List, Set, no_type_check
from urllib.parse import urlparse
from pydispatch import dispatcher
from scrapy import signals
from scrapy.crawler import CrawlerRunner
from scrapy.http import Response
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from twisted.i... | Fetches up to k URLs reachable from the input URL using Scrapy. Args: url (str): The starting URL. k (int, optional): The max desired final URLs. Defaults to 20. Returns: List[str]: List of URLs within the same domain as the input URL. |
141,867 | import itertools
import json
import logging
import os
import subprocess
import tempfile
import time
from collections import deque
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from github... | null |
141,868 | import itertools
import json
import logging
import os
import subprocess
import tempfile
import time
from collections import deque
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from github... | Recursively checks if there is at least one file in a directory. |
141,869 | import itertools
import json
import logging
import os
import subprocess
import tempfile
import time
from collections import deque
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from github... | null |
141,870 | from csv import Sniffer
from typing import List
import pandas as pd
The provided code snippet includes necessary dependencies for implementing the `read_tabular_data` function. Write a Python function `def read_tabular_data(path_or_url: str, sep: None | str = None) -> pd.DataFrame` to solve the following problem:
Read... | Reads tabular data from a file or URL and returns a pandas DataFrame. The separator is auto-detected if not specified. Args: path_or_url (str): Path or URL to the file to be read. Returns: pd.DataFrame: Data from file or URL as a pandas DataFrame. Raises: ValueError: If the data cannot be read or is misformatted. |
141,871 | from csv import Sniffer
from typing import List
import pandas as pd
The provided code snippet includes necessary dependencies for implementing the `describe_dataframe` function. Write a Python function `def describe_dataframe( df: pd.DataFrame, filter_fields: List[str] = [], n_vals: int = 10 ) -> str` to solve the... | Generates a description of the columns in the dataframe, along with a listing of up to `n_vals` unique values for each column. Intended to be used to insert into an LLM context so it can generate appropriate queries or filters on the df. Args: df (pd.DataFrame): The dataframe to describe. filter_fields (list): A list o... |
141,872 | import getpass
import hashlib
import importlib
import inspect
import logging
import shutil
import socket
import traceback
from typing import Any
logger = logging.getLogger(__name__)
DELETION_ALLOWED_PATHS = [
".qdrant",
".chroma",
".lancedb",
]
The provided code snippet includes necessary dependencies for ... | Remove a directory recursively. Args: path (str): path to directory to remove Returns: True if a dir was removed, false otherwise. Raises error if failed to remove. |
141,873 | import getpass
import hashlib
import importlib
import inspect
import logging
import shutil
import socket
import traceback
from typing import Any
The provided code snippet includes necessary dependencies for implementing the `caller_name` function. Write a Python function `def caller_name() -> str` to solve the followi... | Who called the function? |
141,874 | import getpass
import hashlib
import importlib
import inspect
import logging
import shutil
import socket
import traceback
from typing import Any
def friendly_error(e: Exception, msg: str = "An error occurred.") -> str:
tb = traceback.format_exc()
original_error_message: str = str(e)
full_error_message: str... | null |
141,875 | import getpass
import hashlib
import importlib
import inspect
import logging
import shutil
import socket
import traceback
from typing import Any
The provided code snippet includes necessary dependencies for implementing the `generate_user_id` function. Write a Python function `def generate_user_id(org: str = "") -> st... | Generate a unique user ID based on the username and machine name. Returns: |
141,876 | import getpass
import hashlib
import importlib
import inspect
import logging
import shutil
import socket
import traceback
from typing import Any
The provided code snippet includes necessary dependencies for implementing the `update_hash` function. Write a Python function `def update_hash(hash: str | None = None, s: st... | Takes a SHA256 hash string and a new string, updates the hash with the new string, and returns the updated hash string along with the original string. Args: hash (str): A SHA256 hash string. s (str): A new string to update the hash with. Returns: The updated hash in hexadecimal format. |
141,877 | from typing import Dict, List, no_type_check
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `topological_sort` function. Write a Python function `def topological_sort(order: np.array) -> List[int]` to solve the following problem:
Given a directed adjacency matrix, ret... | Given a directed adjacency matrix, return a topological sort of the nodes. order[i,j] = -1 means there is an edge from i to j. order[i,j] = 0 means there is no edge from i to j. order[i,j] = 1 means there is an edge from j to i. Args: order (np.array): The adjacency matrix. Returns: List[int]: The topological sort of t... |
141,878 | from typing import Dict, List, no_type_check
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `components` function. Write a Python function `def components(order: np.ndarray) -> List[List[int]]` to solve the following problem:
Find the connected components in an undire... | Find the connected components in an undirected graph represented by a matrix. Args: order (np.ndarray): A matrix with values 0 or 1 indicating undirected graph edges. `order[i][j] = 1` means an edge between `i` and `j`, and `0` means no edge. Returns: List[List[int]]: A list of List where each List contains the indices... |
141,879 | import logging
import os.path
from typing import no_type_check
import colorlog
from rich.console import Console
import logging
def setup_colored_logging() -> None:
# Define the log format with color codes
log_format = "%(log_color)s%(asctime)s - %(levelname)s - %(message)s%(reset)s"
# Create a color forma... | null |
141,880 | import logging
import os.path
from typing import no_type_check
import colorlog
from rich.console import Console
def setup_logger(name: str, level: int = logging.INFO) -> logging.Logger:
import logging
def setup_console_logger(name: str) -> logging.Logger:
logger = setup_logger(name)
handler = logging.StreamHa... | null |
141,881 | import logging
import os.path
from typing import no_type_check
import colorlog
from rich.console import Console
def setup_logger(name: str, level: int = logging.INFO) -> logging.Logger:
"""
Set up a logger of module `name` at a desired level.
Args:
name: module name
level: desired logging le... | null |
141,882 | import logging
import os.path
from typing import no_type_check
import colorlog
from rich.console import Console
def setup_logger(name: str, level: int = logging.INFO) -> logging.Logger:
"""
Set up a logger of module `name` at a desired level.
Args:
name: module name
level: desired logging le... | Set up loggers for all modules in a package. This ensures that log-levels of modules outside the package are not affected. Args: package_name: main package name level: desired logging level Returns: |
141,883 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Check if a Pydantic model class has a field with the given name. |
141,884 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Remove a key from a dictionary recursively |
141,885 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Given a possibly nested Pydantic class, return a flattened version of it, by constructing top-level fields, whose names are formed from the path through the nested structure, separated by double underscores. This version ignores inherited defaults, so it is incomplete. But retaining it as it is simpler and may be usefu... |
141,886 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Get all field names from a possibly nested Pydantic model. |
141,887 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Generates a JSON schema for a Pydantic model, with options to exclude specific fields. This function traverses the Pydantic model's fields, including nested models, to generate a dictionary representing the JSON schema. Fields specified in the exclude list will not be included in the generated schema. Args: model (Type... |
141,888 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Given a possibly nested Pydantic instance, return a flattened version of it, as a dict where nested traversal paths are translated to keys a__b__c. Args: instance (BaseModel): The Pydantic instance to flatten. prefix (str, optional): The prefix to use for the top-level fields. force_str (bool, optional): Whether to for... |
141,889 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Extract specified fields from a Pydantic object. Supports dotted field names, e.g. "metadata.author". Dotted fields are matched exactly according to the corresponding path. Non-dotted fields are matched against the last part of the path. Clashes ignored. Args: doc (BaseModel): The Pydantic object. fields (List[str]): T... |
141,890 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Flattened dict with a__b__c style keys -> nested dict -> pydantic object |
141,891 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Generate a simple schema for a given Pydantic model, including inherited fields, with an option to exclude certain fields. Handles cases where fields are Lists or other generic types and includes field descriptions if available. Args: model (Type[BaseModel]): The Pydantic model class. excludes (List[str]): A list of fi... |
141,892 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | null |
141,893 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Context manager to temporarily override `field` in a `config` |
141,894 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Make a list of Pydantic objects from a dataframe. |
141,895 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Make a list of Document objects from a dataframe. Args: df (pd.DataFrame): The dataframe. content (str): The name of the column containing the content, which will map to the Document.content field. metadata (List[str]): A list of column names containing metadata; these will be included in the Document.metadata field. d... |
141,896 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Checks for extra fields in a document's metadata that are not defined in the original metadata schema. Args: document (Document): The document instance to check for extra fields. doc_cls (Type[Document]): The class type derived from Document, used as a reference to identify extra fields in the document's metadata. Retu... |
141,897 | import logging
from contextlib import contextmanager
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TypeVar,
get_args,
get_origin,
no_type_check,
)
import numpy as np
import pandas as pd
from pydantic import BaseModel, ValidationError, create_model
fr... | Generates a new pydantic class based on a given document instance. This function dynamically creates a new pydantic class with additional fields based on the "extra" metadata fields present in the given document instance. The new class is a subclass of the original Document class, with the original metadata fields reta... |
141,898 | import logging
import sys
from contextlib import contextmanager
from typing import Any, Iterator, Optional
from rich import print as rprint
from rich.text import Text
from langroid.utils.configuration import settings
from langroid.utils.constants import Colors
def shorten_text(text: str, chars: int = 40) -> str:
t... | null |
141,899 | import logging
import sys
from contextlib import contextmanager
from typing import Any, Iterator, Optional
from rich import print as rprint
from rich.text import Text
from langroid.utils.configuration import settings
from langroid.utils.constants import Colors
def print_long_text(
color: str, style: str, preamble: ... | null |
141,900 | import logging
import sys
from contextlib import contextmanager
from typing import Any, Iterator, Optional
from rich import print as rprint
from rich.text import Text
from langroid.utils.configuration import settings
from langroid.utils.constants import Colors
The provided code snippet includes necessary dependencies ... | Temporarily silence all output to stdout and from rich.print. This context manager redirects all output written to stdout (which includes outputs from the built-in print function and rich.print) to /dev/null on UNIX-like systems or NUL on Windows. Once the context block exits, stdout is restored to its original state. ... |
141,901 | import copy
import os
from contextlib import contextmanager
from typing import Iterator, List, Literal
from dotenv import find_dotenv, load_dotenv
from pydantic import BaseSettings
class Settings(BaseSettings):
# NOTE all of these can be overridden in your .env file with upper-case names,
# for example CACHE_TY... | Update global settings so modules can access them via (as an example): ``` from langroid.utils.configuration import settings if settings.debug... ``` Caution we do not want to have too many such global settings! Args: cfg: pydantic config, typically from a main script keys: which keys from cfg to use, to update the glo... |
141,902 | import copy
import os
from contextlib import contextmanager
from typing import Iterator, List, Literal
from dotenv import find_dotenv, load_dotenv
from pydantic import BaseSettings
class Settings(BaseSettings):
# NOTE all of these can be overridden in your .env file with upper-case names,
# for example CACHE_TY... | Temporarily update the global settings and restore them afterward. |
141,903 | import copy
import os
from contextlib import contextmanager
from typing import Iterator, List, Literal
from dotenv import find_dotenv, load_dotenv
from pydantic import BaseSettings
The provided code snippet includes necessary dependencies for implementing the `set_env` function. Write a Python function `def set_env(se... | Set environment variables from a BaseSettings instance Args: settings (BaseSettings): desired settings Returns: |
141,904 | from typing import Any
import pandas as pd
def stringify(x: Any) -> str:
# Convert x to DataFrame if it is not one already
if isinstance(x, pd.Series):
df = x.to_frame()
elif not isinstance(x, pd.DataFrame):
return str(x)
else:
df = x
# Truncate long text columns to 1000 ch... | null |
141,905 | import typer
from rich import print
from pydantic import BaseModel
import json
import os
from langroid.agent.openai_assistant import (
OpenAIAssistantConfig,
OpenAIAssistant,
AssistantTool,
)
import langroid as lr
from langroid.agent.task import Task
from langroid.agent.tool_message import ToolMessage
from ... | null |
141,906 | import os
import fire
import langroid as lr
import langroid.language_models as lm
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
class DocChatAgentConfig(ChatAgentConfig):
class DocChatAgent(ChatAgent):
def __init__(
self,
config: DocChatAgentConfig,
... | null |
141,907 | import re
from typing import List
import typer
from rich import print
from rich.prompt import Prompt
from pydantic import BaseSettings
import langroid.language_models as lm
from langroid.agent.tool_message import ToolMessage
from langroid.agent.chat_agent import ChatAgent, ChatDocument
from langroid.agent.special.doc_c... | null |
141,908 | import typer
from rich import print
from rich.prompt import Prompt
import os
import tempfile
from langroid.agent.openai_assistant import (
OpenAIAssistantConfig,
OpenAIAssistant,
AssistantTool,
)
from langroid.parsing.url_loader import URLLoader
from langroid.language_models.openai_gpt import OpenAIChatMode... | null |
141,909 | from langroid.agent.special import DocChatAgent, DocChatAgentConfig
from langroid.vector_store.lancedb import LanceDBConfig
from langroid.embedding_models.models import OpenAIEmbeddingsConfig
from langroid.parsing.parser import ParsingConfig
from langroid.language_models.openai_gpt import OpenAIGPTConfig
import os
impo... | null |
141,910 | from langroid.agent.special import DocChatAgent, DocChatAgentConfig
from langroid.vector_store.lancedb import LanceDBConfig
from langroid.embedding_models.models import OpenAIEmbeddingsConfig
from langroid.parsing.parser import ParsingConfig
from langroid.language_models.openai_gpt import OpenAIGPTConfig
import os
impo... | null |
141,911 | import typer
from rich import print
from rich.prompt import Prompt
import os
import tempfile
from langroid.agent.openai_assistant import (
OpenAIAssistantConfig,
OpenAIAssistant,
AssistantTool,
)
from langroid.mytypes import Entity
from langroid.parsing.url_loader import URLLoader
from langroid.language_mod... | null |
141,912 | import typer
from rich import print
import os
from langroid.agent.special.doc_chat_agent import (
DocChatAgent,
DocChatAgentConfig,
)
from langroid.mytypes import Entity
from langroid.parsing.parser import ParsingConfig, PdfParsingConfig, Splitter
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig... | null |
141,913 | import typer
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.task import Task
from langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig
from langroid.utils.configuration import set_global, Settings
from langroid.utils.logging import setup_colored_logging
clas... | null |
141,914 | import typer
from rich import print
import langroid as lr
lr.utils.logging.setup_colored_logging()
documents = [
lr.mytypes.Document(
content="""
In the year 2050, GPT10 was released.
In 2057, paperclips were seen all over the world.
Global warming was solved in 2060.
... | null |
141,915 | import typer
from rich import print
from rich.prompt import Prompt
import langroid as lr
Role = lr.language_models.Role
LLMMessage = lr.language_models.LLMMessage
def chat() -> None:
print("[blue]Welcome to langroid!")
cfg = lr.language_models.OpenAIGPTConfig(
chat_model=lr.language_models.OpenAIChatM... | null |
141,916 | import typer
import langroid as lr
lr.utils.logging.setup_colored_logging()
def chat(tools: bool = False) -> None:
config = lr.ChatAgentConfig(
llm=lr.language_models.OpenAIGPTConfig(
chat_model=lr.language_models.OpenAIChatModel.GPT4,
),
use_tools=tools,
use_functions_a... | null |
141,917 | import typer
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.tools.recipient_tool import RecipientTool
from langroid.agent.task import Task
from langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig
from langroid.utils.configuration import set_global, Settings
... | null |
141,918 | import typer
from rich import print
from pydantic import BaseSettings
import langroid as lr
lr.utils.logging.setup_colored_logging()
class ProbeTool(lr.agent.ToolMessage):
request: str = "probe"
purpose: str = """
To find how many numbers in my list are less than or equal to
the <number> you s... | null |
141,919 | import typer
from rich import print
import langroid as lr
lr.utils.logging.setup_colored_logging()
def chat() -> None:
print(
"""
[blue]Welcome to the basic chatbot!
Enter x or q to quit
"""
)
config = lr.ChatAgentConfig(
llm=lr.language_models.OpenAIGPTConfig(
... | null |
141,920 | import langroid as lr
import langroid.language_models as lm
import chainlit as cl
async def on_chat_start():
lm_config = lm.OpenAIGPTConfig(chat_model="ollama/mistral")
agent = lr.ChatAgent(lr.ChatAgentConfig(llm=lm_config))
task = lr.Task(agent, interactive=True)
msg = "Help me with some questions"
... | null |
141,921 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import add_instructions
from textwrap import dedent
class CapitalTool(lr.ToolMessage):
request = "capital"
purpose = "To present the capital of given <country>."
country: str
capital: str
def handle(self) -> str:
... | null |
141,922 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import add_instructions
from textwrap import dedent
try:
import chainlit as cl
except ImportError:
raise ImportError(
"""
You are attempting to use `chainlit`, which is not installed
by default with `lan... | null |
141,923 | from typing import Optional
import chainlit as cl
import langroid as lr
from langroid import ChatDocument
from langroid.agent.tools.metaphor_search_tool import MetaphorSearchTool
from langroid.agent.tools.duckduckgo_search_tool import DuckduckgoSearchTool
from langroid.agent.callbacks.chainlit import (
add_instruct... | null |
141,924 | from typing import Optional
import chainlit as cl
import langroid as lr
from langroid import ChatDocument
from langroid.agent.tools.metaphor_search_tool import MetaphorSearchTool
from langroid.agent.tools.duckduckgo_search_tool import DuckduckgoSearchTool
from langroid.agent.callbacks.chainlit import (
add_instruct... | null |
141,925 | from typing import Optional
import chainlit as cl
import langroid as lr
from langroid import ChatDocument
from langroid.agent.tools.metaphor_search_tool import MetaphorSearchTool
from langroid.agent.tools.duckduckgo_search_tool import DuckduckgoSearchTool
from langroid.agent.callbacks.chainlit import (
add_instruct... | null |
141,926 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import ChainlitTaskCallbacks
from langroid.agent.callbacks.chainlit import add_instructions
from langroid.utils.configuration import settings
from textwrap import dedent
async def add_instructions(
title: str = "Instructions",
c... | null |
141,927 | from typing import List, Optional, Type
from dotenv import load_dotenv
from textwrap import dedent
import chainlit as cl
import langroid as lr
from langroid.agent.callbacks.chainlit import add_instructions
import langroid.language_models as lm
from langroid import ChatDocument
from langroid.agent.tools.duckduckgo_searc... | null |
141,928 | import chainlit as cl
import langroid as lr
import langroid.language_models as lm
import langroid.parsing.parser as lp
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
from langroid.utils.constants import NO_ANSWER
from langroid.agent.callbacks.chainlit import (
add_instructions,
... | null |
141,929 | import chainlit as cl
import langroid as lr
import langroid.language_models as lm
import langroid.parsing.parser as lp
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
from langroid.utils.constants import NO_ANSWER
from langroid.agent.callbacks.chainlit import (
add_instructions,
... | null |
141,930 | import chainlit as cl
import langroid as lr
import langroid.language_models as lm
import langroid.parsing.parser as lp
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
from langroid.utils.constants import NO_ANSWER
from langroid.agent.callbacks.chainlit import (
add_instructions,
... | null |
141,931 | import typer
from rich import print
from pyvis.network import Network
import webbrowser
from pathlib import Path
import langroid as lr
import langroid.language_models as lm
import chainlit as cl
from langroid.agent.callbacks.chainlit import (
add_instructions,
make_llm_settings_widgets,
setup_llm,
updat... | null |
141,932 | import typer
from rich import print
from pyvis.network import Network
import webbrowser
from pathlib import Path
import langroid as lr
import langroid.language_models as lm
import chainlit as cl
from langroid.agent.callbacks.chainlit import (
add_instructions,
make_llm_settings_widgets,
setup_llm,
updat... | null |
141,933 | import typer
from rich import print
from pyvis.network import Network
import webbrowser
from pathlib import Path
import langroid as lr
import langroid.language_models as lm
import chainlit as cl
from langroid.agent.callbacks.chainlit import (
add_instructions,
make_llm_settings_widgets,
setup_llm,
updat... | null |
141,934 | from typing import List
import typer
import langroid as lr
import langroid.language_models as lm
from langroid.agent.tool_message import ToolMessage
from langroid.agent.chat_agent import ChatAgent, ChatDocument
from langroid.agent.special.doc_chat_agent import (
DocChatAgent,
DocChatAgentConfig,
)
from langroid... | null |
141,935 | from typing import List
import typer
import langroid as lr
import langroid.language_models as lm
from langroid.agent.tool_message import ToolMessage
from langroid.agent.chat_agent import ChatAgent, ChatDocument
from langroid.agent.special.doc_chat_agent import (
DocChatAgent,
DocChatAgentConfig,
)
from langroid... | null |
141,936 | from typing import List
import typer
import langroid as lr
import langroid.language_models as lm
from langroid.agent.tool_message import ToolMessage
from langroid.agent.chat_agent import ChatAgent, ChatDocument
from langroid.agent.special.doc_chat_agent import (
DocChatAgent,
DocChatAgentConfig,
)
from langroid... | null |
141,937 | import chainlit as cl
import langroid as lr
from langroid.agent.callbacks.chainlit import add_instructions
try:
import chainlit as cl
except ImportError:
raise ImportError(
"""
You are attempting to use `chainlit`, which is not installed
by default with `langroid`.
Please insta... | null |
141,938 | import chainlit as cl
import langroid as lr
from langroid.agent.callbacks.chainlit import add_instructions
try:
import chainlit as cl
except ImportError:
raise ImportError(
"""
You are attempting to use `chainlit`, which is not installed
by default with `langroid`.
Please insta... | null |
141,939 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import ChainlitTaskCallbacks
from langroid.utils.constants import DONE
from langroid.utils.configuration import settings
from langroid.agent.callbacks.chainlit import add_instructions
from textwrap import dedent
class ExportTool(lr.ToolM... | null |
141,940 | import chainlit as cl
import langroid as lr
class CapitalTool(lr.ToolMessage):
request = "capital"
purpose = "To present the capital of given <country>."
country: str
capital: str
def handle(self) -> str:
return f"""
Success! LLM responded with a tool/function-call, with result:
... | null |
141,941 | import chainlit as cl
import langroid as lr
async def llm_tool_call(msg: str) -> lr.ChatDocument:
agent: lr.ChatAgent = cl.user_session.get("agent")
response = await agent.llm_response_async(msg)
return response
async def on_message(message: cl.Message):
agent: lr.ChatAgent = cl.user_session.get("agent... | null |
141,942 | import chainlit as cl
import langroid as lr
from langroid.agent.tools.metaphor_search_tool import MetaphorSearchTool
class MetaphorSearchTool(ToolMessage):
request: str = "metaphor_search"
purpose: str = """
To search the web and return up to <num_results>
links relevant to the given <... | null |
141,943 | import chainlit as cl
import langroid as lr
from langroid.agent.tools.metaphor_search_tool import MetaphorSearchTool
async def llm_response(msg: str) -> lr.ChatDocument:
agent: lr.ChatAgent = cl.user_session.get("agent")
response = await agent.llm_response_async(msg)
return response
async def agent_response... | null |
141,944 | import chainlit as cl
import langroid as lr
async def on_chat_start():
sys_msg = "You are a helpful assistant. Be concise in your answers."
config = lr.ChatAgentConfig(
system_message=sys_msg,
)
agent = lr.ChatAgent(config)
cl.user_session.set("agent", agent) | null |
141,945 | import chainlit as cl
import langroid as lr
async def on_message(message: cl.Message):
agent: lr.ChatAgent = cl.user_session.get("agent")
response = await agent.llm_response_async(message.content)
msg = cl.Message(content=response.content)
await msg.send() | null |
141,946 | import chainlit as cl
import langroid.parsing.parser as lp
import langroid.language_models as lm
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
async def setup_agent() -> None:
model = cl.user_session.get("settings", {}).get("ModelName")
print(f"Using model: {model}")
llm... | null |
141,947 | import chainlit as cl
import langroid.parsing.parser as lp
import langroid.language_models as lm
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
async def setup_agent() -> None:
model = cl.user_session.get("settings", {}).get("ModelName")
print(f"Using model: {model}")
llm... | null |
141,948 | import chainlit as cl
import langroid.parsing.parser as lp
import langroid.language_models as lm
from langroid.agent.special.doc_chat_agent import DocChatAgent, DocChatAgentConfig
class DocChatAgent(ChatAgent):
def __init__(
self,
config: DocChatAgentConfig,
):
def clear(self)... | null |
141,949 | import chainlit as cl
from langroid import ChatAgent, ChatAgentConfig
from langroid.utils.configuration import settings
import re
import sys
import asyncio
async def on_chat_start():
sys_msg = "You are a helpful assistant. Be concise in your answers."
config = ChatAgentConfig(
system_message=sys_msg,
... | null |
141,950 | import chainlit as cl
from langroid import ChatAgent, ChatAgentConfig
from langroid.utils.configuration import settings
import re
import sys
import asyncio
class ContinuousCaptureStream:
"""
Capture stdout in a stream.
This allows capturing of streaming output that would normally be printed to stdout,
e... | null |
141,951 | from dotenv import load_dotenv
from textwrap import dedent
import chainlit as cl
import langroid as lr
from langroid.agent.callbacks.chainlit import add_instructions
import langroid.language_models as lm
from langroid.agent.tools.google_search_tool import GoogleSearchTool
from langroid.agent.tools.duckduckgo_search_too... | null |
141,952 | from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.task import Task
from langroid.agent.tool_message import ToolMessage
from langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig
from langroid.utils.globals import GlobalState
from langroid.utils.configuration impo... | null |
141,953 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import (
add_instructions,
make_llm_settings_widgets,
update_llm,
setup_llm,
)
from textwrap import dedent
async def setup_agent_task():
await setup_llm()
llm_config = cl.user_session.get("llm_config")
if task... | null |
141,954 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import (
add_instructions,
make_llm_settings_widgets,
update_llm,
setup_llm,
)
from textwrap import dedent
async def setup_agent_task():
async def make_llm_settings_widgets(
config: lm.OpenAIGPTConfig | None = None,
... | null |
141,955 | import langroid as lr
import chainlit as cl
from langroid.agent.callbacks.chainlit import (
add_instructions,
make_llm_settings_widgets,
update_llm,
setup_llm,
)
from textwrap import dedent
try:
import chainlit as cl
except ImportError:
raise ImportError(
"""
You are attempting ... | null |
141,956 | import textwrap
import json
import typer
from typing import List
from rich import print
from pydantic import BaseModel
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.task import Task
from kaggle_text import kaggle_description
from langroid.agent.tool_message import ToolMessage
from... | null |
141,957 | import os
from typing import List
import fire
from pydantic import BaseModel, Field
import langroid as lr
from langroid.utils.configuration import settings
from langroid.agent.tool_message import ToolMessage
import langroid.language_models as lm
from langroid.agent.chat_document import ChatDocument
DEFAULT_LLM = lm.Ope... | null |
141,958 | import typer
from rich import print
import langroid as lr
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.task import Task
from langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig
from langroid.utils.configuration import set_global, Settings
from langroid.uti... | null |
141,959 | import typer
from rich.prompt import Prompt
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.task import Task
from langroid.agent.tool_message import ToolMessage
from langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig
from langroid.utils.globals import Global... | null |
141,960 | import os
from typing import List
import fire
import langroid as lr
from langroid.language_models.openai_gpt import OpenAICallParams
from langroid.utils.configuration import settings
from langroid.agent.tool_message import ToolMessage
import langroid.language_models as lm
from langroid.agent.chat_document import ChatDo... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.