instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate consistent docstrings
from __future__ import annotations def fizzbuzz(number: int) -> list[int | str]: if number < 1: raise ValueError("n cannot be less than one") if number is None: raise TypeError("n cannot be None") result: list[int | str] = [] for value in range(1, number + 1): if value % 3 ==...
--- +++ @@ -1,8 +1,37 @@+""" +FizzBuzz + +Return an array of numbers from 1 to N, replacing multiples of 3 with 'Fizz', +multiples of 5 with 'Buzz', and multiples of both with 'FizzBuzz'. + +Reference: https://en.wikipedia.org/wiki/Fizz_buzz + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ impor...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/fizzbuzz.py
Improve my code by adding docstrings
from __future__ import annotations import threading import uuid from pathlib import Path from typing import Optional, Sequence, cast from theflow.settings import settings as flowsettings from kotaemon.base import BaseComponent, Document, RetrievedDocument from kotaemon.embeddings import BaseEmbeddings from kotaemon....
--- +++ @@ -19,6 +19,13 @@ class VectorIndexing(BaseIndexing): + """Ingest the document, run through the embedding, and store the embedding in a + vector store. + + This pipeline supports the following set of inputs: + - List of documents + - List of texts + """ cache_dir: Optional[...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/vectorindex.py
Add structured docstrings to improve clarity
from __future__ import annotations def misras_gries(array: list[int], k: int = 2) -> dict[str, int] | None: keys: dict[str, int] = {} for item in array: val = str(item) if val in keys: keys[val] += 1 elif len(keys) < k - 1: keys[val] = 1 else: ...
--- +++ @@ -1,8 +1,39 @@+""" +Misra-Gries Frequency Estimation + +Given a list of items and a value k, returns every item that appears at least +n/k times, where n is the length of the list. Defaults to k=2 (majority +problem). + +Reference: https://en.wikipedia.org/wiki/Misra%E2%80%93Gries_summary + +Complexity: + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/streaming/misra_gries.py
Add well-formatted docstrings
from typing import TYPE_CHECKING, Iterator, Optional, cast from kotaemon.base import BaseMessage, HumanMessage, LLMInterface, Param from .base import ChatLLM if TYPE_CHECKING: from llama_cpp import CreateChatCompletionResponse as CCCR from llama_cpp import Llama class LlamaCppChat(ChatLLM): model_path...
--- +++ @@ -10,6 +10,7 @@ class LlamaCppChat(ChatLLM): + """Wrapper around the llama-cpp-python's Llama model""" model_path: Optional[str] = Param( help="Path to the model file. This is required to load the model.", @@ -51,6 +52,7 @@ @Param.auto() def client_object(self) -> "Llama": + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/chats/llamacpp.py
Create simple docstrings for beginners
from typing import List, Optional from kotaemon.base import BaseComponent, Document, Param from .linear import GatedLinearPipeline class SimpleBranchingPipeline(BaseComponent): branches: List[BaseComponent] = Param(default_callback=lambda *_: []) def add_branch(self, component: BaseComponent): sel...
--- +++ @@ -6,13 +6,70 @@ class SimpleBranchingPipeline(BaseComponent): + """ + A simple branching pipeline for executing multiple branches. + + Attributes: + branches (List[BaseComponent]): The list of branches to be executed. + + Example: + ```python + from kotaemon.llms import ( ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/branching.py
Document functions with detailed explanations
from typing import TYPE_CHECKING, AsyncGenerator, Iterator, Optional, Type from pydantic import BaseModel from theflow.utils.modules import import_dotted_string from kotaemon.base import ( AIMessage, BaseMessage, HumanMessage, LLMInterface, Param, StructuredOutputLLMInterface, ) from .base im...
--- +++ @@ -21,6 +21,14 @@ class BaseChatOpenAI(ChatLLM): + """Base interface for OpenAI chat model, using the openai library + + This class exposes the parameters in resources.Chat. To subclass this class: + + - Implement the `prepare_client` method to return the OpenAI client + - Implement the...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/chats/openai.py
Generate docstrings for script automation
from typing import Any, List, Optional, Union from kotaemon.agents.base import BaseLLM, BaseTool from kotaemon.agents.io import BaseScratchPad from kotaemon.base import BaseComponent from kotaemon.llms import PromptTemplate from .prompt import few_shot_planner_prompt, zero_shot_planner_prompt class Planner(BaseComp...
--- +++ @@ -15,6 +15,13 @@ plugins: List[BaseTool] def _compose_worker_description(self) -> str: + """ + Compose the worker prompt from the workers. + + Example: + toolname1[input]: tool1 description + toolname2[input]: tool2 description + """ prompt = "" ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/rewoo/planner.py
Document all endpoints with docstrings
from __future__ import annotations def atbash(text: str) -> str: translated = "" for char in text: code = ord(char) if char.isalpha(): if char.isupper(): offset = code - ord("A") translated += chr(ord("Z") - offset) elif char.islower(): ...
--- +++ @@ -1,8 +1,32 @@+""" +Atbash Cipher + +Atbash cipher maps each letter of the alphabet to its reverse. +The first letter 'a' maps to 'z', 'b' maps to 'y', and so on. + +Reference: https://en.wikipedia.org/wiki/Atbash + +Complexity: + Time: O(n) where n is the length of the input string + Space: O(n) +""" ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/atbash_cipher.py
Generate docstrings for script automation
from __future__ import annotations import collections def first_switch_pairs(stack: list[int]) -> list[int]: storage_stack: list[int] = [] for _ in range(len(stack)): storage_stack.append(stack.pop()) for _ in range(len(storage_stack)): if len(storage_stack) == 0: break ...
--- +++ @@ -1,3 +1,16 @@+""" +Switch Pairs + +Switch successive pairs of values in a stack starting from the bottom. +If there is an odd number of values, the top element is not moved. +Two approaches: one using an auxiliary stack, one using an auxiliary queue. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstrac...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/switch_pairs.py
Help me add docstrings to my project
from __future__ import annotations def is_valid(s: str) -> bool: stack: list[str] = [] matching = {")": "(", "}": "{", "]": "["} for char in s: if char in matching.values(): stack.append(char) elif char in matching and (not stack or matching[char] != stack.pop()): ...
--- +++ @@ -1,8 +1,34 @@+""" +Valid Parentheses + +Determine if a string containing only '(', ')', '{', '}', '[' and ']' +has valid (properly closed and nested) brackets. + +Reference: https://leetcode.com/problems/valid-parentheses/ + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ import annota...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/valid_parenthesis.py
Generate helpful docstrings for debugging
import requests from kotaemon.base import ( AIMessage, BaseMessage, HumanMessage, LLMInterface, Param, SystemMessage, ) from .base import ChatLLM class EndpointChatLLM(ChatLLM): endpoint_url: str = Param( help="URL of the OpenAI API compatible endpoint", required=True ) ...
--- +++ @@ -13,6 +13,13 @@ class EndpointChatLLM(ChatLLM): + """ + A ChatLLM that uses an endpoint to generate responses. This expects an OpenAI API + compatible endpoint. + + Attributes: + endpoint_url (str): The url of a OpenAI API compatible endpoint. + """ endpoint_url: str = Param(...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/chats/endpoint_based.py
Can you add docstrings to this Python file?
from __future__ import annotations import logging from typing import AsyncGenerator, Iterator from kotaemon.base import BaseMessage, HumanMessage, LLMInterface, Param from .base import ChatLLM logger = logging.getLogger(__name__) class LCChatMixin: def _get_lc_class(self): raise NotImplementedError( ...
--- +++ @@ -11,6 +11,7 @@ class LCChatMixin: + """Mixin for langchain based chat models""" def _get_lc_class(self): raise NotImplementedError( @@ -73,6 +74,15 @@ def invoke( self, messages: str | BaseMessage | list[BaseMessage], **kwargs ) -> LLMInterface: + """Generate r...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/chats/langchain_based.py
Provide clean and structured docstrings
from __future__ import annotations def walls_and_gates(rooms: list[list[int]]) -> None: for i in range(len(rooms)): for j in range(len(rooms[0])): if rooms[i][j] == 0: _dfs(rooms, i, j, 0) def _dfs(rooms: list[list[int]], i: int, j: int, depth: int) -> None: if i < 0 or ...
--- +++ @@ -1,8 +1,29 @@+""" +Walls and Gates + +Fill each empty room (INF) with the distance to its nearest gate (0). +Walls are represented by -1. + +Reference: https://leetcode.com/problems/walls-and-gates/ + +Complexity: + Time: O(M * N) + Space: O(M * N) recursion stack +""" from __future__ import annota...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/walls_and_gates.py
Add docstrings that explain purpose and usage
import logging from typing import Optional from kotaemon.base import LLMInterface from .base import LLM logger = logging.getLogger(__name__) class LCCompletionMixin: def _get_lc_class(self): raise NotImplementedError( "Please return the relevant Langchain class in in _get_lc_class" ...
--- +++ @@ -106,6 +106,7 @@ class OpenAI(LCCompletionMixin, LLM): + """Wrapper around Langchain's OpenAI class, focusing on key parameters""" def __init__( self, @@ -149,6 +150,7 @@ class AzureOpenAI(LCCompletionMixin, LLM): + """Wrapper around Langchain's AzureOpenAI class, focusing on ke...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/completions/langchain_based.py
Replace inline comments with docstrings
from copy import deepcopy from typing import Callable, List from theflow import Function, Node, Param from kotaemon.base import BaseComponent, Document from .chats import LCAzureChatOpenAI from .completions import LLM from .prompts import BasePromptComponent class Thought(BaseComponent): prompt: str = Param( ...
--- +++ @@ -11,6 +11,60 @@ class Thought(BaseComponent): + """A thought in the chain of thought + + - Input: `**kwargs` pairs, where key is the placeholder in the prompt, and + value is the value. + - Output: an output dictionary + + _**Usage:**_ + + Create and run a thought: + + ```python + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/cot.py
Create documentation for each function signature
from typing import Any, Callable, Optional, Union from ..base import BaseComponent from ..base.schema import Document, IO_Type from .chats import ChatLLM from .completions import LLM from .prompts import BasePromptComponent class SimpleLinearPipeline(BaseComponent): prompt: BasePromptComponent llm: Union[Ch...
--- +++ @@ -8,6 +8,42 @@ class SimpleLinearPipeline(BaseComponent): + """ + A simple pipeline for running a function with a prompt, a language model, and an + optional post-processor. + + Attributes: + prompt (BasePromptComponent): The prompt component used to generate the initial + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/linear.py
Write proper docstrings for these functions
from __future__ import annotations def group_anagrams(strings: list[str]) -> list[list[str]]: anagram_map: dict[str, int] = {} groups: list[list[str]] = [] group_index = 0 for word in strings: sorted_word = "".join(sorted(word)) if sorted_word not in anagram_map: anagram_m...
--- +++ @@ -1,8 +1,32 @@+""" +Group Anagrams + +Given an array of strings, group anagrams together. Anagrams are words that +contain the same letters in a different order. + +Reference: https://leetcode.com/problems/group-anagrams/ + +Complexity: + Time: O(n * k log k) where n is the number of strings and k is max ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/group_anagrams.py
Document functions with clear intent
from __future__ import annotations def multiply(num1: str, num2: str) -> str: intermediate: list[int] = [] zero = ord("0") position_i = 1 for digit_i in reversed(num1): position_j = 1 accumulator = 0 for digit_j in reversed(num2): product = ( (ord(d...
--- +++ @@ -1,8 +1,33 @@+""" +Multiply Strings + +Given two non-negative integers represented as strings, return their product +as a string without using built-in BigInteger or direct integer conversion. + +Reference: https://leetcode.com/problems/multiply-strings/ + +Complexity: + Time: O(m * n) where m, n are the...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/multiply_strings.py
Add clean documentation to messy code
from typing import Callable from theflow import Param from kotaemon.base import BaseComponent, Document from .template import PromptTemplate class BasePromptComponent(BaseComponent): class Config: middleware_switches = {"theflow.middleware.CachingMiddleware": False} allow_extra = True tem...
--- +++ @@ -8,6 +8,14 @@ class BasePromptComponent(BaseComponent): + """ + Base class for prompt components. + + Args: + template (PromptTemplate): The prompt template. + **kwargs: Any additional keyword arguments that will be used to populate the + given template. + """ ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/prompts/base.py
Add docstrings for production code
from __future__ import annotations import collections def word_squares(words: list[str]) -> list[list[str]]: word_length = len(words[0]) prefix_map: dict[str, list[str]] = collections.defaultdict(list) for word in words: for index in range(word_length): prefix_map[word[:index]].appen...
--- +++ @@ -1,3 +1,15 @@+""" +Word Squares + +Given a set of words (without duplicates), find all word squares that can be +built from them. A word square reads the same horizontally and vertically. + +Reference: https://leetcode.com/problems/word-squares/ + +Complexity: + Time: O(n * 26^L) where n is the number of...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/word_squares.py
Add docstrings to improve readability
from __future__ import annotations import urllib import urllib.parse from collections import defaultdict def strip_url_params1(url: str, params_to_strip: list[str] | None = None) -> str: if not params_to_strip: params_to_strip = [] if url: result = "" tokens = url.split("?") ...
--- +++ @@ -1,3 +1,15 @@+""" +Strip URL Parameters + +Remove duplicate query string parameters from a URL and optionally remove +specified parameters. Three approaches of increasing Pythonic style. + +Reference: https://en.wikipedia.org/wiki/Query_string + +Complexity: + Time: O(n) where n is the length of the URL ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/strip_url_params.py
Insert docstrings into my code
from __future__ import annotations def repeat_substring(text: str) -> bool: doubled = (text + text)[1:-1] return text in doubled
--- +++ @@ -1,7 +1,31 @@+""" +Repeated Substring Pattern + +Given a non-empty string, check if it can be constructed by taking a +substring of it and appending multiple copies of the substring together. + +Reference: https://leetcode.com/problems/repeated-substring-pattern/ + +Complexity: + Time: O(n) for the strin...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/repeat_substring.py
Create docstrings for each class method
from __future__ import annotations import re def is_valid_coordinates_0(coordinates: str) -> bool: for char in coordinates: if not (char.isdigit() or char in ["-", ".", ",", " "]): return False parts = coordinates.split(", ") if len(parts) != 2: return False try: ...
--- +++ @@ -1,3 +1,15 @@+""" +Validate Coordinates + +Validate if given parameters are valid geographical coordinates. +Latitude must be between -90 and 90, longitude between -180 and 180. + +Reference: https://en.wikipedia.org/wiki/Geographic_coordinate_system + +Complexity: + Time: O(n) where n is the length of t...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/validate_coordinates.py
Add docstrings for better understanding
from __future__ import annotations def check_pangram(input_string: str) -> bool: alphabet = "abcdefghijklmnopqrstuvwxyz" return all(char in input_string.lower() for char in alphabet)
--- +++ @@ -1,7 +1,31 @@+""" +Check Pangram + +Checks whether a given string is a pangram, meaning it contains every +letter of the English alphabet at least once. + +Reference: https://en.wikipedia.org/wiki/Pangram + +Complexity: + Time: O(n) where n is the length of the input string + Space: O(1) +""" from ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/check_pangram.py
Create docstrings for all classes and functions
import warnings from string import Formatter class PromptTemplate: def __init__(self, template: str, ignore_invalid=True): template = template formatter = Formatter() parsed_template = list(formatter.parse(template)) placeholders = set() for _, key, _, _ in parsed_templat...
--- +++ @@ -3,6 +3,9 @@ class PromptTemplate: + """ + Base class for prompt templates. + """ def __init__(self, template: str, ignore_invalid=True): template = template @@ -29,11 +32,37 @@ self.__parsed_template = parsed_template def check_missing_kwargs(self, **kwargs): + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/llms/prompts/template.py
Add structured docstrings to improve clarity
from __future__ import annotations def int_to_roman(num: int) -> str: thousands = ["", "M", "MM", "MMM"] hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "V...
--- +++ @@ -1,8 +1,32 @@+""" +Integer to Roman Numeral + +Given an integer, convert it to a Roman numeral string. Input is guaranteed +to be within the range from 1 to 3999. + +Reference: https://en.wikipedia.org/wiki/Roman_numerals + +Complexity: + Time: O(1) since the input range is bounded + Space: O(1) +""" ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/int_to_roman.py
Add docstrings that explain inputs and outputs
import base64 import os from io import BytesIO from pathlib import Path from typing import Optional from PIL import Image from kotaemon.base import Document, Param from .base import BaseReader from .utils.adobe import generate_single_figure_caption def crop_image(file_path: Path, bbox: list[float], page_number: in...
--- +++ @@ -13,6 +13,16 @@ def crop_image(file_path: Path, bbox: list[float], page_number: int = 0) -> Image.Image: + """Crop the image based on the bounding box + + Args: + file_path (Path): path to the image file + bbox (list[float]): bounding box of the image (in percentage [x0, y0, x1, y1]) ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/azureai_document_intelligence_loader.py
Improve my code by adding docstrings
from __future__ import annotations def strong_password(length: int, password: str) -> int: missing_types = 0 if not any(char.isdigit() for char in password): missing_types += 1 if not any(char.islower() for char in password): missing_types += 1 if not any(char.isupper() for char in pa...
--- +++ @@ -1,8 +1,34 @@+""" +Strong Password Checker + +Given a password string, determine the minimum number of characters that +must be added to make it strong. A strong password has at least 6 characters, +a digit, a lowercase letter, an uppercase letter, and a special character. + +Reference: https://www.hackerran...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/strong_password.py
Add docstrings that explain logic
from __future__ import annotations from collections.abc import Iterator def ladder_length(begin_word: str, end_word: str, word_list: list[str]) -> int: if len(begin_word) != len(end_word): return -1 if begin_word == end_word: return 0 if sum(c1 != c2 for c1, c2 in zip(begin_word, end_w...
--- +++ @@ -1,3 +1,16 @@+""" +Word Ladder (Bidirectional BFS) + +Given two words and a dictionary, find the length of the shortest +transformation sequence where only one letter changes at each step and +every intermediate word must exist in the dictionary. + +Reference: https://leetcode.com/problems/word-ladder/ + +Co...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/word_ladder.py
Add well-formatted docstrings
import logging import os import re from collections import defaultdict from pathlib import Path from typing import Any, Dict, List, Optional from decouple import config from llama_index.core.readers.base import BaseReader from kotaemon.base import Document logger = logging.getLogger(__name__) DEFAULT_VLM_ENDPOINT =...
--- +++ @@ -22,6 +22,22 @@ class AdobeReader(BaseReader): + """Read PDF using the Adobe's PDF Services. + Be able to extract text, table, and figure with high accuracy + + Example: + ```python + >> from kotaemon.loaders import AdobeReader + >> reader = AdobeReader() + >> documen...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/adobe_loader.py
Can you add docstrings to this Python file?
from __future__ import annotations from algorithms.tree.tree import TreeNode def is_symmetric(root: TreeNode | None) -> bool: if root is None: return True return _helper(root.left, root.right) def _helper(p: TreeNode | None, q: TreeNode | None) -> bool: if p is None and q is None: retu...
--- +++ @@ -1,3 +1,15 @@+""" +Symmetric Tree + +Given a binary tree, check whether it is a mirror of itself (i.e., symmetric +around its center). Provides both recursive and iterative solutions. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) +""" from __futur...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/is_symmetric.py
Generate descriptive docstrings automatically
# =============================================================================== # Validate Binary Search Tree # =============================================================================== from algorithms.common.tree_node import TreeNode # Function to validate if a binary tree is a BST def validate_bst(node): ...
--- +++ @@ -1,5 +1,15 @@ # =============================================================================== # Validate Binary Search Tree +""" +To check if the given binary tree is a valid binary search +tree (BST), we need to ensure that: + 1. The left subtree of a node contains only nodes with + keys less th...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/bst_validate_bst.py
Add structured docstrings to improve clarity
from __future__ import annotations def _reverse_list(array: list[str], left: int, right: int) -> None: while left < right: array[left], array[right] = array[right], array[left] left += 1 right -= 1 def reverse_words(string: str) -> str: words = string.strip().split() word_count ...
--- +++ @@ -1,8 +1,27 @@+""" +Reverse Words in a String + +Given a string, reverse the order of words. Leading and trailing spaces +are trimmed and words are separated by single spaces. + +Reference: https://leetcode.com/problems/reverse-words-in-a-string/ + +Complexity: + Time: O(n) where n is the length of the st...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/reverse_words.py
Add docstrings that explain logic
import json import logging import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Literal, NamedTuple, Optional, Union from pydantic import ConfigDict from kotaemon.base import LLMInterface def check_log(): return os.environ.get("LOG_PATH", None) is not None class Agen...
--- +++ @@ -11,10 +11,18 @@ def check_log(): + """ + Checks if logging has been enabled. + :return: True if logging has been enabled, False otherwise. + :rtype: bool + """ return os.environ.get("LOG_PATH", None) is not None class AgentType(Enum): + """ + Enumerated type for agent type...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/io/base.py
Generate docstrings for each module
from __future__ import annotations from collections import deque from algorithms.tree.tree import TreeNode def path_sum(root: TreeNode | None, sum: int) -> list[list[int]]: if root is None: return [] result: list[list[int]] = [] _dfs(root, sum, [], result) return result def _dfs(root: Tre...
--- +++ @@ -1,3 +1,15 @@+""" +Path Sum II + +Given a binary tree and a target sum, find all root-to-leaf paths where each +path's sum equals the given sum. Provides recursive, DFS, and BFS solutions. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) +""" from __...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/path_sum2.py
Fully document this Python code with docstrings
from pathlib import Path from typing import TYPE_CHECKING, Any, List, Type, Union from kotaemon.base import BaseComponent, Document if TYPE_CHECKING: from llama_index.core.readers.base import BaseReader as LIBaseReader class BaseReader(BaseComponent): ... class AutoReader(BaseReader): def __init__(s...
--- +++ @@ -8,13 +8,22 @@ class BaseReader(BaseComponent): + """The base class for all readers""" ... class AutoReader(BaseReader): + """General auto reader for a variety of files. (based on llama-hub)""" def __init__(self, reader_type: Union[str, Type["LIBaseReader"]]) -> None: + ""...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/base.py
Add docstrings including usage examples
import unicodedata from pathlib import Path from typing import List, Optional import pandas as pd from llama_index.core.readers.base import BaseReader from kotaemon.base import Document class DocxReader(BaseReader): def __init__(self, *args, **kwargs): try: import docx # noqa excep...
--- +++ @@ -9,6 +9,14 @@ class DocxReader(BaseReader): + """Read Docx files that respect table, using python-docx library + + Reader behavior: + - All paragraphs are extracted as a Document + - Each table is extracted as a Document, rendered as a CSV string + - The output is a list of Doc...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/docx_loader.py
Help me comply with documentation standards
import base64 from collections import defaultdict from io import BytesIO from pathlib import Path from typing import List, Optional from kotaemon.base import Document, Param from .azureai_document_intelligence_loader import crop_image from .base import BaseReader from .utils.adobe import generate_single_figure_captio...
--- +++ @@ -12,6 +12,7 @@ class DoclingReader(BaseReader): + """Using Docling to extract document structure and content""" _dependencies = ["docling"] @@ -57,6 +58,7 @@ def load_data( self, file_path: str | Path, extra_info: Optional[dict] = None, **kwargs ) -> List[Document]: + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/docling_loader.py
Add docstrings to my Python code
from pathlib import Path from typing import Any, List, Optional, Union from llama_index.core.readers.base import BaseReader from kotaemon.base import Document class PandasExcelReader(BaseReader): def __init__( self, *args: Any, pandas_config: Optional[dict] = None, row_joiner: s...
--- +++ @@ -1,3 +1,8 @@+"""Pandas Excel reader. + +Pandas parser for .xlsx files. + +""" from pathlib import Path from typing import Any, List, Optional, Union @@ -7,6 +12,19 @@ class PandasExcelReader(BaseReader): + r"""Pandas-based CSV parser. + + Parses CSVs using the separator detection from Pandas `r...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/excel_loader.py
Write Python docstrings for this snippet
import base64 from io import BytesIO from pathlib import Path from typing import Dict, List, Optional from decouple import config from fsspec import AbstractFileSystem from llama_index.readers.file import PDFReader from PIL import Image from kotaemon.base import Document PDF_LOADER_DPI = config("PDF_LOADER_DPI", def...
--- +++ @@ -16,6 +16,15 @@ def get_page_thumbnails( file_path: Path, pages: list[int], dpi: int = PDF_LOADER_DPI ) -> List[Image.Image]: + """Get image thumbnails of the pages in the PDF file. + + Args: + file_path (Path): path to the image file + page_number (list[int]): list of page numbers ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/pdf_loader.py
Write docstrings describing functionality
from __future__ import annotations from collections import deque from algorithms.tree.tree import TreeNode def has_path_sum(root: TreeNode | None, sum: int) -> bool: if root is None: return False if root.left is None and root.right is None and root.val == sum: return True sum -= root.va...
--- +++ @@ -1,3 +1,16 @@+""" +Path Sum + +Given a binary tree and a target sum, determine if the tree has a root-to-leaf +path such that adding up all values along the path equals the given sum. +Provides recursive, DFS, and BFS solutions. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/path_sum.py
Write documentation strings for class attributes
import email from pathlib import Path from typing import Optional from llama_index.core.readers.base import BaseReader from theflow.settings import settings as flowsettings from kotaemon.base import Document class HtmlReader(BaseReader): def __init__(self, page_break_pattern: Optional[str] = None, *args, **kwa...
--- +++ @@ -9,6 +9,17 @@ class HtmlReader(BaseReader): + """Reader HTML usimg html2text + + Reader behavior: + - HTML is read with html2text. + - All of the texts will be split by `page_break_pattern` + - Each page is extracted as a Document + - The output is a list of Documents + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/html_loader.py
Auto-generate documentation strings for this file
import logging import os from pathlib import Path from typing import List, Optional from uuid import uuid4 import requests from llama_index.core.readers.base import BaseReader from tenacity import after_log, retry, stop_after_attempt, wait_exponential from kotaemon.base import Document from .utils.pdf_ocr import par...
--- +++ @@ -33,8 +33,26 @@ class OCRReader(BaseReader): + """Read PDF using OCR, with high focus on table extraction + + Example: + ```python + >> from kotaemon.loaders import OCRReader + >> reader = OCRReader() + >> documents = reader.load_data("path/to/pdf") + ``` + + A...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/ocr_loader.py
Add missing documentation to my Python functions
import json import re import time from pathlib import Path from typing import Any, Dict, Generator, List, Optional, Union import requests from langchain.utils import get_from_dict_or_env from llama_index.core.readers.base import BaseReader from kotaemon.base import Document from .utils.table import strip_special_cha...
--- +++ @@ -16,6 +16,7 @@ # MathpixPDFLoader implementation taken largely from Daniel Gross's: # https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21 class MathpixPDFReader(BaseReader): + """Load `PDF` files using `Mathpix` service.""" def __init__( self, @@ -24,6 +25,15 @@ ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/mathpix_loader.py
Document this script properly
from pathlib import Path from typing import Any, Dict, List, Optional from llama_index.core.readers.base import BaseReader from kotaemon.base import Document class UnstructuredReader(BaseReader): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args) # not passing kwargs to par...
--- +++ @@ -1,3 +1,14 @@+"""Unstructured file reader. + +A parser for unstructured text files using Unstructured.io. +Supports .txt, .docx, .pptx, .jpg, .png, .eml, .html, and .pdf documents. + +To use .doc and .xls parser, install + +sudo apt-get install -y libmagic-dev poppler-utils libreoffice +pip install xlrd + +"...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/unstructured_loader.py
Generate consistent documentation across files
# need pip install pdfservices-sdk==2.3.0 import base64 import json import logging import os import tempfile import zipfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import List, Union import pandas as pd from decouple import config from kotaemon.loaders.utils.gpt4v impor...
--- +++ @@ -17,6 +17,15 @@ def request_adobe_service(file_path: str, output_path: str = "") -> str: + """Main function to call the adobe service, and unzip the results. + Args: + file_path (str): path to the pdf file + output_path (str): path to store the results + + Returns: + output_...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/utils/adobe.py
Create Google-style docstrings for my code
import csv from io import StringIO from typing import List, Optional, Tuple from .box import get_rect_iou def check_col_conflicts( col_a: List[str], col_b: List[str], thres: float = 0.15 ) -> bool: num_rows = len([cell for cell in col_a if cell]) assert len(col_a) == len(col_b) conflict_count = 0 ...
--- +++ @@ -8,6 +8,16 @@ def check_col_conflicts( col_a: List[str], col_b: List[str], thres: float = 0.15 ) -> bool: + """Check if 2 columns A and B has non-empty content in the same row + (to be used with merge_cols) + + Args: + col_a: column A (list of str) + col_b: column B (list of str)...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/utils/table.py
Document helper functions with docstrings
from collections import defaultdict from pathlib import Path from typing import Dict, List, Optional, Union from .box import ( bbox_to_points, box_area, box_h, box_w, get_rect_iou, points_to_bbox, scale_box, scale_points, sort_funsd_reading_order, union_points, ) from .table imp...
--- +++ @@ -21,6 +21,15 @@ def read_pdf_unstructured(input_path: Union[Path, str]): + """Convert PDF from specified path to list of text items with + location information + + Args: + input_path: path to input file + + Returns: + Dict page_number: list of text boxes + """ try: ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/utils/pdf_ocr.py
Annotate my code with docstrings
from __future__ import annotations from typing import Optional import requests from kotaemon.base import Document, Param from .base import BaseReranking session = requests.session() class TeiFastReranking(BaseReranking): endpoint_url: str = Param( None, help="TEI Reranking service api base URL", req...
--- +++ @@ -12,6 +12,9 @@ class TeiFastReranking(BaseReranking): + """Text Embeddings Inference (TEI) Reranking model + (https://huggingface.co/docs/text-embeddings-inference/en/index) + """ endpoint_url: str = Param( None, help="TEI Reranking service api base URL", required=True @@ -50,6 +...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/rerankings/tei_fast_rerank.py
Add missing documentation to my Python functions
from typing import List, Tuple def bbox_to_points(box: List[int]): x1, y1, x2, y2 = box return [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] def points_to_bbox(points: List[Tuple[int, int]]): all_x = [p[0] for p in points] all_y = [p[1] for p in points] return [min(all_x), min(all_y), max(all_x), max...
--- +++ @@ -2,21 +2,25 @@ def bbox_to_points(box: List[int]): + """Convert bounding box to list of points""" x1, y1, x2, y2 = box return [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] def points_to_bbox(points: List[Tuple[int, int]]): + """Convert list of points to bounding box""" all_x = [p[0] ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/loaders/utils/box.py
Add docstrings to meet PEP guidelines
from abc import ABC, abstractmethod from typing import List, Optional, Union from kotaemon.base import Document class BaseDocumentStore(ABC): @abstractmethod def __init__(self, *args, **kwargs): ... @abstractmethod def add( self, docs: Union[Document, List[Document]], ...
--- +++ @@ -5,6 +5,7 @@ class BaseDocumentStore(ABC): + """A document store is in charged of storing and managing documents""" @abstractmethod def __init__(self, *args, **kwargs): @@ -17,30 +18,42 @@ ids: Optional[Union[List[str], str]] = None, **kwargs, ): + """Add docum...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/docstores/base.py
Generate consistent docstrings
from typing import List, Optional, Union from kotaemon.base import Document from .base import BaseDocumentStore MAX_DOCS_TO_GET = 10**4 class ElasticsearchDocumentStore(BaseDocumentStore): def __init__( self, collection_name: str = "docstore", elasticsearch_url: str = "http://localhost...
--- +++ @@ -8,6 +8,7 @@ class ElasticsearchDocumentStore(BaseDocumentStore): + """Simple memory document store that store document in a dictionary""" def __init__( self, @@ -66,6 +67,13 @@ refresh_indices: bool = True, **kwargs, ): + """Add document into document stor...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/docstores/elasticsearch.py
Add docstrings to improve readability
from __future__ import annotations from abc import ABC, abstractmethod from typing import Any, Optional from llama_index.core.schema import NodeRelationship, RelatedNodeInfo from llama_index.core.vector_stores.types import BasePydanticVectorStore from llama_index.core.vector_stores.types import VectorStore as LIVecto...
--- +++ @@ -23,10 +23,27 @@ metadatas: Optional[list[dict]] = None, ids: Optional[list[str]] = None, ) -> list[str]: + """Add vector embeddings to vector stores + + Args: + embeddings: List of embeddings + metadatas: List of metadata of the embeddings + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/vectorstores/base.py
Add standardized docstrings across the file
from typing import Any, Dict, List, Optional, Type, cast from llama_index.vector_stores.chroma import ChromaVectorStore as LIChromaVectorStore from .base import LlamaIndexVectorStore class ChromaVectorStore(LlamaIndexVectorStore): _li_class: Type[LIChromaVectorStore] = LIChromaVectorStore def __init__( ...
--- +++ @@ -58,9 +58,16 @@ self._client = cast(LIChromaVectorStore, self._client) def delete(self, ids: List[str], **kwargs): + """Delete vector embeddings from vector stores + + Args: + ids: List of ids of the embeddings to be deleted + kwargs: meant for vectorstore-s...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/vectorstores/chroma.py
Add professional docstrings to my codebase
from pathlib import Path from typing import List, Optional, Union from kotaemon.base import Document from .in_memory import InMemoryDocumentStore class SimpleFileDocumentStore(InMemoryDocumentStore): def __init__(self, path: str | Path, collection_name: str = "default"): super().__init__() self...
--- +++ @@ -7,6 +7,7 @@ class SimpleFileDocumentStore(InMemoryDocumentStore): + """Improve InMemoryDocumentStore by auto saving whenever the corpus is changed""" def __init__(self, path: str | Path, collection_name: str = "default"): super().__init__() @@ -19,6 +20,7 @@ self.load(self...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/docstores/simple_file.py
Generate descriptive docstrings automatically
import json from pathlib import Path from typing import List, Optional, Union from kotaemon.base import Document from .base import BaseDocumentStore class InMemoryDocumentStore(BaseDocumentStore): def __init__(self): self._store = {} def add( self, docs: Union[Document, List[Docume...
--- +++ @@ -8,6 +8,7 @@ class InMemoryDocumentStore(BaseDocumentStore): + """Simple memory document store that store document in a dictionary""" def __init__(self): self._store = {} @@ -18,6 +19,15 @@ ids: Optional[Union[List[str], str]] = None, **kwargs, ): + """Add ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/docstores/in_memory.py
Add docstrings that explain inputs and outputs
import json from typing import List, Optional, Union from kotaemon.base import Document from .base import BaseDocumentStore MAX_DOCS_TO_GET = 10**4 class LanceDBDocumentStore(BaseDocumentStore): def __init__(self, path: str = "lancedb", collection_name: str = "docstore"): try: import lance...
--- +++ @@ -9,6 +9,7 @@ class LanceDBDocumentStore(BaseDocumentStore): + """LancdDB document store which support full-text search query""" def __init__(self, path: str = "lancedb", collection_name: str = "docstore"): try: @@ -29,6 +30,7 @@ refresh_indices: bool = True, **kwargs, ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/docstores/lancedb.py
Document functions with clear intent
from typing import Any, List, Type, cast from llama_index.core.vector_stores.types import MetadataFilters from llama_index.vector_stores.lancedb import LanceDBVectorStore as LILanceDBVectorStore from llama_index.vector_stores.lancedb import base as base_lancedb from .base import LlamaIndexVectorStore # custom monkey...
--- +++ @@ -65,9 +65,16 @@ self._client._metadata_keys = ["file_id"] def delete(self, ids: List[str], **kwargs): + """Delete vector embeddings from vector stores + + Args: + ids: List of ids of the embeddings to be deleted + kwargs: meant for vectorstore-specific param...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/vectorstores/lancedb.py
Document this code for team use
from __future__ import annotations import re from typing import Callable from kotaemon.base import BaseComponent, Document, ExtractorOutput, Param class RegexExtractor(BaseComponent): class Config: middleware_switches = {"theflow.middleware.CachingMiddleware": False} pattern: list[str] output_...
--- +++ @@ -7,6 +7,14 @@ class RegexExtractor(BaseComponent): + """ + Simple class for extracting text from a document using a regex pattern. + + Args: + pattern (List[str]): The regex pattern(s) to use. + output_map (dict, optional): A mapping from extracted text to the + desired ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/parsers/regex_extractor.py
Add docstrings for utility scripts
from __future__ import annotations def polynomial_division( dividend: list[float], divisor: list[float] ) -> tuple[list[float], list[float]]: if not divisor or all(c == 0 for c in divisor): msg = "Cannot divide by zero polynomial" raise ZeroDivisionError(msg) dividend = [float(c) for c in...
--- +++ @@ -1,3 +1,11 @@+"""Polynomial long division. + +Divide polynomial *dividend* by *divisor* and return (quotient, remainder). +Polynomials are represented as lists of coefficients from highest to lowest +degree. E.g. [1, -3, 2] represents x^2 - 3x + 2. + +Inspired by PR #840 (KTH-Software-Engineering-DD2480). +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/polynomial_division.py
Create simple docstrings for beginners
from typing import Any, List, Optional, cast from .base import LlamaIndexVectorStore class QdrantVectorStore(LlamaIndexVectorStore): _li_class = None def _get_li_class(self): try: from llama_index.vector_stores.qdrant import ( QdrantVectorStore as LIQdrantVectorStore, ...
--- +++ @@ -47,6 +47,12 @@ self._client = cast(LIQdrantVectorStore, self._client) def delete(self, ids: List[str], **kwargs): + """Delete vector embeddings from vector stores + + Args: + ids: List of ids of the embeddings to be deleted + kwargs: meant for vectorstore-s...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/vectorstores/qdrant.py
Add clean documentation to messy code
from __future__ import annotations from algorithms.math.gcd import gcd def solve_chinese_remainder(nums: list[int], rems: list[int]) -> int: if not len(nums) == len(rems): raise Exception("nums and rems should have equal length") if not len(nums) > 0: raise Exception("Lists nums and rems nee...
--- +++ @@ -1,3 +1,16 @@+""" +Chinese Remainder Theorem + +Solves a system of simultaneous congruences using the Chinese Remainder +Theorem. Given pairwise coprime moduli, finds the smallest positive integer +satisfying all congruences. + +Reference: https://en.wikipedia.org/wiki/Chinese_remainder_theorem + +Complexity...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/chinese_remainder_theorem.py
Add docstrings for production code
from pathlib import Path from typing import Any, Optional, Type import fsspec from llama_index.core.vector_stores import SimpleVectorStore as LISimpleVectorStore from llama_index.core.vector_stores.simple import SimpleVectorStoreData from kotaemon.base import DocumentWithEmbedding from .base import LlamaIndexVectorS...
--- +++ @@ -1,3 +1,4 @@+"""Simple file vector store index.""" from pathlib import Path from typing import Any, Optional, Type @@ -11,6 +12,7 @@ class SimpleFileVectorStore(LlamaIndexVectorStore): + """Similar to InMemoryVectorStore but is backed by file by default""" _li_class: Type[LISimpleVectorStor...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/vectorstores/simple_file.py
Help me document legacy Python code
import logging from functools import cache from pathlib import Path from typing import Optional from theflow.settings import settings from theflow.utils.modules import deserialize from kotaemon.base import BaseComponent from kotaemon.storages import BaseDocumentStore, BaseVectorStore logger = logging.getLogger(__na...
--- +++ @@ -1,3 +1,4 @@+"""Common components, some kind of config""" import logging from functools import cache @@ -36,6 +37,7 @@ class ModelPool: + """Represent a pool of models""" def __init__(self, category: str, conf: dict): self._category = category @@ -57,23 +59,29 @@ self._cost...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/components.py
Add detailed documentation for each class
from typing import Optional, Type from sqlalchemy import select from sqlalchemy.orm import Session from theflow.settings import settings as flowsettings from theflow.utils.modules import deserialize from kotaemon.embeddings.base import BaseEmbeddings from .db import EmbeddingTable, engine class EmbeddingManager: ...
--- +++ @@ -11,6 +11,7 @@ class EmbeddingManager: + """Represent a pool of models""" def __init__(self): self._models: dict[str, BaseEmbeddings] = {} @@ -34,6 +35,7 @@ self.load_vendors() def load(self): + """Load the model pool from database""" self._models, self._...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/embeddings/manager.py
Add detailed docstrings explaining each function
from typing import Any, Optional, Type import fsspec from llama_index.core.vector_stores import SimpleVectorStore as LISimpleVectorStore from llama_index.core.vector_stores.simple import SimpleVectorStoreData from .base import LlamaIndexVectorStore class InMemoryVectorStore(LlamaIndexVectorStore): _li_class: Ty...
--- +++ @@ -1,3 +1,4 @@+"""Simple vector store index.""" from typing import Any, Optional, Type import fsspec @@ -17,6 +18,7 @@ fs: Optional[fsspec.AbstractFileSystem] = None, **kwargs: Any, ) -> None: + """Initialize params.""" self._data = data or SimpleVectorStoreData() ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/storages/vectorstores/in_memory.py
Create docstrings for reusable components
import datetime import uuid from typing import Optional from sqlalchemy import JSON, Column from sqlmodel import Field, SQLModel from tzlocal import get_localzone class BaseConversation(SQLModel): __table_args__ = {"extend_existing": True} id: str = Field( default_factory=lambda: uuid.uuid4().hex, ...
--- +++ @@ -8,6 +8,16 @@ class BaseConversation(SQLModel): + """Store the chat conversation between the user and the bot + + Attributes: + id: canonical id to identify the conversation + name: human-friendly name of the conversation + user: the user id + data_source: the data sourc...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/db/base_models.py
Generate docstrings for this script
import abc import logging from typing import TYPE_CHECKING, Any, Optional if TYPE_CHECKING: from ktem.app import BasePage from kotaemon.base import BaseComponent logger = logging.getLogger(__name__) class BaseIndex(abc.ABC): def __init__(self, app, id, name, config): self._app = app s...
--- +++ @@ -12,6 +12,46 @@ class BaseIndex(abc.ABC): + """The base class for the index + + The index is responsible for storing information in a searchable manner, and + retrieving that information. + + An application can have multiple indices. For example: + - An index of files locally in the co...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/base.py
Generate docstrings with examples
from pathlib import Path from typing import Generator, Optional from kotaemon.base import BaseComponent, Document, Param class BaseFileIndexRetriever(BaseComponent): Source = Param(help="The SQLAlchemy Source table") Index = Param(help="The SQLAlchemy Index table") VS = Param(help="The VectorStore") ...
--- +++ @@ -15,6 +15,12 @@ @classmethod def get_user_settings(cls) -> dict: + """Get the user settings for indexing + + Returns: + dict: user settings in the dictionary format of + `ktem.settings.SettingItem` + """ return {} @classmethod @@ -28,6...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/base.py
Document functions with detailed explanations
import asyncio import glob import logging import os import re from pathlib import Path from typing import Generator import numpy as np import pandas as pd from ktem.db.models import engine from ktem.embeddings.manager import embedding_models_manager as embeddings from ktem.llms.manager import llms from sqlalchemy.orm ...
--- +++ @@ -235,6 +235,7 @@ class NanoGraphRAGIndexingPipeline(GraphRAGIndexingPipeline): + """GraphRAG specific indexing pipeline""" prompts: dict[str, str] = {} collection_graph_id: str @@ -401,6 +402,7 @@ class NanoGraphRAGRetrieverPipeline(BaseFileIndexRetriever): + """GraphRAG specific re...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/graph/nano_pipelines.py
Help me document legacy Python code
import os import shutil import subprocess from pathlib import Path from shutil import rmtree from typing import Generator from uuid import uuid4 import pandas as pd import tiktoken import yaml from decouple import config from ktem.db.models import engine from sqlalchemy.orm import Session from theflow.settings import ...
--- +++ @@ -64,8 +64,10 @@ class GraphRAGIndexingPipeline(IndexDocumentPipeline): + """GraphRAG specific indexing pipeline""" def route(self, file_path: str | Path) -> IndexPipeline: + """Simply disable the splitter (chunking) for this pipeline""" pipeline = super().route(file_path) ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/graph/pipelines.py
Document functions with clear intent
import os import pickle from pathlib import Path from typing import Any, Dict, List, Type, Union import pandas as pd import yaml from theflow.storage import storage from theflow.utils.modules import import_dotted_string from kotaemon.base import BaseComponent from .logs import ResultLog def from_log_to_dict(pipeli...
--- +++ @@ -1,3 +1,4 @@+"""Export logs into Excel file""" import os import pickle from pathlib import Path @@ -14,6 +15,15 @@ def from_log_to_dict(pipeline_cls: Type[BaseComponent], log_config: dict) -> dict: + """Export the log to panda dataframes + + Args: + pipeline_cls (Type[BaseComponent]): Pip...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/contribs/promptui/export.py
Add concise docstrings to each method
import uuid from datetime import datetime from typing import Any, Optional, Type from ktem.components import filestorage_path, get_docstore, get_vectorstore from ktem.db.engine import engine from ktem.index.base import BaseIndex from sqlalchemy import JSON, Column, DateTime, Integer, String, UniqueConstraint from sqla...
--- +++ @@ -22,6 +22,18 @@ class FileIndex(BaseIndex): + """ + File index to store and allow retrieval of files + + The file index stores files in a local folder and index them for retrieval. + This file index provides the following infrastructure to support the indexing: + - SQL table Source: st...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/index.py
Create structured documentation for my script
from __future__ import annotations def exponential_search(arr: list[int], target: int) -> int: if not arr: return -1 if arr[0] == target: return 0 bound = 1 while bound < len(arr) and arr[bound] <= target: bound *= 2 low = bound // 2 high = min(bound, len(arr) - 1) ...
--- +++ @@ -1,8 +1,19 @@+"""Exponential search — locate an element in a sorted array. + +First finds a range where the target may lie by doubling the index, +then performs binary search within that range. Useful when the target +is near the beginning of a large or unbounded list. + +Time: O(log i) where i is the index ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/exponential_search.py
Add minimal docstrings for each function
from __future__ import annotations import json import logging import shutil import threading import time import warnings from collections import defaultdict from copy import deepcopy from functools import lru_cache from hashlib import sha256 from pathlib import Path from typing import Generator, Optional, Sequence im...
--- +++ @@ -54,6 +54,7 @@ @lru_cache def dev_settings(): + """Retrieve the developer settings from flowsettings.py""" file_extractors = {} if hasattr(settings, "FILE_INDEX_PIPELINE_FILE_EXTRACTORS"): @@ -77,6 +78,18 @@ class DocumentRetrievalPipeline(BaseFileIndexRetriever): + """Retrieve relev...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/pipelines.py
Expand my code with proper documentation strings
import html import json import os import shutil import tempfile import zipfile from copy import deepcopy from pathlib import Path from typing import Generator import gradio as gr import pandas as pd from gradio.data_classes import FileData from gradio.utils import NamedString from ktem.app import BasePage from ktem.db...
--- +++ @@ -76,6 +76,10 @@ class File(gr.File): + """Subclass from gr.File to maintain the original filename + + The issue happens when user uploads file with name like: !@#$%%^&*().pdf + """ def _process_single_file(self, f: FileData) -> NamedString | bytes: file_name = f.path @@ -280,6 +2...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/ui.py
Add docstrings to existing functions
import base64 import json import os from pathlib import Path from typing import Optional, Sequence import requests import yaml from kotaemon.base import RetrievedDocument from kotaemon.indices.rankings import BaseReranking, LLMReranking, LLMTrulensScoring from ..pipelines import BaseFileIndexRetriever, IndexDocument...
--- +++ @@ -14,6 +14,7 @@ class KnetIndexingPipeline(IndexDocumentPipeline): + """Knowledge Network specific indexing pipeline""" # collection name for external indexing call collection_name: str = "default" @@ -32,6 +33,7 @@ } def route(self, file_path: str | Path) -> IndexPipeline: +...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/knet/pipelines.py
Write docstrings including parameters and return values
from __future__ import annotations from typing import Any, AsyncGenerator import anyio from gradio import ChatInterface from gradio.components import Component, get_component_instance from gradio.events import on from gradio.helpers import special_args from gradio.routes import Request class ChatBlock(ChatInterface...
--- +++ @@ -11,6 +11,11 @@ class ChatBlock(ChatInterface): + """The ChatBlock subclasses ChatInterface to provide extra functionalities: + + - Show additional outputs to the chat interface + - Disallow blank user message + """ def __init__( self, @@ -74,11 +79,13 @@ def _display_inpu...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/contribs/promptui/ui/blocks.py
Auto-generate documentation strings for this file
from __future__ import annotations class Node: def __init__(self, x: int) -> None: self.val = x self.next: Node | None = None def merge_two_list(l1: Node | None, l2: Node | None) -> Node | None: sentinel = current = Node(0) while l1 and l2: if l1.val < l2.val: curren...
--- +++ @@ -1,3 +1,15 @@+""" +Merge Two Sorted Lists + +Merge two sorted linked lists into a single sorted list by splicing together +the nodes of the two input lists. + +Reference: https://leetcode.com/problems/merge-two-sorted-lists/ + +Complexity: + Time: O(m + n) + Space: O(1) iterative, O(m + n) recursive +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/merge_two_list.py
Generate helpful docstrings for debugging
from typing import Optional, Type, overload from sqlalchemy import select from sqlalchemy.orm import Session from theflow.settings import settings as flowsettings from theflow.utils.modules import deserialize, import_dotted_string from kotaemon.llms import ChatLLM from .db import LLMTable, engine class LLMManager:...
--- +++ @@ -11,6 +11,7 @@ class LLMManager: + """Represent a pool of models""" def __init__(self): self._models: dict[str, ChatLLM] = {} @@ -36,6 +37,7 @@ self.load_vendors() def load(self): + """Load the model pool from database""" self._models, self._info, self._d...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/llms/manager.py
Add docstrings for utility scripts
import gradio as gr import pandas as pd import yaml from ktem.app import BasePage from ktem.utils.file import YAMLNoDateSafeLoader from .manager import IndexManager # UGLY way to restart gradio server by updating atime def update_current_module_atime(): import os import time # Define the file path f...
--- +++ @@ -108,6 +108,7 @@ self.spec_desc = gr.Markdown(self.spec_desc_default) def _on_app_created(self): + """Called when the app is created""" self._app.app.load( self.list_indices, inputs=[], @@ -221,6 +222,14 @@ ) def on_index_typ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/ui.py
Add docstrings for better understanding
from typing import Optional, Type from ktem.db.models import engine from sqlmodel import Session, select from theflow.settings import settings from theflow.utils.modules import import_dotted_string from .base import BaseIndex from .models import Index class IndexManager: def __init__(self, app): self._...
--- +++ @@ -10,6 +10,15 @@ class IndexManager: + """Manage the application indices + + The index manager is responsible for: + - Managing the range of possible indices and their extensions + - Each actual index built by user + + Attributes: + - indices: list of indices built by user + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/manager.py
Write reusable docstrings
import logging from sqlalchemy import select from sqlalchemy.orm import Session from .db import MCPTable, engine logger = logging.getLogger(__name__) class MCPManager: def __init__(self): self._configs: dict[str, dict] = {} self.load() def load(self): self._info = {} with...
--- +++ @@ -1,79 +1,92 @@- -import logging - -from sqlalchemy import select -from sqlalchemy.orm import Session - -from .db import MCPTable, engine - -logger = logging.getLogger(__name__) - - -class MCPManager: - - def __init__(self): - self._configs: dict[str, dict] = {} - self.load() - - def load(...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/mcp/manager.py
Provide clean and structured docstrings
import asyncio import json import re from copy import deepcopy from typing import Optional import gradio as gr from decouple import config from ktem.app import BasePage from ktem.components import reasonings from ktem.db.models import Conversation, engine from ktem.index.file.ui import File from ktem.reasoning.prompt_...
--- +++ @@ -881,6 +881,7 @@ first_selector_choices, request: gr.Request, ): + """Submit a message to the chatbot""" if KH_DEMO_MODE: sso_user_id = check_rate_limit("chat", request) print("User ID:", sso_user_id) @@ -1083,6 +1084,7 @@ state, ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/pages/chat/__init__.py
Add docstrings including usage examples
import json import logging import gradio as gr import pandas as pd from ktem.app import BasePage from kotaemon.agents.tools.mcp import discover_tools_info, format_tool_list from .manager import mcp_manager logger = logging.getLogger(__name__) TOOLS_DEFAULT = "# Available Tools\n\nSelect or add an MCP server to vie...
--- +++ @@ -1,344 +1,349 @@-import json -import logging - -import gradio as gr -import pandas as pd -from ktem.app import BasePage - -from kotaemon.agents.tools.mcp import discover_tools_info, format_tool_list - -from .manager import mcp_manager - -logger = logging.getLogger(__name__) - -TOOLS_DEFAULT = "# Available To...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/mcp/ui.py
Write docstrings for backend logic
import logging import os from copy import deepcopy import gradio as gr from ktem.app import BasePage from ktem.db.models import Conversation, User, engine from sqlmodel import Session, or_, select import flowsettings from ...utils.conversation import sync_retrieval_n_message from .chat_suggestion import ChatSuggesti...
--- +++ @@ -31,6 +31,7 @@ def is_conv_name_valid(name): + """Check if the conversation name is valid""" errors = [] if len(name) == 0: errors.append("Name cannot be empty") @@ -41,6 +42,7 @@ class ConversationControl(BasePage): + """Manage conversation""" def __init__(self, app):...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/pages/chat/control.py
Add docstrings to improve readability
from typing import Optional from kotaemon.base import BaseComponent class BaseReasoning(BaseComponent): @classmethod def get_info(cls) -> dict: raise NotImplementedError @classmethod def get_user_settings(cls) -> dict: return {} @classmethod def get_pipeline( cls, ...
--- +++ @@ -4,13 +4,32 @@ class BaseReasoning(BaseComponent): + """The reasoning pipeline that handles each of the user chat messages + + This reasoning pipeline has access to: + - the retrievers + - the user settings + - the message + - the conversation id + - the message h...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/reasoning/base.py
Write docstrings including parameters and return values
import hashlib import gradio as gr import pandas as pd from ktem.app import BasePage from ktem.db.models import User, engine from sqlmodel import Session, select from theflow.settings import settings as flowsettings USERNAME_RULE = """**Username rule:** - Username is case-insensitive - Username must be at least 3 ch...
--- +++ @@ -28,6 +28,11 @@ def validate_username(usn): + """Validate that whether username is valid + + Args: + usn (str): Username + """ errors = [] if len(usn) < 3: errors.append("Username must be at least 3 characters long") @@ -44,6 +49,22 @@ def validate_password(pwd, pwd...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/pages/resources/user.py
Add docstrings to my Python code
import logging from ktem.llms.manager import llms from ktem.reasoning.prompt_optimization.rewrite_question import RewriteQuestionPipeline from pydantic import BaseModel, Field from kotaemon.base import Document, HumanMessage, Node, SystemMessage from kotaemon.llms import ChatLLM logger = logging.getLogger(__name__) ...
--- +++ @@ -11,6 +11,7 @@ class SubQuery(BaseModel): + """Search over a database of insurance rulebooks or financial reports""" sub_query: str = Field( ..., @@ -19,6 +20,12 @@ class DecomposeQuestionPipeline(RewriteQuestionPipeline): + """Decompose user complex question into multiple sub-q...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/reasoning/prompt_optimization/decompose_question.py
Can you add docstrings to this Python file?
from typing import Optional, Type from sqlalchemy import select from sqlalchemy.orm import Session from theflow.settings import settings as flowsettings from theflow.utils.modules import deserialize from kotaemon.rerankings.base import BaseReranking from .db import RerankingTable, engine class RerankingManager: ...
--- +++ @@ -11,6 +11,7 @@ class RerankingManager: + """Represent a pool of rerankings models""" def __init__(self): self._models: dict[str, BaseReranking] = {} @@ -34,6 +35,7 @@ self.load_vendors() def load(self): + """Load the model pool from database""" self._mode...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/rerankings/manager.py
Add standardized docstrings across the file
from typing import Any from pydantic import BaseModel, Field class SettingItem(BaseModel): name: str value: Any choices: list = Field(default_factory=list) metadata: dict = Field(default_factory=dict) component: str = "text" special_type: str = "" class BaseSettingGroup(BaseModel): set...
--- +++ @@ -4,6 +4,15 @@ class SettingItem(BaseModel): + """Represent a setting item + + Args: + name: the name of the setting item + value: the default value of the setting item + choices: the list of choices of the setting item, if any + metadata: the metadata of the setting item...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/settings.py
Add return value explanations in docstrings
import hashlib import gradio as gr from ktem.app import BasePage from ktem.components import reasonings from ktem.db.models import Settings, User, engine from sqlmodel import Session, select from theflow.settings import settings as flowsettings KH_SSO_ENABLED = getattr(flowsettings, "KH_SSO_ENABLED", False) signout...
--- +++ @@ -34,6 +34,7 @@ def render_setting_item(setting_item, value): + """Render the setting component into corresponding Gradio UI component""" kwargs = { "label": setting_item.name, "value": value, @@ -56,10 +57,16 @@ class SettingsPage(BasePage): + """Responsible for allowing ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/pages/settings.py
Document this script properly
import yaml class YAMLNoDateSafeLoader(yaml.SafeLoader): @classmethod def remove_implicit_resolver(cls, tag_to_remove): if "yaml_implicit_resolvers" not in cls.__dict__: cls.yaml_implicit_resolvers = cls.yaml_implicit_resolvers.copy() for first_letter, mappings in cls.yaml_implic...
--- +++ @@ -2,9 +2,15 @@ class YAMLNoDateSafeLoader(yaml.SafeLoader): + """Load datetime as strings, not dates""" @classmethod def remove_implicit_resolver(cls, tag_to_remove): + """Remove implicit resolvers for a particular tag + + Args: + tag_to_remove (str): YAML tag to re...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/utils/file.py
Add docstrings to incomplete code
import html import logging from difflib import SequenceMatcher from typing import AnyStr, Generator, Optional, Type from ktem.llms.manager import llms from ktem.mcp.manager import mcp_manager from ktem.reasoning.base import BaseReasoning from ktem.utils.generator import Generator as GeneratorWrapper from ktem.utils.re...
--- +++ @@ -174,6 +174,13 @@ class RewriteQuestionPipeline(BaseComponent): + """Rewrite user question + + Args: + llm: the language model to rewrite question + rewrite_template: the prompt template for llm to paraphrase a text input + lang: the language of the answer. Currently support En...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/reasoning/rewoo.py
Add docstrings including usage examples
import os import markdown from fast_langdetect import detect from kotaemon.base import RetrievedDocument BASE_PATH = os.environ.get("GR_FILE_ROOT_PATH", "") def is_close(val1, val2, tolerance=1e-9): return abs(val1 - val2) <= tolerance def replace_mardown_header(text: str) -> str: textlines = text.splitl...
--- +++ @@ -26,6 +26,7 @@ def get_header(doc: RetrievedDocument) -> str: + """Get the header for the document""" header = "" if "page_label" in doc.metadata: header += f" [Page {doc.metadata['page_label']}]" @@ -35,9 +36,11 @@ class Render: + """Default text rendering into HTML for the ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/utils/render.py
Generate docstrings with parameter types
from typing import List, Tuple import numpy as np import pandas as pd import plotly.graph_objs as go import umap from kotaemon.base import BaseComponent from kotaemon.embeddings import BaseEmbeddings VISUALIZATION_SETTINGS = { "Original Query": {"color": "red", "opacity": 1, "symbol": "cross", "size": 15}, "...
--- +++ @@ -1,3 +1,11 @@+""" +This module aims to project high-dimensional embeddings +into a lower-dimensional space for visualization. + +Refs: +1. [RAGxplorer](https://github.com/gabrielchua/RAGxplorer) +2. [RAGVizExpander](https://github.com/KKenny0/RAGVizExpander) +""" from typing import List, Tuple import num...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/utils/visualize_cited.py
Add docstrings that explain logic
from __future__ import annotations def interpolation_search(array: list[int], search_key: int) -> int: high = len(array) - 1 low = 0 while (low <= high) and (array[low] <= search_key <= array[high]): pos = low + int( ((search_key - array[low]) * (high - low)) / (array[high] - array[l...
--- +++ @@ -1,8 +1,37 @@+""" +Interpolation Search + +Search for a target value in a uniformly distributed sorted array by +estimating the position of the target using linear interpolation. + +Reference: https://en.wikipedia.org/wiki/Interpolation_search + +Complexity: + Time: O(1) best / O(log log n) average / O(n...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/interpolation_search.py
Please document this code using docstrings
import logging import threading from textwrap import dedent from typing import Generator from decouple import config from ktem.embeddings.manager import embedding_models_manager as embeddings from ktem.llms.manager import llms from ktem.reasoning.prompt_optimization import ( DecomposeQuestionPipeline, RewriteQ...
--- +++ @@ -84,6 +84,7 @@ class FullQAPipeline(BaseReasoning): + """Question answering pipeline. Handle from question to answer""" class Config: allow_extra = True @@ -107,6 +108,7 @@ def retrieve( self, message: str, history: list ) -> tuple[list[RetrievedDocument], list[Docume...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/reasoning/simple.py
Write reusable docstrings
from __future__ import annotations def two_sum(numbers: list[int], target: int) -> list[int] | None: for i, number in enumerate(numbers): second_val = target - number low, high = i + 1, len(numbers) - 1 while low <= high: mid = low + (high - low) // 2 if second_val...
--- +++ @@ -1,8 +1,39 @@+""" +Two Sum + +Given a sorted array of integers and a target sum, find the 1-based indices of +the two numbers that add up to the target. Three approaches are provided: +binary search, hash table, and two pointers. + +Reference: https://en.wikipedia.org/wiki/Subset_sum_problem + +Complexity: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/two_sum.py
Help me comply with documentation standards
import importlib import torch.utils.data from torch.utils.data.distributed import DistributedSampler import torch.distributed as dist import os from data.base_dataset import BaseDataset def find_dataset_using_name(dataset_name): dataset_filename = "data." + dataset_name + "_dataset" datasetlib = importlib.im...
--- +++ @@ -1,3 +1,15 @@+"""This package includes all the modules related to data loading and preprocessing + + To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset. + You need to implement four functions: + -- ...
https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/__init__.py